http://stackoverflow.com/comment/85443498
type: AnswerComment
has text: @Ovaflow Well, if you want a list just cast `FreqDist.values()` to list. Please accept my answer if it helped you.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49218753

http://stackoverflow.com/comment/85554948
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49276102
has text: Using `gt` returns an empy list `<QuerySet []>`. And I have setup `TIME_ZONE = 'Asia/Kolkata'` in my django settings.

http://stackoverflow.com/comment/85338439
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49166586
has text: Thank you very much! I have a doubt about what is to be done if the adjective describing the noun happens to be appear before the noun?
score: 1

http://stackoverflow.com/a/49245207
type: Answer
upvote count: 1
has body: The problem is that in shell you have to do each block separately. If you want it to work in shell you are going to have to do: &gt;&gt;&gt; if name == "Doug": print "Hello, D-man!" And then: &gt;&gt;&gt; print "How are you today?" Although I would suggest simply selecting New File from the File menu of IDLE which should open up a new blank window that's called untitled.py. Here you can actually write your code so that it works as: name = "Doug" if name == 'Doug': print "Hello, D-man!" print "How are you today? Whenever you want to run it simply save it to your computer then go to the drop down menu Run and select Run Module or use the shortcut F5 and the file should then run back in the Shell.
score: 1
answers question: http://stackoverflow.com/q/49243913
downvote count: 0

http://stackoverflow.com/comment/85412181
type: QuestionComment
score: 1
has text: What is the overall goal of this script? If you are just looking for `[["a","b"],["c","d","e"]]`, then `list=[];list.append(["a","b"]);list.append(["c","d","e"])` is fine. However, what would be your desired output for your longer and more generic input?
comment on: http://stackoverflow.com/q/49203330
type: Comment

http://stackoverflow.com/comment/85472742
comment on: http://stackoverflow.com/a/49234401
score: 0
type: Comment
has text: Great, can we have the output in this form? l1 = [[1,2,3], [4,5,6]] l2 = [[a,b,c], [d,e,f]]
type: AnswerComment

http://stackoverflow.com/comment/85555451
has text: have you tried providing full path to python executable in cron command. like /usr/bin/python.
comment on: http://stackoverflow.com/q/49276477
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85439199
comment on: http://stackoverflow.com/a/49214674
score: 0
type: AnswerComment
type: Comment
has text: https://drive.google.com/file/d/1EA-DuWEFbzM89x13681cNxB2vLU4jRYi/view?usp=sharing This is the link to the new csv. You can remove the '\n' by using pd.replace('\n', np.nan) and then pd.dropna(inplace = True). Now as you can see there is a column named '0'. The value '1' in the '0'column is repeated. So I want to split the dataframe into smaller dataframes. Do you know how can I do that?

data-visualization
tags question: http://stackoverflow.com/q/49184094
tags question: http://stackoverflow.com/q/49196517
tags question: http://stackoverflow.com/q/49167961
tags question: http://stackoverflow.com/q/49132343
type: Tag
tag name: data-visualization

http://stackoverflow.com/comment/85444049
type: Comment
comment on: http://stackoverflow.com/a/49218753
score: 0
type: AnswerComment
has text: Also you used text as a variable twice, wouldnt that confuse the function?

http://stackoverflow.com/q/49225122
has comment: http://stackoverflow.com/comment/85454326
tagged with: python
tagged with: libtcod
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85454528
has title: Installing libtcod on MacOS for Rougelike
has comment: http://stackoverflow.com/comment/85454457
has comment: http://stackoverflow.com/comment/85455231
answer count: 0
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85453940
has comment: http://stackoverflow.com/comment/89399270
has comment: http://stackoverflow.com/comment/85454878
type: Question
has body: I've been following the Python3 guide on roguebasin (http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python3%2Blibtcod,_part_0) and have gotten stuck during the libtcod installation. I've followed the guide completely and when it comes to the validating libtcod installation, when running the command python -c "import libtcod" I get: (venv:libtcod-build|2.7.13) bash-3.2$ python -c "import libtcod" Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; ImportError: No module named libtcod I'm not sure what I'm doing wrong, or if I've missed any steps. Any ideas on how I can validate that libtcod is installed so I can move on to the next steps of this guide? Thanks EDIT Added in link of the guide I am following
has comment: http://stackoverflow.com/comment/85454300

http://stackoverflow.com/q/49138516
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85282323
accepted answer: http://stackoverflow.com/a/49138559
has body: I have two Python dictionaries - dict1 = {'a' : [1, 2, 3], 'b' : [4, 5, 6], 'c' : [7, 8, 9]} dict2 = {'a' : 30, 'b' : 75, 'c' : 15} I want to sort dict1 based on the values of dict2. The final answer should be something like - [['c', [7, 8, 9]], ['a', [1, 2, 3]], ['b', [4, 5, 6]]] What is the most efficient way to solve this?
possible better answer: http://stackoverflow.com/a/49138594
duplicate of: http://stackoverflow.com/q/1252481
tagged with: python
has answer: http://stackoverflow.com/a/49138554
tagged with: sorting
has title: Sorting dictionary based on another dictionary
has answer: http://stackoverflow.com/a/49138559
tagged with: dictionary
has answer: http://stackoverflow.com/a/49138594
score: 2
upvote count: 4
type: AnsweredQuestion
answer count: 3
has comment: http://stackoverflow.com/comment/85282135
has comment: http://stackoverflow.com/comment/85282130
downvote count: 2
has comment: http://stackoverflow.com/comment/85282100
linked to: http://stackoverflow.com/q/1252481
favorite count: 0
type: Question

http://stackoverflow.com/q/49177228
type: UnansweredQuestion
tagged with: class
score: 0
tagged with: unit-testing
tagged with: testing
has title: good practise to add method to class to check consistency?
has body: I am writing a package which has a lot of complicated indexing for a hierarchical clustering algorithm. I have written unit tests, and in these test I have created a method which checks that some values in the class are consistent with each other. This means I can test if a method breaks it. However, I was wondering if it is good/bad practice to have a method like this defined in the class itself as I haven't seen this before. As requested here is a minimal example. In my application the variables are a matrix of index allocations for the nested clusters, and a list of counters for the nested cluster and an integer counter for the top layer cluster. Counter just means how many are filled, so when it gets to a level I run a method which removes the clusters which have been emptied. class ClassName(object): _variable_one = None _variable_two = None def __init__(self, var1, var2): # set variables self._variable_one = var1 self._variable_two = var2 def _checker(self): # check some relationship between _variable_one and _variable two # and assert it is still true, for example: assert self._variable_one == self._variable_two def do_stuff(self): # perform a method which changes _variable_one and _variable two # check your changes do not 'break' the model self._checker() Thank you for your help.
tagged with: automated-tests
type: Question
has comment: http://stackoverflow.com/comment/85368637
answer count: 0
has comment: http://stackoverflow.com/comment/85409190
has comment: http://stackoverflow.com/comment/85359753
tagged with: python

http://stackoverflow.com/comment/85396417
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49195348
has text: I mean the part in { } should not be disturbed by the program. That shouldn't be removed either.

http://stackoverflow.com/comment/85457991
type: QuestionComment
has text: In this case you cannot use the classifiers. You need other utilities like statistics of each team, win percentage, etc to guide that. Show your data.
score: 0
comment on: http://stackoverflow.com/q/49226358
type: Comment

http://stackoverflow.com/q/49238324
tagged with: character-encoding
has body: When trying to extract text from a pdf using pdfminer, I get the following error: ValueError: unichr() arg not in range(0x110000) (wide Python build) It appears that there is an unrecognized character and that one character is throwing an error before the rest of the text can be extracted. the utf integer is greater than 110000. Most errors of this kind have to do with a narrow Python build, but not in this case. The error appears to be in the name2unicode function in pdfminer: &lt;ipython-input-87-ebcd473faf08&gt; in name2unicode(name) 13 if not m: 14 raise KeyError(name) ---&gt; 15 return unichr(int(m.group(0))) I've found the offending character. Its unicode int that is much larger than the range, and I haven't found a corresponding symbol.
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49238432
has answer: http://stackoverflow.com/a/49238432
answer count: 1
type: Question
tagged with: pdfminer
has title: PDFminer errors out over unrecognized character
tagged with: python

http://stackoverflow.com/comment/85282724
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49138786
score: 3
has text: You should first define perhaps what `order` means in this context.... is is a purely sorted by the full name, or by the numeric part of the name.... Is it by extension first ?... etc

http://stackoverflow.com/comment/85561254
comment on: http://stackoverflow.com/a/49278793
score: 0
type: AnswerComment
has text: You still haven't shown the *full* error, or the index view.
type: Comment

http://stackoverflow.com/comment/85597153
type: QuestionComment
comment on: http://stackoverflow.com/q/49246856
score: 1
has text: @Eliethesaiyan Once you define the custom scorer function, the custom scorer object to be passed to GridSearchCV is generally created as: custom_scorer = make_scorer(custom_scorer_function, greater_is_better=True, extra_arg1=..., extra_arg2=... and so on) with custom scorer function signature then being: def custom_scorer_function(y_true, y_pred, extra_arg1, extra_arg2, ...) So how exactly would you pass the index "i" as "extra arg" into it?
type: Comment

django
tags question: http://stackoverflow.com/q/49230370
tags question: http://stackoverflow.com/q/49124081
tags question: http://stackoverflow.com/q/49124834
tags question: http://stackoverflow.com/q/49208101
tags question: http://stackoverflow.com/q/49268783
tags question: http://stackoverflow.com/q/49160576
tags question: http://stackoverflow.com/q/49168128
tags question: http://stackoverflow.com/q/49150889
tags question: http://stackoverflow.com/q/49138462
tags question: http://stackoverflow.com/q/49162910
tags question: http://stackoverflow.com/q/49275945
tags question: http://stackoverflow.com/q/49254161
tags question: http://stackoverflow.com/q/49146314
tags question: http://stackoverflow.com/q/49217502
tags question: http://stackoverflow.com/q/49208047
tags question: http://stackoverflow.com/q/49150718
tags question: http://stackoverflow.com/q/49262607
tags question: http://stackoverflow.com/q/49140454
tags question: http://stackoverflow.com/q/49137670
tags question: http://stackoverflow.com/q/49183133
tags question: http://stackoverflow.com/q/49244372
tags question: http://stackoverflow.com/q/49209753
tags question: http://stackoverflow.com/q/49189402
tags question: http://stackoverflow.com/q/49150541
tags question: http://stackoverflow.com/q/49235486
tags question: http://stackoverflow.com/q/49256558
tags question: http://stackoverflow.com/q/49200384
tags question: http://stackoverflow.com/q/49196248
tags question: http://stackoverflow.com/q/49246721
tags question: http://stackoverflow.com/q/49209375
tags question: http://stackoverflow.com/q/49194556
tags question: http://stackoverflow.com/q/49164181
tags question: http://stackoverflow.com/q/49276965
tags question: http://stackoverflow.com/q/49201581
tags question: http://stackoverflow.com/q/49267271
tags question: http://stackoverflow.com/q/49188514
tags question: http://stackoverflow.com/q/49160010
tags question: http://stackoverflow.com/q/49205715
tags question: http://stackoverflow.com/q/49272177
tags question: http://stackoverflow.com/q/49153709
tags question: http://stackoverflow.com/q/49129422
tags question: http://stackoverflow.com/q/49263547
tags question: http://stackoverflow.com/q/49141186
tags question: http://stackoverflow.com/q/49131584
tags question: http://stackoverflow.com/q/49161006
tags question: http://stackoverflow.com/q/49170875
tags question: http://stackoverflow.com/q/49196563
tags question: http://stackoverflow.com/q/49134133
tags question: http://stackoverflow.com/q/49172935
tags question: http://stackoverflow.com/q/49230486
tags question: http://stackoverflow.com/q/49181298
tags question: http://stackoverflow.com/q/49195637
tags question: http://stackoverflow.com/q/49225195
tags question: http://stackoverflow.com/q/49177473
tags question: http://stackoverflow.com/q/49187039
tags question: http://stackoverflow.com/q/49206319
tags question: http://stackoverflow.com/q/49128976
tags question: http://stackoverflow.com/q/49264871
tags question: http://stackoverflow.com/q/49132579
tags question: http://stackoverflow.com/q/49137592
tags question: http://stackoverflow.com/q/49220046
tags question: http://stackoverflow.com/q/49233696
tags question: http://stackoverflow.com/q/49145666
tags question: http://stackoverflow.com/q/49194232
tags question: http://stackoverflow.com/q/49168667
tags question: http://stackoverflow.com/q/49157120
tags question: http://stackoverflow.com/q/49158281
tags question: http://stackoverflow.com/q/49142819
tags question: http://stackoverflow.com/q/49141414
tags question: http://stackoverflow.com/q/49273508
tags question: http://stackoverflow.com/q/49195959
tags question: http://stackoverflow.com/q/49273387
tags question: http://stackoverflow.com/q/49166496
tags question: http://stackoverflow.com/q/49190698
tags question: http://stackoverflow.com/q/49205801
tags question: http://stackoverflow.com/q/49121973
tags question: http://stackoverflow.com/q/49121732
tags question: http://stackoverflow.com/q/49121841
tags question: http://stackoverflow.com/q/49168426
tags question: http://stackoverflow.com/q/49221709

http://stackoverflow.com/q/49143117
answer count: 2
tagged with: pyserial
score: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49143336
upvote count: 1
linked to: http://stackoverflow.com/q/16470903
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/92945253
has title: Is it possible to implement pySerial with device responses terminated with a carriage return
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/53015825
linked to: http://stackoverflow.com/q/10222788
tagged with: python
has comment: http://stackoverflow.com/comment/92967364
has body: I have spent a while trying to interpret the solutions found here pySerial 2.6: specify end-of-line in readline() and here Line buffered serial input, but for the life of me I cannot seem to "quickly" communicate with one of my pressure monitors that replies with responses terminated with a carriage return character ('\r') I am able to reliably communicate with the device but it is always limited by the timeout parameter when I define the serial port. I can see that the device is in fact responding with a \r character as displayed using the traditional method. When using the io.TextIOWrapper I get the desired functionality of clipping the termination character, but it still timeouts as the original method. My python code is as follows: import serial,io,timeit cmd = b'#0002UAUX1\r' ser = serial.Serial(port='COM4',baudrate=9600,timeout=1) def readline1(ser): return(ser.readline()) def readline2(ser): sio = io.TextIOWrapper(io.BufferedRWPair(ser,ser,1),newline='\r') return(sio.readline().encode()) def readline3(ser): out = b'' while True: ch = ser.read() out += ch if(ch == b'\r' or ch == b''): break return(out) def timer(func): tic = timeit.default_timer() ser.write(cmd) print(func()) toc = timeit.default_timer() print('%0.2f seconds' % (toc-tic)) for func in (readline1,readline3,readline2): timer(lambda : func(ser)) my shell response is: b'&gt;3.066E-02\r' 1.03 seconds b'&gt;3.066E-02\r' 0.02 seconds b'&gt;3.066E-02\r' 1.06 seconds All methods return the same output, but the readline3 operates much quicker as it does not timeout. I don't understand why it isn't as easy as ser.readline(eol='\r') P.S. I'm quite new to python (heavily dependent on MATLAB) so any and all criticism is appreciated.

http://stackoverflow.com/q/49151170
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85306484
tagged with: numpy
answer count: 2
tagged with: pandas-groupby
downvote count: 0
tagged with: pandas
upvote count: 1
has body: grouping rows in list in pandas groupby i have found question and need to go a step further output required by this question was A [1,2] B [5,5,4] C [6] what I'am trying to achieve is A B C 1 5 6 2 5 4 i have tried using grouped=dataSet.groupby('Column1') df = grouped.aggregate(lambda x: list(x)) output im Stucked with is df.T Column1 A B C [1,2] [5,5,4] [6]
has comment: http://stackoverflow.com/comment/85306689
has answer: http://stackoverflow.com/a/49151244
has answer: http://stackoverflow.com/a/49151309
has title: Group rows in list and transpose pandas
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/22219004
type: UnansweredQuestion

http://stackoverflow.com/comment/85520841
type: Comment
comment on: http://stackoverflow.com/q/49246721
type: QuestionComment
has text: I don't know your requirement or what did you tried till now.
score: 0

http://stackoverflow.com/a/49223444
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85452908
accepted answer of: http://stackoverflow.com/q/49219278
has comment: http://stackoverflow.com/comment/85451439
has comment: http://stackoverflow.com/comment/85453016
type: Answer
has comment: http://stackoverflow.com/comment/85451410
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/85453038
answers question: http://stackoverflow.com/q/49219278
downvote count: 0
has body: A possible solution is to overwrite the paint method of ArrowItem and move the QPainter: import numpy as np from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg class MyArrowItem(pg.ArrowItem): def paint(self, p, *args): p.translate(-self.boundingRect().center()) pg.ArrowItem.paint(self, p, *args) app = QtGui.QApplication([]) w = QtGui.QMainWindow() p = pg.PlotWidget() p.showGrid(x = True, y = True, alpha = 0.3) w.show() w.resize(640, 480) w.setCentralWidget(p) w.setWindowTitle('pyqtgraph example: Arrow') a = pg.ArrowItem(angle=-160, tipAngle=60, headLen=40, tailLen=40, tailWidth=20, pen={'color': 'w', 'width': 3}, brush='r') b = MyArrowItem(angle=-160, tipAngle=60, headLen=40, tailLen=40, tailWidth=20, pen={'color': 'w', 'width': 3}) a.setPos(10,0) b.setPos(10,0) p.addItem(a) p.addItem(b) ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() As shown in the following figure, the red arrow is the default ArrowItem, and the blue is the offset, both are located in the same position with respect to the plot. Update: The problem is caused by the method that rotates the item used as the center of coordinates using the center of transformations by default, that is to say the (0, 0), we must move it: import pyqtgraph as pg import numpy as np import time from pyqtgraph.Qt import QtGui, QtCore from pyqtgraph import functions as fn class CenteredArrowItem(pg.ArrowItem): def setStyle(self, **opts): # http://www.pyqtgraph.org/documentation/_modules/pyqtgraph/graphicsItems/ArrowItem.html#ArrowItem.setStyle self.opts.update(opts) opt = dict([(k,self.opts[k]) for k in ['headLen', 'tipAngle', 'baseAngle', 'tailLen', 'tailWidth']]) tr = QtGui.QTransform() path = fn.makeArrowPath(**opt) tr.rotate(self.opts['angle']) p = -path.boundingRect().center() tr.translate(p.x(), p.y()) self.path = tr.map(path) self.set…

http://stackoverflow.com/comment/85385503
comment on: http://stackoverflow.com/q/49189246
score: 0
has text: There is no broadcast. If you medium.com link - it says this should work. In my case, IIS is talking to Python via Fast CGI.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85260038
comment on: http://stackoverflow.com/q/49127546
type: Comment
has text: Thanks, that makes sense, got it working now :) `inputwords = input('What keywords are you looking for?').split() inputwords.append(inputwords) inputwords = enumerate(inputwords) print (list(inputwords))`
type: QuestionComment
score: 0

http://stackoverflow.com/q/49197002
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49200133
accepted answer: http://stackoverflow.com/a/49200133
has comment: http://stackoverflow.com/comment/85403573
score: -2
has body: I need to make a math operation with variables taken from a: a database b: tkinter entry #Get database number cantidad = IntVar() cursor.execute('''SELECT terneros FROM animales''') cantidad.set(cursor.fetchone()) Then, a tkinter entry: ent_peso = Entry (ventana1, textvariable=peso).grid(row=3, column=2) When I try to make the following operation total = StringVar() total.set(peso*cantidad.get()) messagebox.showinfo("Resultado", "$: "+ total.get()) I get this TypeError: getdouble() argument must be str, not tuple Entire code: peso = IntVar() def calcular(): cantidad = IntVar() cursor.execute('''SELECT terneros FROM animales''') cantidad.set(cursor.fetchone()) total = StringVar() total.set(peso.get()*cantidad.get()) messagebox.showinfo("Resultado", "$: "+ total.get()) ent_peso = Entry (ventana, textvariable=peso).grid(row=3, column=2) but_calc = Button(ventana, text="Calcular", command=calcular).place(x=150,y=115) ventana.mainloop()
tagged with: database
has comment: http://stackoverflow.com/comment/85400744
tagged with: python
type: AnsweredQuestion
upvote count: 0
has title: Tkinter math operation with DB variable
downvote count: 2
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85399756
tagged with: sqlite

http://stackoverflow.com/q/49186091
accepted answer: http://stackoverflow.com/a/49186149
answer count: 4
has title: Range and loops
type: Question
has answer: http://stackoverflow.com/a/49186302
possible better answer: http://stackoverflow.com/a/49186302
score: 2
has answer: http://stackoverflow.com/a/49186162
upvote count: 2
downvote count: 0
has body: Looking for a way to explain something in Python to my students. If we start with number_list = range(100), we can use a for loop such as... for n in number_list: (do something) If we have the same set up, but try to use a while loop, n comes back as undefined. How do I explain that? while n in number_list &lt; 20: (do something) --&gt; n is undefined I guess it is more curious why it's OK in the for loop. I have been harping on them to initialize variables before using them, so why does n work just fine in the for loop?
has answer: http://stackoverflow.com/a/49186149
favorite count: 0
has comment: http://stackoverflow.com/comment/88191255
type: AnsweredQuestion
tagged with: while-loop
has answer: http://stackoverflow.com/a/49186415
tagged with: range
tagged with: python

http://stackoverflow.com/comment/85394284
type: AnswerComment
comment on: http://stackoverflow.com/a/49193975
has text: But it is giving me the same error of 400. As in the documentation Accept header is defined, where i have to put the accept header? and also do i need to put Authorisation also as a header something like.. header={'Accep't: '.........', Authorisation='OAuth'}?
score: 0
type: Comment

http://stackoverflow.com/comment/85260745
comment on: http://stackoverflow.com/a/49126168
type: Comment
score: 0
type: AnswerComment
has text: I made up the colors to more easily lay out the question

http://stackoverflow.com/q/49198057
answer count: 1
tagged with: amazon-web-services
accepted answer: http://stackoverflow.com/a/49201020
type: Question
has answer: http://stackoverflow.com/a/49201020
type: AnsweredQuestion
score: 0
has title: Intentionally Fail Health Check using Route 53 AWS
tagged with: amazon-route53
tagged with: python
has body: I have a query as to whether what I want to achieve is doable, and if so, perhaps someone could give me some advice on how to achieve this. So I have set up a health check on Route 53 for my server, and I have arranged so that if the health check fails, the user will be redirected to a static website I have set up at a backup site. I also have a web scraper running regularly collecting data, and my question is, would their be a way to use the data I have collected, and depending on its value, either pass or fail the heath check, therefore determining what site the user would be diverted to. I have discussed with AWS support and they have said that their policies and conditions are there by design, and long story short would not support what I am trying to achieve. I'm a pretty novice programmer so I'm not sure if it's possible to work this, but this is my final hurdle so any advice or help would be hugely appreciated. Thanks!
tagged with: health-monitoring

http://stackoverflow.com/comment/85477786
has text: Rather than asking how to do it, you should show what you've done on your own, and, if you get stuck, ask for help on specific problems.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49237298
score: 5

http://stackoverflow.com/comment/85541056
score: 0
has text: Can you explain what you're looking for a little more? Are you saying you want to be able to find out which item is missing from each person's wardrobe in the dictionary?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49268613

http://stackoverflow.com/a/49223321
type: Answer
answers question: http://stackoverflow.com/q/49223198
score: 4
upvote count: 4
has body: You can use np.insert(), with a slice to specify the positions: np.insert(x, slice(2, None, 2), ' ')
downvote count: 0

http://stackoverflow.com/comment/85535606
score: 0
comment on: http://stackoverflow.com/a/49265939
type: AnswerComment
has text: I understand. However, the end user when calling `?get_now` will be shown the code related with mocking as well. Is it possible to avoid this behaviour?
type: Comment

http://stackoverflow.com/comment/85334504
comment on: http://stackoverflow.com/q/49164477
type: Comment
type: QuestionComment
score: 0
has text: `Instead, it should be (0, 3) so that I get all tuples in the range of the indexing` Can you please explain what this means?

python
tags question: http://stackoverflow.com/q/49245161
tags question: http://stackoverflow.com/q/49154732
tags question: http://stackoverflow.com/q/49176813
tags question: http://stackoverflow.com/q/49155175
tags question: http://stackoverflow.com/q/49159617
tags question: http://stackoverflow.com/q/49224945
tags question: http://stackoverflow.com/q/49234219
tags question: http://stackoverflow.com/q/49216518
tags question: http://stackoverflow.com/q/49214709
tags question: http://stackoverflow.com/q/49236631
tags question: http://stackoverflow.com/q/49261593
tags question: http://stackoverflow.com/q/49222435
tags question: http://stackoverflow.com/q/49253773
tags question: http://stackoverflow.com/q/49244690
tags question: http://stackoverflow.com/q/49268918
tags question: http://stackoverflow.com/q/49209375
tags question: http://stackoverflow.com/q/49225456
tags question: http://stackoverflow.com/q/49145259
tags question: http://stackoverflow.com/q/49255500
tags question: http://stackoverflow.com/q/49208617
tags question: http://stackoverflow.com/q/49175628
tags question: http://stackoverflow.com/q/49277109
tags question: http://stackoverflow.com/q/49171254
tags question: http://stackoverflow.com/q/49188701
tags question: http://stackoverflow.com/q/49183577
tags question: http://stackoverflow.com/q/49147192
tags question: http://stackoverflow.com/q/49270573
tags question: http://stackoverflow.com/q/49194556
tags question: http://stackoverflow.com/q/49147533
tags question: http://stackoverflow.com/q/49236905
tags question: http://stackoverflow.com/q/49266999
tags question: http://stackoverflow.com/q/49196889
tags question: http://stackoverflow.com/q/49128262
tags question: http://stackoverflow.com/q/49214620
tags question: http://stackoverflow.com/q/49248318
tags question: http://stackoverflow.com/q/49220815
tags question: http://stackoverflow.com/q/49202952
tags question: http://stackoverflow.com/q/49256594
tags question: http://stackoverflow.com/q/49240698
tags question: http://stackoverflow.com/q/49271785
tags question: http://stackoverflow.com/q/49126007
tags question: http://stackoverflow.com/q/49242411
tags question: http://stackoverflow.com/q/49257503
tags question: http://stackoverflow.com/q/49188198
tags question: http://stackoverflow.com/q/49276965
tags question: http://stackoverflow.com/q/49197079
tags question: http://stackoverflow.com/q/49182468
tags question: http://stackoverflow.com/q/49231812
tags question: http://stackoverflow.com/q/49248658
tags question: http://stackoverflow.com/q/49160820
tags question: http://stackoverflow.com/q/49221539
tags question: http://stackoverflow.com/q/49190186
tags question: http://stackoverflow.com/q/49123526
tags question: http://stackoverflow.com/q/49202160
tags question: http://stackoverflow.com/q/49197119
tags question: http://stackoverflow.com/q/49261388
tags question: http://stackoverflow.com/q/49195819
tags question: http://stackoverflow.com/q/49201651
tags question: http://stackoverflow.com/q/49192432
tags question: http://stackoverflow.com/q/49192768
tags question: http://stackoverflow.com/q/49160481
tags question: http://stackoverflow.com/q/49244490
tags question: http://stackoverflow.com/q/49151441
tags question: http://stackoverflow.com/q/49212051
tags question: http://stackoverflow.com/q/49235332
tags question: http://stackoverflow.com/q/49249815
tags question: http://stackoverflow.com/q/49203567
tags question: http://stackoverflow.com/q/49223697
tags question: http://stackoverflow.com/q/49159952
tags question: http://stackoverflow.com/q/49219588
tags question: http://stackoverflow.com/q/49235590
tags question: http://stackoverflow.com/q/49240711
tags question: http://stackoverflow.com/q/49219565
tags question: http://stackoverflow.com/q/49127155
tags question: http://stackoverflow.com/q/49201581
tags question: http://stackoverflow.com/q/49137535
tags question: http://stackoverflow.com/q/49224993
tags question: http://stackoverflow.com/q/49267271
tags question: http://stackoverflow.com/q/49264325
tags question: http://stackoverflow.com/q/49173710

http://stackoverflow.com/q/49155546
has body: This might strike as something very simple, and I too thought it'd be, but it apparently isn't. I must've spent a week trying to make this work, but I for the love of me can't manage to do so. What I need I need to render any given string (only containing standard characters) with any given font (handwritten-like) in Python. The font must be loaded from a TTF file. I also need to be able to accurately detect its borders (get the exact start and end position of the text, vertically and horizontally), preferably before drawing it. Lastly, it'd really make my life easier if the output is an array which I can then keep processing, and not an image file written to disc. What I've tried Imagemagick bindings (namely Wand): Couldn't figure out how to get the text metrics before setting the image size and rendering the text on it. Pango via Pycairo bindings: nearly inexistent documentation, couldn't figure out how to load a TrueType font from a file. PIL (Pillow): The most promising option. I've managed to accurately calculate the height for any text (which surprisingly is not the height getsize returns), but the width seems buggy for some fonts. Not only that, but those fonts with buggy width also get rendered incorrectly. Even when making the image large enough, they get cut off. Here are some examples, with the text "Puzzling": Font: Lovers Quarrel Result: Font: Miss Fajardose Result: This is the code I'm using to generate the images: from PIL import Image, ImageDraw, ImageFont import cv2 import numpy as np import glob import os font_size = 75 font_paths = sorted(glob.glob('./fonts/*.ttf')) text = "Puzzling" background_color = 180 text_color = 50 color_variance = 60 cv2.namedWindow('display', 0) for font_path in font_paths: font = ImageFont.truetype(font_path, font_size) text_width, text_height = font.getsize(text) ascent, descent = font.getmetrics() (width, baseline), (offset_x, offset_y) = font.font.getsize(text) # +100 added to see that text gets cut off PIL_image = Im…
score: 8
linked to: http://stackoverflow.com/q/13821882
has title: Properly render text with a given font in Python and accurately detect its boundaries
answer count: 3
tagged with: fonts
has answer: http://stackoverflow.com/a/76336546
has comment: http://stackoverflow.com/comment/85471426
has comment: http://stackoverflow.com/comment/85471424
downvote count: 0
has comment: http://stackoverflow.com/comment/104630021
linked to: http://stackoverflow.com/q/1933766
has answer: http://stackoverflow.com/a/72615131
linked to: http://stackoverflow.com/q/39556515
possible better answer: http://stackoverflow.com/a/72615131
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 8
has comment: http://stackoverflow.com/comment/85320519
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/49169747
accepted answer: http://stackoverflow.com/a/49169747
has comment: http://stackoverflow.com/comment/85323447
tagged with: python
tagged with: text-rendering
has comment: http://stackoverflow.com/comment/85479975

http://stackoverflow.com/q/49165706
has comment: http://stackoverflow.com/comment/85339710
has comment: http://stackoverflow.com/comment/85366645
has comment: http://stackoverflow.com/comment/85366815
downvote count: 0
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85336981
answer count: 0
has title: Why can't I use an iterative variable in this struct function?
type: UnansweredQuestion
has body: I want to convert every hex value I have to a float and I know that this: while x &lt; 7000: pos.append(struct.unpack('!f', bytes.fromhex(l[x]))[0]) x+=1 works if I use a number instead of x, i.e. l(1) rather than l(x) but when I use this code: df4=pd.read_csv('indexedData.log', low_memory=False) df4 import struct l=df4['3'] pos=[] x=0 while x &lt; 7000: pos.append(struct.unpack('!f', bytes.fromhex(l[x]))[0]) x+=1 pos I get this error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-56-bede8a2bc9a3&gt; in &lt;module&gt;() 8 x=0 9 while x &lt; 7000: ---&gt; 10 pos.append(struct.unpack('!f', bytes.fromhex(l[x]))[0]) 11 x+=1 12 pos ValueError: non-hexadecimal number found in fromhex() arg at position 1
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/85570279
has text: @sanforyou Oh, the first version, I went through all that trouble to split out `base`, and then used `element` instead. Easy fix…
type: AnswerComment
comment on: http://stackoverflow.com/a/49267411
score: 0
type: Comment

http://stackoverflow.com/comment/85261316
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49123943
score: 0
has text: if you want to extract a cell value, you can use the same method, using loc, but instead of `.tolist()` use `.item()`

http://stackoverflow.com/comment/85260632
comment on: http://stackoverflow.com/q/49125105
type: Comment
score: 0
has text: If you have access to the Postfix queue on the server, maybe examine what happened to queue entry 173532000045 but this is no longer a programming question anyway.
type: QuestionComment

http://stackoverflow.com/a/50880662
answers question: http://stackoverflow.com/q/49130108
type: Answer
has body: This modification will give you probabilities for each class given an image. classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu')) classifier.add(MaxPooling2D(pool_size = (2, 2))) classifier.add(Flatten()) classifier.add(Dense(units = 128, activation = 'relu')) classifier.add(Dense(units = 4, activation = 'softmax')) classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy']) Here you need to train with one hot encoding and cross-entropy as the loss function. Then during test time if you pass an image you will be getting an output vector (4 dimensions) each representing the probability of the image belonging to their respective classes. Conversion to one-hot encoding: keras.utils.to_categorical function will help. If you want to do fine-tuning with pre-trained models you can have a look at my repository where I used bottlenecks to accelerate finetuning.
score: 0

http://stackoverflow.com/comment/85415618
type: QuestionComment
score: 0
has text: So, you are re-running `app.run()` in the `while` loop **and** spawning a new process?
comment on: http://stackoverflow.com/q/49205097
type: Comment

http://stackoverflow.com/comment/133832654
score: 0
type: AnswerComment
type: Comment
has text: if I hit Win+R, and type `code` it opens, but if I do `subprocess.run('code')` it fails?
comment on: http://stackoverflow.com/a/49242467

http://stackoverflow.com/q/49160878
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85331395
answer count: 0
tagged with: encoding
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85328594
upvote count: 1
has comment: http://stackoverflow.com/comment/85331596
has comment: http://stackoverflow.com/comment/85331524
has comment: http://stackoverflow.com/comment/85331411
has title: Why is Python3 decode/encode duplicating characters?
has body: I am trying to check the subject of emails in foreign languages for automatic tests. I was having issues with encoding so I decided to try and write something that handles the encoding of the subject. In this case it's given to me in base64. Converting this to utf-8 and then decoding it produces this strange double character problem. Here is some code I used to test this: import base64 ja_str = "こんにちは" encoded_js = base64.b64encode(ja_str.encode()) print (encoded_js) print(base64.b64decode(encoded_js).decode()) The result of the above is: b'44GT44KT44Gr44Gh44Gv' ここんんににちちはは
score: 1
tagged with: base64
tagged with: python
tagged with: utf-8
favorite count: 0
has comment: http://stackoverflow.com/comment/85331553

http://stackoverflow.com/q/49188298
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Scrapy spider not scraping correct div
type: Question
has body: import scrapy class rottenTomatoesSpider(scrapy.Spider): name = "movieList" start_urls = [ 'https://www.rottentomatoes.com/' ] def parse(self, response): for movieList in response.xpath('//div[@id="homepage-opening-this-week"]'): yield { 'score': response.css('td.left_col').extract_first(), 'title': response.css('td.middle_col').extract_first(), 'openingDate': response.css('td.right_col right').extract_first() } So the spider is instead scraping &lt;div id='homepage-tv-top'&gt; I'm assuming it is the homepage- that is confusing the script. Anyone know the workaround?
accepted answer: http://stackoverflow.com/a/49188711
tagged with: rotten-tomatoes
has answer: http://stackoverflow.com/a/49188711
downvote count: 0
answer count: 1
upvote count: 1
tagged with: scrapy

http://stackoverflow.com/a/49254289
type: Answer
score: 4
upvote count: 4
has body: you can create a subclass of your Label and attach the double_tap event to it class MyLabel(Label): def on_touch_down(self, touch): if touch.is_double_tap: demo()
has comment: http://stackoverflow.com/comment/117503041
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49253272
has comment: http://stackoverflow.com/comment/117472108
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49253272
has comment: http://stackoverflow.com/comment/85636322
has comment: http://stackoverflow.com/comment/85588387

http://stackoverflow.com/q/49147961
has comment: http://stackoverflow.com/comment/85304457
has comment: http://stackoverflow.com/comment/85306526
has body: The problem Tensorflow includes the function tf.train.ExponentialMovingAverage which allows us to apply a moving average to the parameters, which I've found to be great to stabilize the testing of the model. With that said, I've found it somewhat irritatingly hard to apply this to general models. My so far most successful approach (shown below) has been to write a function decorator and then put my whole NN inside a function. This does however have several downsides. For one, it duplicates the whole graph, and second, I need to define my NN inside a function. Is there a better way to do this? Current Implementation def ema_wrapper(is_training, decay=0.99): """Use Exponential Moving Average of parameters during testing. Parameters ---------- is_training : bool or `tf.Tensor` of type bool EMA is applied if ``is_training`` is False. decay: Decay rate for `tf.train.ExponentialMovingAverage` """ def function(fun): @functools.wraps(fun) def fun_wrapper(*args, **kwargs): # Regular call with tf.variable_scope('ema_wrapper', reuse=False) as scope: result_train = fun(*args, **kwargs) # Set up exponential moving average ema = tf.train.ExponentialMovingAverage(decay=decay) var_class = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope.name) ema_op = ema.apply(var_class) # Add to collection so they are updated tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, ema_op) # Getter for the variables with EMA applied def ema_getter(getter, name, *args, **kwargs): var = getter(name, *args, **kwargs) ema_var = ema.average(var) return ema_var if ema_var else var # Call with EMA applied with tf.variable_scope('ema_wrapper', reuse=True, custom_getter=ema_getter): result_test = fun(*args, **kwargs) # Return the correct version depending on if we're training or not return tf.cond(is_training, lambda: result_train, lambda: result_test) return fun_wrapper return function Example usage: @ema_wrapper(is_training) def neural_network(x): # If is_training is False, we will use an EMA of a instead…
score: 7
answer count: 1
upvote count: 7
tagged with: tensorflow
favorite count: 0
type: Question
has title: How to use Exponential Moving Average in Tensorflow
type: UnansweredQuestion
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49152088
tagged with: moving-average

http://stackoverflow.com/a/49156943
has body: Based on the answer from abarnert, I created the following run-it-yourself example that demonstrates the behaviour I was trying to understand: from types import ModuleType from importlib import import_module import sys class MyModule(ModuleType): def __del__(self): print('I am being deleted') if __name__ == '__main__': x = import_module('urllib3') x.__class__ = MyModule del x del sys.modules['urllib3'] # Comment this out and urllib3 will NOT be garbage collected before the script finishes print('finishing') Output when run as is: I am being deleted finishing Output with the del sys.modules['urllib3'] line commented out: finishing I am being deleted It is clear that modules are garbage collected as one would expect when all references to them have been deleted, and that unless the module in question is somewhat particular, this occurs when references in the application and in sys.modules have been deleted.
answers question: http://stackoverflow.com/q/49150115
type: Answer
has comment: http://stackoverflow.com/comment/85318659
score: 4
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/49181155
type: UnansweredQuestion
downvote count: 2
tagged with: set
upvote count: 1
tagged with: set-union
favorite count: 0
type: Question
tagged with: tuples
has comment: http://stackoverflow.com/comment/85367880
has body: The trouble I'm having is that these tuples are inside a list of lists of lists as shown below: giantlist = [[[(0,2), (2,3), (4,5)],[(0,2), (3,4), (6,8)], [(3,4),(0,2)]]] So, my issue is trying to traverse through each list and find out if they have tuples in common which I then like to print "found common points between list 1 and list 2". For example: The first list inside the list of lists of lists is [(0,2),(2,3),(4,5)] and it has a common tuple with the second list which is the point [(0,2)] The third list which is shown below also has the common point [(0,2)] [(3,4),(0,2)] I would then like to print list1 has a common point with list2 and list3 I've tried a lot of different loops but I'm having trouble comparing the lists because I cant index them properly. I figured that I could find the intersection between these lists and if they had an intersection then I would print. I also found that maybe I could get the length of each list and then union them and check if the union length is less than the length of the two lists together, that would mean they have a common tuple.
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49181252
has answer: http://stackoverflow.com/a/49181274
tagged with: list
answer count: 2
has title: How to to check if any tuples inside one list are inside another list?

http://stackoverflow.com/comment/85396226
type: QuestionComment
has text: Don't worry about the assertion, this will depend on how to call the code. If you run it as script, `get_xticklabels()` will result in something like ["", "","",""], which is completely expected and has nothing to do with your issue here. Concerning the issue, as said, for me all labels are different, you need to be lucky to find someone who can reproduce your issue to be able to help.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49182468

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/49125894
tags question: http://stackoverflow.com/q/49249664
tags question: http://stackoverflow.com/q/49262092
tags question: http://stackoverflow.com/q/49151878
tags question: http://stackoverflow.com/q/49127773
tags question: http://stackoverflow.com/q/49162937
tags question: http://stackoverflow.com/q/49254161
tags question: http://stackoverflow.com/q/49268210
tags question: http://stackoverflow.com/q/49256558
tags question: http://stackoverflow.com/q/49186323
tags question: http://stackoverflow.com/q/49254839
tags question: http://stackoverflow.com/q/49240478
tags question: http://stackoverflow.com/q/49274862
tags question: http://stackoverflow.com/q/49251100
tags question: http://stackoverflow.com/q/49264618
tags question: http://stackoverflow.com/q/49240364
tags question: http://stackoverflow.com/q/49154643
tags question: http://stackoverflow.com/q/49232693
tags question: http://stackoverflow.com/q/49124081
tags question: http://stackoverflow.com/q/49234772
tags question: http://stackoverflow.com/q/49137508
tags question: http://stackoverflow.com/q/49274563
tags question: http://stackoverflow.com/q/49200384
tags question: http://stackoverflow.com/q/49202160
tags question: http://stackoverflow.com/q/49181602
tags question: http://stackoverflow.com/q/49275868
tags question: http://stackoverflow.com/q/49125925
tags question: http://stackoverflow.com/q/49131265
tags question: http://stackoverflow.com/q/49190698
tags question: http://stackoverflow.com/q/49134786
tags question: http://stackoverflow.com/q/49241246
type: Tag
tags question: http://stackoverflow.com/q/49139506
tags question: http://stackoverflow.com/q/49122666
tags question: http://stackoverflow.com/q/49214241
tags question: http://stackoverflow.com/q/49166529

http://stackoverflow.com/comment/85469891
type: QuestionComment
has text: Well, with a sample data set both vbars and circles work ... I must have missed something. I'll answer as soon as I fix everything ...
score: 0
comment on: http://stackoverflow.com/q/49196517
type: Comment

http://stackoverflow.com/q/49257216
type: Question
has comment: http://stackoverflow.com/comment/85546294
has comment: http://stackoverflow.com/comment/85562838
has title: Extracting Child XML using ElementTree ignoring Namespace
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49282022
tagged with: xml-parsing
score: 1
has answer: http://stackoverflow.com/a/49282022
answer count: 1
has comment: http://stackoverflow.com/comment/85562868
downvote count: 0
has body: I have the following XML that I would like to extract a portion of the child if name matches "Adam" <a:config version="1.0" xmlns:a="uri:abc.com/a" xmlns:b="uri:abc.com/b"> <a:xxx config="ABC"> option_on /123/123 123 </a:xxx> <a:xxx name="Adam"> <a:yyy value="5555-5555"> true </a:yyy> </a:xxx> <a:xxx name="Lisa"> <a:yyy value="2222-2222"> false </a:yyy> </a:xxx> </a:config> I manage to extract the section but it doesn't output the original namespace rather it is showing ns0 and ns1. Below is my code import xml.etree.ElementTree as ET tree2 = ET.parse("mycode.xml") root2= tree2.getroot() for elem in tree2.iter(tag='{uri:abc.com/a}xxx'): match = elem.get('name') if match == "Adam": bla = ET.dump(elem) Output as follows: - <ns0:xxx xmlns:ns0="uri:abc.com/a" name="Adam"> <ns0:yyy value="5555-5555"> true </ns0:yyy> </ns0:xxx> I am hoping to get exactly as what the original document is:- <a:xxx name="Adam"> <a:yyy value="5555-5555"> true </a:yyy> </a:xxx>
upvote count: 1
tagged with: elementtree
favorite count: 0
tagged with: http://stackoverflow.com/tag/xml

http://stackoverflow.com/a/63917277
score: 0
has body: Or if you don't want to add the executable path everytime you want to use the chrome driver, you can just move the chromedriver.exe file to the same current working directory
answers question: http://stackoverflow.com/q/49201281
type: Answer

http://stackoverflow.com/q/49268016
accepted answer: http://stackoverflow.com/a/49271910
has title: Creating a dictionary from 2 lists with duplicate keys
has body: Though I have seen versions of my issue whereby a dictionary was created from two lists (one list with the keys, and the other with the corresponding values), I want to create a dictionary from a list (containing the keys), and 'lists of list' (containing the corresponding values). An example of my code is: #-Creating python dictionary from a list and lists of lists: keys = [18, 34, 30, 30, 18] values = [[7,8,9],[4,5,6],[1,2,3],[10,11,12],[13,14,15]] print "This is example dictionary: " print dictionary The result I expect to get is: {18:[7,8,9],34:[4,5,6],30:[1,2,3],30:[10,11,12],18:[13,14,15]} I do not need the repeated keys (30, 18) to be paired up with their respective values. Instead, I keep getting the following result: {18: [13, 14, 15], 34: [4, 5, 6], 30: [10, 11, 12]} This result is missing two of the elements from my expected list. I am hoping to have some help from this forum.
possible better answer: http://stackoverflow.com/a/49271672
type: AnsweredQuestion
tagged with: python-2.7
tagged with: list
upvote count: 3
score: 3
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49271910
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49271672
downvote count: 0

http://stackoverflow.com/a/49191037
score: 7
type: Answer
accepted answer of: http://stackoverflow.com/q/49190649
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49190649
downvote count: 0
upvote count: 7
has body: If you want to use groupby, the list has to be sorted by the same key you want to group by. &gt;&gt;&gt; lst = [{'a':1}, {'b':2}, {'c':1}, {'d':3}, {'e':2}] &gt;&gt;&gt; keyfunc = lambda d: next(iter(d.values())) &gt;&gt;&gt; sorted(lst, key=keyfunc) [{'a': 1}, {'c': 1}, {'b': 2}, {'e': 2}, {'d': 3}] &gt;&gt;&gt; {k: [x for d in g for x in d] ... for k, g in itertools.groupby(sorted(lst, key=keyfunc), key=keyfunc)} {1: ['a', 'c'], 2: ['b', 'e'], 3: ['d']}

http://stackoverflow.com/q/49122128
possible better answer: http://stackoverflow.com/a/49122479
tagged with: file
has body: The python built-ins open, and file work with context managers in a way that I don't quite understand. It is to my understanding that open will create a file. file implements the context-manager methods __enter__ and __exit__. I would initially expect __enter__ to implement the actual opening of the file descriptor. However, using open outside of a with block will return a file which is already open. So, it appears either file.__init__ or open is actually opening the file descriptor, and as far as I can tell file.__enter__ isn't doing anything. Or maybe file.__init__/open calls file.__enter__ directly? First question: What is the execution-flow of the open built-in? What does open handle, what does file.__init__ handle, and what does file.__enter__ handle? How does this work when re-using one file object for multiple cycles of opening/closing the file? How is this different from re-using other contextmanager objects for multiple context-cycles? Second question: Objects such as file objects have a setup steps and teardown steps. The setup occurs in __init__ , and the tear-down occurs in either close or __exit__. Is this a good design pattern? Should this design pattern be implemented for custom functions/context managers?
has answer: http://stackoverflow.com/a/49122479
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: contextmanager
has title: How does open handle context management?
has comment: http://stackoverflow.com/comment/85250315
tagged with: python
accepted answer: http://stackoverflow.com/a/49122471
tagged with: with-statement
has answer: http://stackoverflow.com/a/49122471
type: Question
score: 2
answer count: 2
has comment: http://stackoverflow.com/comment/85250724
upvote count: 3

http://stackoverflow.com/comment/85420021
score: 0
has text: Thanks a lot for your comments. This has put me on the right track and prevented me from going round in circles.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49207552

http://stackoverflow.com/comment/85437527
has text: That makes sense - The way the statement was parenthesized along with saying you'd post your code, it sounded like you were trying post an image of code, which is something that new users seem prone to do.
comment on: http://stackoverflow.com/q/49216575
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49217228
downvote count: 0
has body: You can using value_counts yourdf=pd.concat([s.nunique(),s.value_counts().to_frame('n').reset_index().groupby('chr').agg(lambda x : ','.join(x.astype(str)))],1) yourdf Out[90]: PI PI n chr 2 3 8,5,6 5,3,2 3 4 9,5,7,4 7,4,2,1 yourdf.columns=['unq_PI','PIs','PI_freq'] yourdf Out[93]: unq_PI PIs PI_freq chr 2 3 8,5,6 5,3,2 3 4 9,5,7,4 7,4,2,1
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49216865
upvote count: 2

http://stackoverflow.com/comment/85426307
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49206880
has text: Another viable approach is non-maximum suppression.
score: 0

http://stackoverflow.com/q/49247670
has comment: http://stackoverflow.com/comment/85500322
linked to: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/85499020
upvote count: 2
tagged with: python
tagged with: variables
duplicate of: http://stackoverflow.com/q/1132941
has comment: http://stackoverflow.com/comment/85499051
possible better answer: http://stackoverflow.com/a/49247688
tagged with: scope
type: AnsweredQuestion
has title: Python variable scope in function definition
has body: I was really surprised by the following Python code def f(x,l=[]): for i in range(x): l.append(i*i) print(l) f(2) #[0, 1] f(3) #[0, 1, 0, 1, 4] The question is why Python uses the same l list, when in function definition is always defined as l=[]
has answer: http://stackoverflow.com/a/49247688
has answer: http://stackoverflow.com/a/49247685
score: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49247685
answer count: 2

http://stackoverflow.com/q/49152901
has title: Loop through multiple tags in Python BeautifulSoup
score: 1
has comment: http://stackoverflow.com/comment/85310937
answer count: 1
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
accepted answer: http://stackoverflow.com/a/49152959
upvote count: 2
has answer: http://stackoverflow.com/a/49152959
has comment: http://stackoverflow.com/comment/85310566
tagged with: python
type: AnsweredQuestion
has body: I am trying to loop through multiple tags in the HTML so I can print all the IDs. My code right now prints only first ID, how can I print the second, third, fourth and so on values. soup = BeautifulSoup(r.content, "html.parser") product_div = soup.find_all('div', {'class': 'valu '}) product_tag = product_div[0].find('a') products = product_tag.attrs['val'] print products

http://stackoverflow.com/q/49155321
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49155861
accepted answer: http://stackoverflow.com/a/49155861
has title: How do I split lines with either of 2 conditions?
tagged with: python
has body: I have a str like: -110-108 -95 -92 -88 -87 -85 -75 -73 -69 -67 -59 -51 -49 -47 -42 -39 -35 -36 -36 -32 -27 -29 -32 I need to split it into a list so that I get all the 24 elements like: ["-110", "-108", "-95" ....] I tried line.split(" ") but this doesn't work as I get the list as: ["-110-108" ...] This is because there is no space between -110 &amp; -108. I tried splitting as line.split("-") but this has 2 problems: The delim is lost, and if there is no negative sign, the whole number is treated as a string. Like: ["-", "110", "-", "95" .... , "5 6 7"] assuming there are positive numbers. How do I split it exactly as the str contains 24 numbers and I need a list with all the 24 numbers as elements with magnitude.
type: Question
upvote count: 2
tagged with: python-3.x
answer count: 2
has answer: http://stackoverflow.com/a/49156257
possible better answer: http://stackoverflow.com/a/49156257
downvote count: 0
favorite count: 0
score: 2

network-programming
tags question: http://stackoverflow.com/q/49170605
tag name: network-programming
tags question: http://stackoverflow.com/q/49208385
tags question: http://stackoverflow.com/q/49272855
tags question: http://stackoverflow.com/q/49132967
tags question: http://stackoverflow.com/q/49222514
tags question: http://stackoverflow.com/q/49190186
tags question: http://stackoverflow.com/q/49178921
tags question: http://stackoverflow.com/q/49223167
tags question: http://stackoverflow.com/q/49246497
type: Tag
tags question: http://stackoverflow.com/q/49210695

http://stackoverflow.com/q/49268743
accepted answer: http://stackoverflow.com/a/53607926
possible better answer: http://stackoverflow.com/a/49283406
has answer: http://stackoverflow.com/a/53607926
tagged with: tensorflow
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49283406
answer count: 2
downvote count: 0
has body: Below is a minimal test case in which I create a variable v which I want to initialize to a value of 777 (for the simplified test case). Note: I can't initialize v with a normal initializer because it depends on a normalization constant computed across all variables (some of which aren't yet created at the time v is created). My solution (below) is to create a boolean variable full_init_cond that I set to True once I've run some initialization/assign OPs once and use tf.cond to ensure they only run the one time. import tensorflow as tf v = tf.Variable(0, trainable=False) full_init_cond = tf.Variable(False, trainable=False, dtype=tf.bool) with tf.control_dependencies([v]): tf.cond( full_init_cond, true_fn=lambda: [tf.no_op], false_fn=lambda: [tf.assign(v, 777), tf.assign(full_init_cond, True)] ) I'm receiving the following error on the tf.cond line: TypeError: Failed to convert object of type &lt;class 'function'&gt; to Tensor. Contents: &lt;function no_op at 0x7f39abf51400&gt;. Consider casting elements to a supported type. I'm not making much sense of this error. Update: To my surprise this simple test seems to produce a valid tensor: tf.cond(full_init_cond, tf.no_op, tf.no_op) Thought this one fails: tf.cond(full_init_cond, lambda: tf.no_op, lambda: tf.no_op) My confusion continues... Tensorflow version 1.5 by the way.
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has title: Tensorflow tf.cond encountering error: TypeError: Failed to convert object of type <class 'function'> to Tensor

cookiecutter
tags question: http://stackoverflow.com/q/49156672
tag name: cookiecutter
type: Tag

http://stackoverflow.com/q/49167472
type: Question
type: UnansweredQuestion
tagged with: scikit-learn
tagged with: python
has body: I am running GridSearchCV function to search for the best alpha (coefficient of regularization term) of a Lasso regression model. When I run the grid search like this, _model = Lasso() param_dict = {'alpha': [1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1]} gsearch = GridSearchCV(_model, param_dict, cv=5, scoring='neg_mean_squared_error', n_jobs=5) the same ConvergenceWarning appear for about 20 times like below. /home/user/.pyenv/versions/anaconda3-4.4.0/lib/python3.6/site-packages/sklearn/linear_model/coordinate_descent.py:491: ConvergenceWarning: Objective did not converge. You might want to increase the number of iterations. Fitting data with very small alpha may cause precision problems. ConvergenceWarning) /home/user/.pyenv/versions/anaconda3-4.4.0/lib/python3.6/site-packages/sklearn/linear_model/coordinate_descent.py:491: ConvergenceWarning: Objective did not converge. You might want to increase the number of iterations. Fitting data with very small alpha may cause precision problems. ConvergenceWarning) /home/user/.pyenv/versions/anaconda3-4.4.0/lib/python3.6/site-packages/sklearn/linear_model/coordinate_descent.py:491: ConvergenceWarning: Objective did not converge. You might want to increase the number of iterations. Fitting data with very small alpha may cause precision problems. ConvergenceWarning) /home/user/.pyenv/versions/anaconda3-4.4.0/lib/python3.6/site-packages/sklearn/linear_model/coordinate_descent.py:491: ConvergenceWarning: Objective did not converge. You might want to increase the number of iterations. Fitting data with very small alpha may cause precision problems. ConvergenceWarning) .... The ConvergenceWarning is important but when it is displayed so many times like this, it's very annoying. Is there any other way to display this ConvergenceWarning only once?
score: 0
answer count: 1
tagged with: warnings
has answer: http://stackoverflow.com/a/49167643
has title: GridSearchCV function gives too much warnings

http://stackoverflow.com/q/49230262
answer count: 2
downvote count: 0
has title: How to count uppercase and lowercase on pandas dataframe
tagged with: string
score: 4
tagged with: text
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85472266
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49230299
tagged with: feature-extraction
possible better answer: http://stackoverflow.com/a/49230476
has answer: http://stackoverflow.com/a/49230299
tagged with: python
has answer: http://stackoverflow.com/a/49230476
has body: Here's my data No Body 1 DaTa Analytics 2 2 StackOver 67 Here's my expected output No Body Uppercase Lowercase 1 DaTa Analytics 2 3 10 2 StackOver 67 2 7
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85463987
upvote count: 4
has comment: http://stackoverflow.com/comment/85464175
has comment: http://stackoverflow.com/comment/85464051

http://stackoverflow.com/comment/85507797
comment on: http://stackoverflow.com/a/49251754
score: 0
type: AnswerComment
has text: I think instead of `subprocess.call` try with `subprocess.Popen`
type: Comment

http://stackoverflow.com/comment/85341404
has text: I decided to check up on your theory that the pixel color might be off. I printed out all the pixels around one of the dots (wid 300 - 400 len: 100-200). Turns out you where right no value was pure 255 red. For all output of pixel color [r,g,b] no value was above 50. This is weird considering while the value may not be 255 for red it should still be higher than 50 on the red spot. Any ideas?
comment on: http://stackoverflow.com/a/49160763
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85360448
comment on: http://stackoverflow.com/q/49175091
score: 0
type: QuestionComment
type: Comment
has text: Haha, well thx I totally overlooked that ;)

http://stackoverflow.com/q/49161120
has answer: http://stackoverflow.com/a/49161313
has answer: http://stackoverflow.com/a/64016190
has answer: http://stackoverflow.com/a/49161189
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49162256
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49162256
has answer: http://stackoverflow.com/a/64686553
has answer: http://stackoverflow.com/a/63146398
accepted answer: http://stackoverflow.com/a/49161313
upvote count: 151
answer count: 10
favorite count: 0
has answer: http://stackoverflow.com/a/76945604
has answer: http://stackoverflow.com/a/68545247
tagged with: conditional-statements
type: Question
has answer: http://stackoverflow.com/a/58767067
has answer: http://stackoverflow.com/a/49162271
tagged with: python
score: 151
has body: I need to set the value of one column based on the value of another in a Pandas dataframe. This is the logic: if df['c1'] == 'Value': df['c2'] = 10 else: df['c2'] = df['c3'] I am unable to get this to do what I want, which is to simply create a column with new values (or change the value of an existing column: either one works for me). If I try to run the code above or if I write it as a function and use the apply method, I get the following: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
has title: Set value of one Pandas column based on value in another column

pyqt
type: Tag
tags question: http://stackoverflow.com/q/49169332
tags question: http://stackoverflow.com/q/49222073
tags question: http://stackoverflow.com/q/49208377
tags question: http://stackoverflow.com/q/49234011
tags question: http://stackoverflow.com/q/49268907
tags question: http://stackoverflow.com/q/49133023
tags question: http://stackoverflow.com/q/49230364
tags question: http://stackoverflow.com/q/49170868
tags question: http://stackoverflow.com/q/49137519
tags question: http://stackoverflow.com/q/49140505
tags question: http://stackoverflow.com/q/49254062
tags question: http://stackoverflow.com/q/49178816
tags question: http://stackoverflow.com/q/49215830
tags question: http://stackoverflow.com/q/49149056
tags question: http://stackoverflow.com/q/49243582
tags question: http://stackoverflow.com/q/49144042
tags question: http://stackoverflow.com/q/49219278
tags question: http://stackoverflow.com/q/49155102
tags question: http://stackoverflow.com/q/49182094
tags question: http://stackoverflow.com/q/49264567
tags question: http://stackoverflow.com/q/49131747
tags question: http://stackoverflow.com/q/49155926
tags question: http://stackoverflow.com/q/49127653
tags question: http://stackoverflow.com/q/49182233
tags question: http://stackoverflow.com/q/49171587
tags question: http://stackoverflow.com/q/49242913
tags question: http://stackoverflow.com/q/49217347
tags question: http://stackoverflow.com/q/49226421
tags question: http://stackoverflow.com/q/49179602
tags question: http://stackoverflow.com/q/49265280
tags question: http://stackoverflow.com/q/49222292
tags question: http://stackoverflow.com/q/49243497
tags question: http://stackoverflow.com/q/49184163
tag name: pyqt
tags question: http://stackoverflow.com/q/49198849
tags question: http://stackoverflow.com/q/49260061
tags question: http://stackoverflow.com/q/49218590
tags question: http://stackoverflow.com/q/49141696
tags question: http://stackoverflow.com/q/49249996
tags question: http://stackoverflow.com/q/49168440
tags question: http://stackoverflow.com/q/49204655
tags question: http://stackoverflow.com/q/49129673
tags question: http://stackoverflow.com/q/49151441
tags question: http://stackoverflow.com/q/49140391
tags question: http://stackoverflow.com/q/49147349
tags question: http://stackoverflow.com/q/49134680
tags question: http://stackoverflow.com/q/49149139
tags question: http://stackoverflow.com/q/49224171
tags question: http://stackoverflow.com/q/49224386

python-datetime
tags question: http://stackoverflow.com/q/49201587
tag name: python-datetime
tags question: http://stackoverflow.com/q/49172824
tags question: http://stackoverflow.com/q/49171911
type: Tag

http://stackoverflow.com/comment/85465013
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49230678
type: Comment
has text: Note that `i == (A or B)` is normally wrong. And should be `i == A or i == B` or `i in (A, B)`.

http://stackoverflow.com/q/49132100
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85268977
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85269058
has comment: http://stackoverflow.com/comment/85269019
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has title: Manipulating a json file in python: change the order of key:value pairs
tagged with: dictionary
type: AnsweredQuestion
has body: I have the follwoing json structure (see here: https://github.com/sebischair/NLU-Evaluation-Corpora/blob/master/AskUbuntuCorpus.json): { "author": "Kristofer", "url": "http://askubuntu.com/questions/226332/how-to-install-a-canon-mf8040cn-printer-on-ubuntu-12-04", "text": "How to Install a Canon MF8040Cn Printer on Ubuntu 12.04", "entities": [ { "text": "Canon MF8040Cn", "entity": "Printer", "stop": 5, "start": 4 }, { "text": "12.04", "entity": "UbuntuVersion", "stop": 11, "start": 9 } ], "intent": "Setup Printer", "answer": { "text": " For 14.04 through 16.04 do the following: \n\n Download the drivers from:\nhttps://www.usa.canon.com/internet/portal/us/home/support/details/printers/black-and-white-laser/mf4770n?tab=drivers#Z7_MQH8HIC0L88RB0AMD0F1Q42K25 \n\n untar it to a directory.\nfrom that directory (assuming 64-bit, adjust as you need to) \n\n cd ~/Downloads\ngunzip -c Linux_UFRII_PrinterDriver_V320_us_EN.tar.gz | tar xvf -\ncd Linux_UFRII_PrinterDriver_V320_us_EN/64-bit_Driver/Debian/\nsudo apt-get -y install libglade2-0 libc6:i386 lib32z1 libxml2:i386 libjpeg62:i386 libstdc++6:i386\ncd 64-bit_Driver/Debian\nsudo dpkg -i *.deb\n \n\n reboot \n\n run add printer .. should just show up automatically when you click the 'Add' button .. give it a few seconds and the printer chirps then just magically shows up. \n\n EDIT 3/2/15 for Vivid (15.04) (I suspect may need for 14.10 as well on brand new installation): \n\n Added extra software dependencies to the above \n\n EDIT 12/18/15 for 15.10 everything worked using above steps. Also, I didn't have to reboot .. it just worked. \n\n EDIT 2/27/16 (16.04beta) Updated the link to the 3.10 driver (they updated their website). Everything just worked using above, didn't need to reboot. \n", "author": "JimB" }, "training": false } So you can load this as a dictionary with json.load. I need to change the order of the key vlaue pairs in the entities-dictionary. Now it is text, entity, stop, start. I want to change the order of e…
has answer: http://stackoverflow.com/a/49152283
has answer: http://stackoverflow.com/a/49132383
possible better answer: http://stackoverflow.com/a/49152283
accepted answer: http://stackoverflow.com/a/49132383

http://stackoverflow.com/q/49178979
has comment: http://stackoverflow.com/comment/85431281
has comment: http://stackoverflow.com/comment/85363603
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85364112
tagged with: text-analysis
downvote count: 0
answer count: 1
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: python-2.5
tagged with: non-english
accepted answer: http://stackoverflow.com/a/49179559
has title: Using a mix of uncommon characters in Python
has answer: http://stackoverflow.com/a/49179559
has comment: http://stackoverflow.com/comment/85368248
tagged with: python
tagged with: character-encoding
has body: I'm working on text analysis in Python, I'm looking at a range of Irish language texts dating from the 6th century to the 14th, which means I have a whole range of orthographic variations to account for when sorting a word list. I want to sort a list which takes into account different grammatical forms of characters (e.g. fada, séimhiú, and úru) from different periods by their core words, so my custom alphabet will look like this: "a, á, b, ḃ, bh, mb, c, ċ, ch, gc, d, ḋ, dh, nd, e, é, f, ḟ, fh, bhf, g, ġ, gh, ng, h, i, í, l, m, ṁ, mh, n, o, ó, p, ṗ, ph, bp, r, rh, s, ṡ, sh, t, ṫ, th, ts, dt, u, ú, j, k, q, v, w, x, y, z" I can probably handle the fada (accented letters) with Unicode encoding, e.g u'á', but I'm struggling to find a way to work with the old style úru (diacritic dot)? Does anyone have experience with this sort of mix of characters? Is there a common way that people have developed to work with these characters? Currently when ever I try to use a diacritic dot charcter with u'ḃ' I get the following error: Traceback (most recent call last): File "csv_generator.py", line 44, in &lt;module&gt; print u'ß©â' File "C:\Users\Charlie\Anaconda2\lib\encodings\cp850.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u1e03' in position 0: character maps to &lt;undefined&gt;

http://stackoverflow.com/q/49198849
has comment: http://stackoverflow.com/comment/85404811
possible better answer: http://stackoverflow.com/a/58826345
upvote count: 4
type: AnsweredQuestion
score: 4
has title: How to remove the divider between widgets when using `statusBar.addPermanentWidget()`?
answer count: 2
has answer: http://stackoverflow.com/a/58826345
tagged with: pyqt
downvote count: 0
has body: Is it possible to remove the divider line between two widgets that were added to the status bar using .addPermanentWidget()? I suspect that it is possible, but I haven't really found any literature on how to proceed. import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QStatusBar, QLabel class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) statusBar = QStatusBar() self.setStatusBar(statusBar) statusBar.addPermanentWidget(QLabel("Label: ")) statusBar.addPermanentWidget(QLabel("Data")) app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_())
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/85405004
has comment: http://stackoverflow.com/comment/85404492
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: qstatusbar
accepted answer: http://stackoverflow.com/a/49200041
has comment: http://stackoverflow.com/comment/85404680
has comment: http://stackoverflow.com/comment/85404323
has answer: http://stackoverflow.com/a/49200041
tagged with: python
has comment: http://stackoverflow.com/comment/85404114

http://stackoverflow.com/q/49224228
type: Question
tagged with: numpy
has title: Numpy: how to insert an (N,) dimensional vector to an (N, M, D) dimensional array as new elements along the D axis? (N, M, D+1)
accepted answer: http://stackoverflow.com/a/49224278
has comment: http://stackoverflow.com/comment/85453722
possible better answer: http://stackoverflow.com/a/49224775
has comment: http://stackoverflow.com/comment/85452059
tagged with: arrays
has answer: http://stackoverflow.com/a/49224278
tagged with: python
has answer: http://stackoverflow.com/a/49224775
type: AnsweredQuestion
answer count: 2
tagged with: array-broadcasting
linked to: http://stackoverflow.com/q/48066662
score: 1
downvote count: 0
upvote count: 1
has body: a is an array of shape (N, M, D) == (20, 4096, 6). b is an array of shape (N,) == (20,). I would like to insert the values of b to a such that each value in b is appended element-wise to the D dim in a (7th element in a). So c would be such an array, of shape (20, 4096, 7), where c[i,:,-1] == b[i] for all i, and c[...,:-1] == a. I know you could just make a new array and add the values accordingly eg: N, M, D = a.shape # (20, 4096, 6) c = np.zeros((N, M, D+1)) c[...,:-1] = a for i in range(N): c[i,:,-1] = b[i] But was wondering if one of the numpy wizards here had a more slick way of doing this with numpy ops and no intermediate arrays.
favorite count: 0

http://stackoverflow.com/a/49136437
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/85277833
accepted answer of: http://stackoverflow.com/q/49135963
has body: This recursive method will scan all directories within a given directory and then print the names of the txt files. I kindly invite you to take it forward. import os def scan_folder(parent): # iterate over all the files in directory 'parent' for file_name in os.listdir(parent): if file_name.endswith(".txt"): # if it's a txt file, print its name (or do whatever you want) print(file_name) else: current_path = "".join((parent, "/", file_name)) if os.path.isdir(current_path): # if we're checking a sub-directory, recursively call this method scan_folder(current_path) scan_folder("/example/path") # Insert parent direcotry's path
upvote count: 5
has comment: http://stackoverflow.com/comment/85277953
type: Answer
answers question: http://stackoverflow.com/q/49135963
has comment: http://stackoverflow.com/comment/85280922
has comment: http://stackoverflow.com/comment/85280610
type: AcceptedAnswer

http://stackoverflow.com/comment/92524635
comment on: http://stackoverflow.com/a/52800517
type: Comment
type: AnswerComment
has text: You should check the model path, the model and the argument that you set. If you are using 0 worker, check the pipeline
score: 0

pandas
tags question: http://stackoverflow.com/q/49144154
tags question: http://stackoverflow.com/q/49179132
tags question: http://stackoverflow.com/q/49188342
tags question: http://stackoverflow.com/q/49132073
tags question: http://stackoverflow.com/q/49177716
tags question: http://stackoverflow.com/q/49162051
tags question: http://stackoverflow.com/q/49234274
tags question: http://stackoverflow.com/q/49185032
tags question: http://stackoverflow.com/q/49207138
tags question: http://stackoverflow.com/q/49209949
tags question: http://stackoverflow.com/q/49216865
tags question: http://stackoverflow.com/q/49243689
tags question: http://stackoverflow.com/q/49194895
tags question: http://stackoverflow.com/q/49233359
tags question: http://stackoverflow.com/q/49252969
tags question: http://stackoverflow.com/q/49156883
tags question: http://stackoverflow.com/q/49183367
tags question: http://stackoverflow.com/q/49233156
tags question: http://stackoverflow.com/q/49177801
tags question: http://stackoverflow.com/q/49157323
tags question: http://stackoverflow.com/q/49142669
tags question: http://stackoverflow.com/q/49240707
tags question: http://stackoverflow.com/q/49217321
tags question: http://stackoverflow.com/q/49154589
tags question: http://stackoverflow.com/q/49207577
tags question: http://stackoverflow.com/q/49132090
tags question: http://stackoverflow.com/q/49188701
tags question: http://stackoverflow.com/q/49271638
tags question: http://stackoverflow.com/q/49223937
tags question: http://stackoverflow.com/q/49248658
tags question: http://stackoverflow.com/q/49183458
tags question: http://stackoverflow.com/q/49181480
tags question: http://stackoverflow.com/q/49279387
tags question: http://stackoverflow.com/q/49223809
tags question: http://stackoverflow.com/q/49180994
tags question: http://stackoverflow.com/q/49226375
tags question: http://stackoverflow.com/q/49169519
tags question: http://stackoverflow.com/q/49241448
tags question: http://stackoverflow.com/q/49135821
tags question: http://stackoverflow.com/q/49261695
tags question: http://stackoverflow.com/q/49278782
tags question: http://stackoverflow.com/q/49245918
tags question: http://stackoverflow.com/q/49239919
tags question: http://stackoverflow.com/q/49205354
tags question: http://stackoverflow.com/q/49279404
tags question: http://stackoverflow.com/q/49188400
tags question: http://stackoverflow.com/q/49214247
tags question: http://stackoverflow.com/q/49245392
tags question: http://stackoverflow.com/q/49209338
tags question: http://stackoverflow.com/q/49134264
tags question: http://stackoverflow.com/q/49236376
tags question: http://stackoverflow.com/q/49244884
tags question: http://stackoverflow.com/q/49274575
tags question: http://stackoverflow.com/q/49192469
tags question: http://stackoverflow.com/q/49207869
tags question: http://stackoverflow.com/q/49128255
tags question: http://stackoverflow.com/q/49173928
tags question: http://stackoverflow.com/q/49254559
tags question: http://stackoverflow.com/q/49259305
tags question: http://stackoverflow.com/q/49164935
tags question: http://stackoverflow.com/q/49163994
tags question: http://stackoverflow.com/q/49242992
tags question: http://stackoverflow.com/q/49200873
tags question: http://stackoverflow.com/q/49279392
tags question: http://stackoverflow.com/q/49199232
tags question: http://stackoverflow.com/q/49242884
tags question: http://stackoverflow.com/q/49276118
tags question: http://stackoverflow.com/q/49263508
tags question: http://stackoverflow.com/q/49254799
tags question: http://stackoverflow.com/q/49215714
tags question: http://stackoverflow.com/q/49237663
tags question: http://stackoverflow.com/q/49228191
tags question: http://stackoverflow.com/q/49277984
tags question: http://stackoverflow.com/q/49214286
tags question: http://stackoverflow.com/q/49156225
tags question: http://stackoverflow.com/q/49245202
tags question: http://stackoverflow.com/q/49185427
tags question: http://stackoverflow.com/q/49139953
tags question: http://stackoverflow.com/q/49275921
tags question: http://stackoverflow.com/q/49254224

http://stackoverflow.com/q/49147829
has comment: http://stackoverflow.com/comment/87157926
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/87157187
has comment: http://stackoverflow.com/comment/87158317
answer count: 2
has comment: http://stackoverflow.com/comment/87168769
downvote count: 0
linked to: http://stackoverflow.com/q/27781993
linked to: http://stackoverflow.com/q/32056387
tagged with: python
has comment: http://stackoverflow.com/comment/87160158
has title: Subprocess, stderr to DEVNULL but errors are printed
accepted answer: http://stackoverflow.com/a/50072485
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/85304521
possible better answer: http://stackoverflow.com/a/50079112
tagged with: mbrola
tagged with: subprocess
has body: I am working on a French chatbot using python. For a first text-to-speech attempt, I am using espeak with mbrola. I call it with subprocess : from subprocess import run, DEVNULL def speak(text): command = ["espeak", "-vmb-fr1", text] run(command, stderr=DEVNULL, stdout=DEVNULL) speak("Bonjour.") As you see, I'm sending stderr and stdout to /dev/null When I run the program, It seems to work, espeak is speaking, but I get this : *** Error in `mbrola': free(): invalid pointer: 0x08e3af18 *** *** Error in `mbrola': free(): invalid pointer: 0x0988af88 *** I think it is a C error in mbrola. I think I can't fix it. But it works, so I just want to mute the error. How can I do ? Is there a way ? Edit, in response to abarnert : When I redirect stdout and stderr by the shell (python myscript.py 2&gt;&amp;1 &gt;/dev/null), the message still show up. distro : Debian 9.3 glibc version : 2.24
has comment: http://stackoverflow.com/comment/87160182
has answer: http://stackoverflow.com/a/50072485
linked to: http://stackoverflow.com/q/4290336
upvote count: 3
has answer: http://stackoverflow.com/a/50079112

http://stackoverflow.com/comment/85312976
score: 0
type: Comment
type: AnswerComment
has text: Where can the data types implementation be found?
comment on: http://stackoverflow.com/a/49154022

http://stackoverflow.com/a/50750312
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49203161
has body: I faced exactly the same issue where I needed to keep previous user answers for a conversation. Take a look at Handler documentation which is a base class for all handlers. It has parameter called pass_user_data. When set to True it passes user_data dictionary to your handler and it's related to the user the update was sent from. You can utilize it to achieve what you are looking for. Let's say I have a conversation with an entry point and two states: def build_conversation_handler(): conversation_handler = ConversationHandler( entry_points=[CommandHandler('command', callback=show_options)], states={ PROCESS_SELECT: [CallbackQueryHandler(process_select, pass_user_data=True)], SOME_OTHER: [MessageHandler(filters=Filters.text, callback=some_other, pass_user_data=True)], }, ) Here are the handlers for the conversation: def show_options(bot, update): button_list = [ [InlineKeyboardButton("Option 1", callback_data="Option 1"), InlineKeyboardButton("Option 2", callback_data="Option 2")]] update.message.reply_text("Here are your options:", reply_markup=InlineKeyboardMarkup(button_list)) return PROCESS_SELECT def process_select(bot, update, user_data): query = update.callback_query selection = query.data # save selection into user data user_data['selection'] = selection return SOME_OTHER def some_other(bot, update, user_data): # here I get my old selection old_selection = user_data['selection'] In the first handler I show user keyboard to choose an option, in the next handler I grab selection from callback query and store it into user data. The last handler is a message handler so it has no callback data, but since I added user_data to it I can access the dictionary with the data that I added previously. With this approach you can store and access anything between the handlers that will be related to a user.
answers question: http://stackoverflow.com/q/49203161
score: 7
upvote count: 7

http://stackoverflow.com/q/49240140
has body: I think I'd better explain what I want to achieve through an example. Supposed I have this dataframe: time 0 2013-01-01 12:56:00 1 2013-01-01 12:00:12 2 2013-01-01 10:34:28 3 2013-01-01 09:34:54 4 2013-01-01 08:34:55 5 2013-01-01 16:35:19 6 2013-01-01 16:35:30 I would like to, given a interval T, count, for each line, how many registers were "opened" in that interval. For example, this would be the output, considering T = 2hours: time count 0 2013-01-01 12:56:00 1 # 12:56-2 = 10:56 -&gt; 1 register between [10:56, 12:56) 1 2013-01-01 12:00:12 1 2 2013-01-01 10:34:28 2 # 10:34:28-2 = 8:34:28 -&gt; 2 registers between [8:34:28, 10:34:28) 3 2013-01-01 09:34:54 1 4 2013-01-01 08:34:55 0 5 2013-01-01 16:35:19 0 6 2013-01-01 16:35:30 1 I wonder how to obtain this result using pandas. If I was considering just the dt.hour acessor, for T equals 1, for example, I could create a column count per hour, and than shift it by 1, summing the result of count[i] + count[i-1]. But I don't know if can generalize this for the desired ouput.
has answer: http://stackoverflow.com/a/49241171
tagged with: python
has comment: http://stackoverflow.com/comment/85484902
type: AnsweredQuestion
tagged with: pandas
tagged with: sql
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85484196
type: Question
has title: Count number of registers in interval
tagged with: time-series
has comment: http://stackoverflow.com/comment/85484138
accepted answer: http://stackoverflow.com/a/49241171

http://stackoverflow.com/comment/85437225
type: Comment
comment on: http://stackoverflow.com/a/49213331
score: 0
type: AnswerComment
has text: So this is an important information which you need to add in your question in a more descriptive way.

http://stackoverflow.com/comment/85345953
has text: I found out since im using MAMP, I had to go in there and use it's mysql. Which is working fine from terminal, but how can I connect my PyMySQL to MAMP's mysql? is this even possible? do you know @thebjorn?
comment on: http://stackoverflow.com/q/49168374
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/49249043
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: tree
tagged with: recursion
type: UnansweredQuestion
has body: I am trying to create a tree with the different possible states of the well-known sliding puzzle In case you don't know it, it's the one like: [3 5 2] [4 1] [8 6 7] Where you have to make it like this: [1 2 3] [4 5 6] [7 8 ] Basically, every state generates new states, depending on how the blank space can be moved (upwards, downwards, to the left, or to the right) What I want is to create the tree with all states given the root as the initial state of the puzzle, but when adding children (new states) to the tree, it should check that that state is not added already anywhere in the tree Would you mind helping me achieve that? Thanks in advance :) Here's my current code which throws RecursionError: maximum recursion depth exceeded while calling a Python object Node class: class Node(object): def __init__(self, value, parent=None): self.parent = parent self.value = value self.children = [] def append(self, obj): if obj is not self.parent and obj not in self.children and obj is not None: self.children.append(obj) def has_children(self): return len(self.children) &gt; 0 def __iter__(self): yield self.value for v in chain(*map(iter, self.children)): yield v def find_root(self): p = self while p.parent is not None: p = p.parent return p Tree generation method (consider self as a puzzle state): def to_tree(self, parent=None): values = [] if parent is not None: for child in parent.find_root(): values.append(child) value = nd.Node(self, parent) if value not in values: children = [move[1].to_tree(value) for move in self.get_possible_movements()] for child in children: if child is not None: value.append(child) return value else: return None
tagged with: python
score: 6
has comment: http://stackoverflow.com/comment/85501660
upvote count: 6
answer count: 2
has answer: http://stackoverflow.com/a/49337828
has comment: http://stackoverflow.com/comment/85501679
tagged with: sliding-tile-puzzle
downvote count: 0
has title: Creating a tree without duplicates
has comment: http://stackoverflow.com/comment/85501763
has answer: http://stackoverflow.com/a/49249686

http://stackoverflow.com/comment/85427278
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49211320
has text: If you want to use tkinter you can use the code that Stack posted (which is maybe a bit more fastforward than using pyqt). To run the command you can use your own function instead of the `print('user input: ...')` in the callback handler. I will give an example by editing my answer.

http://stackoverflow.com/q/49201341
downvote count: 0
favorite count: 0
has body: Goal I'm trying to get DEAP to parallelize across a spark cluster. I have seen this referenced by other users, as it allows for tight integration with existing server architecture easily via yarn. I have followed several tutorials online cited in the references. I have working code for deap, and then code that I have attempted to transform to use spark. The same error 'Can't get attribute Individual on module deap.creator' is the one to usually occur. Working Code import numpy as np import random from deap import base from deap import creator from deap import tools from deap import algorithms creator.create("FitnessMax", base.Fitness, weights=(1.0,)) creator.create("Individual", list, fitness=creator.FitnessMax) def evalOneMax(individual): return sum(individual), toolbox = base.Toolbox() toolbox.register("attr_bool", random.randint, 0, 1) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 100) toolbox.register("population", tools.initRepeat, list, toolbox.individual) toolbox.register("evaluate", evalOneMax) toolbox.register("mate", tools.cxTwoPoint) toolbox.register("mutate", tools.mutFlipBit, indpb=0.05) toolbox.register("select", tools.selTournament, tournsize=3) # Define parallelism outside main if __name__=="__main__": pop = toolbox.population(n=300) hof = tools.HallOfFame(1) stats = tools.Statistics(lambda ind: ind.fitness.values) stats.register("avg", np.mean) stats.register("std", np.std) stats.register("min", np.min) stats.register("max", np.max) pop, log = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=40, stats=stats, halloffame=hof, verbose=True) Ran: python3 test-deap.py Output gen nevals avg std min max 0 300 50.5533 4.78893 38 63 1 184 54.2433 3.85627 44 65 2 191 57.2667 3.38756 47 65 3 182 60.0333 3.15154 51 69 4 179 62.35 2.95762 53 71 5 176 64.3267 2.77968 55 73 6 183 66.2467 2.80223 58 75 7 182 68.1733 2.66019 59 79 8 186 69.8367 2.83255 62 77 9 179 71.7233 2.70557 59 78 10 187 73.3667 2.63165 63 80…
type: Question
upvote count: 2
tagged with: deap
tagged with: python
type: UnansweredQuestion
has title: Spark + Deap Examples Not Working
linked to: http://stackoverflow.com/q/45607035
tagged with: apache-spark
score: 2
tagged with: genetic-algorithm
answer count: 0

http://stackoverflow.com/comment/85323395
comment on: http://stackoverflow.com/q/49155698
score: 0
has text: If you want speed improvements, don't use `vectorize`. Figure out instead how to write `inside` so with works with the `a` kind of 3d array directly.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49137073
score: 12
has comment: http://stackoverflow.com/comment/85279716
answers question: http://stackoverflow.com/q/49137031
upvote count: 12
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49137031
has comment: http://stackoverflow.com/comment/85279607
type: Answer
has body: This should generalise pretty easily. You'll need groupby + transform + count, and then filter the result: col = 'poo' # 'bar' n = 3 # 2 df[df.groupby(col)[col].transform('count').ge(n)] foo bar poo 0 1 a A 1 2 a A 2 3 a B 3 4 b B 4 5 b A 5 6 b A 7 8 d B 8 9 e B

http://stackoverflow.com/comment/85434826
type: Comment
has text: I am not exactly sure what python does when it sees `_, name = k`, but it looks like you can easily 'parse out' the coordinates of a tuple.
type: AnswerComment
comment on: http://stackoverflow.com/a/49212052
score: 0

http://stackoverflow.com/a/49143776
downvote count: 1
answers question: http://stackoverflow.com/q/49143628
type: Answer
has body: Your code is also comparing the guess to i. Let's follow it through the loop: first guess = 50; i = 1 second guess = 25; i = 2 third guess = 12.5; i = 3 At this point, the guess stops being an integer and it won't ever match. You should probably be defining the number it is guessing first, or by setting it to a random number try: import random answer = random.randint(1,100)
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85337551

http://stackoverflow.com/a/65523707
upvote count: 1
score: 1
type: Answer
has body: To overcome error you may change datetime.date(1, 1, 1) to more greater values like datetime.date(2, 2, 2) but if you edit Time column for example note that your date in this column is artificial 2, 2, 2 or something
answers question: http://stackoverflow.com/q/49263547
downvote count: 0

http://stackoverflow.com/comment/109233023
score: 0
type: Comment
has text: Also this takes care of any possible duplicates that could be present in the given list.
comment on: http://stackoverflow.com/a/49225759
type: AnswerComment

http://stackoverflow.com/a/49241361
has comment: http://stackoverflow.com/comment/121753483
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/98349116
has comment: http://stackoverflow.com/comment/85486471
has body: Separate your dataframe by articletype and then try storing all your predicted values in a dictionary def get_prediction(df): prediction = {} df = df.rename(columns={'Date of the document': 'ds','Quantity sold': 'y', 'Article bar code': 'article'}) list_articles = df2.article.unique() for article in list_articles: article_df = df2.loc[df2['article'] == article] # set the uncertainty interval to 95% (the Prophet default is 80%) my_model = Prophet(weekly_seasonality= True, daily_seasonality=True,seasonality_prior_scale=1.0) my_model.fit(article_df) future_dates = my_model.make_future_dataframe(periods=6, freq='MS') forecast = my_model.predict(future_dates) prediction[article] = forecast return prediction now the prediction will have forecasts for each type of article.
accepted answer of: http://stackoverflow.com/q/49237785
score: 5
answers question: http://stackoverflow.com/q/49237785
upvote count: 5
type: Answer

http://stackoverflow.com/comment/85473630
comment on: http://stackoverflow.com/q/49235092
type: Comment
score: 1
type: QuestionComment
has text: I think its something to do with your system setup as I am running the same example and its working fine

http://stackoverflow.com/q/49188323
possible better answer: http://stackoverflow.com/a/49188388
answer count: 3
has body: Currently, i have a list and a table both containing: data = [97,89,43] table = [[1, 97],[2, 89],[3, 102],[4, 12],[5, 43]] and i want to print the values in data together with the first column value associated in the table. Output: 1 : 97 2 : 89 5 : 43 I have attempted: n = len(data) #having some problems here for k in range(n): # loop 3 times for j in range(n): # loop 3 times if table[j][1] == data[k]: print( str(table[j][0]+ ':' + " " + str(data[k])) but the issue I'm facing now is that if i take n = len(data) the loop would only loop 3 times and it won't be able to loop further on until the rest of the elements in the table is scanned, giving me only: 1 : 97 2 : 89 #error message, index out of range What modification could i do in order to achieve the output desired?
has answer: http://stackoverflow.com/a/49188422
type: Question
accepted answer: http://stackoverflow.com/a/49188422
has answer: http://stackoverflow.com/a/49188417
tagged with: python
has title: Printing between association of a list and a table
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49188388

http://stackoverflow.com/comment/85377171
has text: @cᴏʟᴅsᴘᴇᴇᴅ sounds good
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49185754
type: QuestionComment

http://stackoverflow.com/comment/85512669
score: 0
type: Comment
has text: apologies for the delay. The error I get is "ValueError: Shape must be rank 0 but is rank 1 for 'limit' for 'range' (op: 'Range') with input shapes: [], [?], []." when I assign idx.
type: AnswerComment
comment on: http://stackoverflow.com/a/49241596

http://stackoverflow.com/comment/85431303
type: AnswerComment
comment on: http://stackoverflow.com/a/49212898
score: 0
type: Comment
has text: I am getting only files with data in f1, f2 and f10

http://stackoverflow.com/comment/85356630
comment on: http://stackoverflow.com/a/49164059
score: 0
type: Comment
type: AnswerComment
has text: j.click() ge, screen, stacktrace) selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed

http://stackoverflow.com/q/49171412
has comment: http://stackoverflow.com/comment/85347885
has comment: http://stackoverflow.com/comment/85348427
type: Question
has comment: http://stackoverflow.com/comment/85348747
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85349005
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has body: A is a 2D Matrix of say dimensions n X m. B is a matrix of dimensions n X 1 , with each element in B a vstack of dimensions p X 1. How would A[ B &lt;= 0] = 0 work in Python3 ?
has comment: http://stackoverflow.com/comment/85348742
has title: How does A[ B <= 0 ] = 0 work, when A and B are 2D matrices in Python3?
favorite count: 0
tagged with: numpy

http://stackoverflow.com/q/49240119
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has title: How to establish remote desktop connection between windows machine using Paramiko, Python
score: 0
linked to: http://stackoverflow.com/q/18961213
tagged with: windows
tagged with: ssh
tagged with: python
tagged with: paramiko
has answer: http://stackoverflow.com/a/49243196
linked to: http://stackoverflow.com/q/42796765
tagged with: remote-desktop
has body: I am trying establish remote desktop connection from a windows machine to other windows machine and have tried below scenarios - import paramiko ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('IP',port = 3389, username='un',password='pwd') print ("Connected to %s" % 'IP') stdin, stdout, stderr = ssh.exec_command('ls -1 /root|head -n 5') print ("STDOUT:\n%s\n\nSTDERR:\n%s\n" %( stdout.read(), stderr.read() )) Upon running above code i observed below error message paramiko.ssh_exception.SSHException: Error reading SSH protocol banner[WinError 10054] An existing connection was forcibly closed by the remote host Looked at this quetsion - python connecting to ssh An existing connection was forcibly closed by the remote host But, I haven't closed the connection in my code and still face the exception. I looked at some forums and understood that for windows machine 3389 is the port for remote desktop connection and so used 3389 as port in my code. I have also used port=22, ran the code and observed this exception: paramiko.ssh_exception.NoValidConnectionsError: [Errno None] Unable to connect to port 22 on IP I have also tried few - How to connect to a remote Windows machine to execute commands? procedures stated here to make remote desktop connection. But couldn't establish the connection. versions: paramiko: 2.4.0 python: 3.6.4
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/85523436
comment on: http://stackoverflow.com/a/49220514
has text: OK, then my answer is right. You can use fields, filters and group by filters on the search views. You want to remove the filters. I have added a filter to my example: `<filter name="draft_filter" domain="[('state', '=', 'draft')]"/>`. You can create a new search view without the filters and add it to the action as my second solution or you can modify the original search view by inheritance and remove the filter elements: `<filter name="draft_filter" position="replace" />`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49184438
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49184201
downvote count: 0
has body: If you print(is_filled = (df.isnull() &amp; df_filled.notnull()) | df.notnull()) then you will see that you have a mixture of True and NaN. So the solution is to replace the NaN values with False: The bottom snippet of code: df=df.drop('date',1) is_filled = (df.isnull() &amp; df_filled.notnull()) | df.notnull() is_filled = is_filled.fillna(False) # Fix here df_filled[is_filled]=df_filled[is_filled].applymap(lambda x: '_2D' if pd.notnull(x) else np.nan)
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49184201

dbpedia
tags question: http://stackoverflow.com/q/49133915
tags question: http://stackoverflow.com/q/49254957
type: Tag
tag name: dbpedia

package
tags question: http://stackoverflow.com/q/49211183
tags question: http://stackoverflow.com/q/49134506
tag name: package
type: Tag
tags question: http://stackoverflow.com/q/49248838
tags question: http://stackoverflow.com/q/49231322
tags question: http://stackoverflow.com/q/49157566
tags question: http://stackoverflow.com/q/49244280
tags question: http://stackoverflow.com/q/49146556

http://stackoverflow.com/comment/85405885
type: Comment
comment on: http://stackoverflow.com/a/49198865
type: AnswerComment
has text: @N8_Coder, can you explain bit more? Why do you want to use it in different scripts?
score: 0

http://stackoverflow.com/comment/85287254
score: 0
comment on: http://stackoverflow.com/q/49140663
type: Comment
type: QuestionComment
has text: so you'll need 1000/20 queries and each one increments by 20, make sense?

http://stackoverflow.com/q/49226874
has answer: http://stackoverflow.com/a/49226904
score: 1
has comment: http://stackoverflow.com/comment/85496148
tagged with: repeat
tagged with: python
has comment: http://stackoverflow.com/comment/85457663
possible better answer: http://stackoverflow.com/a/49226904
type: AnsweredQuestion
tagged with: list
answer count: 2
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85457545
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49226896
accepted answer: http://stackoverflow.com/a/49226896
has body: New to python with limited prior programming experience, I'm trying to create a card game as a learning vehicle. The first step is to deal cards. I know there are many ways to do this including creating card objects and deal methods. That will come later. For now, I want to randomly generate suites and numbers, concatenate the values into a string and append the element in a list. As the cards are dealt, the newly generated element will be compared against what's already in the list to see if it's a repeat. If it is, then regenerate the element. I'm having trouble checking the element as I'm adding the element to the list. Everything I found on this topic has been checking the list against a static known value. I want to dynamically check the element against what's already in the list as new elements are added to the list. Below is what I have so far. Any help is much appreciated! import random player_count =int(input('Welcome! How many players? ')) for i in range (player_count): x = random.randint(1,13) y = random.choice(['-Spade','-Heart','-Diamond','-Club']) card_set =[str(x) + y] if card_set not in card_set: card_set.append print(card_set)
has title: How to check element as you append element in python list?

http://stackoverflow.com/comment/85365977
comment on: http://stackoverflow.com/q/49180006
score: 0
has text: You may want to read [this Q&A](https://stackoverflow.com/questions/23628325/cv2-imread-checking-if-image-is-being-read) as well. Things sometimes fail in the real world, you have to write your software to account for that possibility.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52448736
upvote count: 4
answers question: http://stackoverflow.com/q/49247310
downvote count: 0
has body: In my case the problem had to do with virtual environments. The python program ran in a virtual environment, but I called pip install Pillow from a normal command prompt. When I ran the program in a non-virtual environment, from PIL import Image worked. It also worked when I called venv/scripts/activate before calling pip install Pillow. So apparently PIL is not found when installed in the python root but the program runs in a virtual environment.
type: Answer
score: 4

http://stackoverflow.com/q/49130053
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1769403
has comment: http://stackoverflow.com/comment/85264753
has body: def print_dict(**person): print(person) print_dict( a ='jack', b ='rose') # {'a': 'jack', 'b': 'rose'} With two asterisks, Python will create a dictionary to hold the keywords arguments. What I do not understand is why the arguments are: a = "Jack" instead of "a" = "Jack", cause a is a key, why is it not quoted?
duplicate of: http://stackoverflow.com/q/1769403
has comment: http://stackoverflow.com/comment/85264600
tagged with: python
has comment: http://stackoverflow.com/comment/85264658
type: Question
has title: New to Python, why is it not quoted?
answer count: 0
has comment: http://stackoverflow.com/comment/85264757
score: 0
tagged with: function

http://stackoverflow.com/comment/85262574
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49128631
has text: If you don’t set `related_name`, you can use the default: `request.user.userprofile`.

http://stackoverflow.com/a/49186728
type: Answer
answers question: http://stackoverflow.com/q/49180625
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49180625
has body: You did not make rpmstatus1 accessible by other functions in the class because you did not use self. Here is the corrected code, and should be used for every widget that you plan to use in other functions: self.rpm_status1 = Label( root, text="%d RPM", bd=1, relief=SUNKEN) This ensures that the widget is usable throughout the class.

http://stackoverflow.com/q/49250151
has body: I have a list like this: list1 = [['2012', '1', '3', '1', '832.0', '261.0', '100.00'], ['2012', '1', '5', '1', '507.0', '193.0', '92.50'], ['2012', '2', '3', '1', '412.0', '200.0', '95.00'], ['2012', '2', '5', '1', '560.0', '335.0', '90.00'], ['2012', '3', '3', '1', '584.0', '205.0', '100.00'], ['2012', '3', '5', '1', '595.0', '162.0', '92.50'], ['2012', '4', '3', '1', '504.0', '227.0', '100.00'], ['2012', '4', '5', '1', '591.0', '264.0', '92.50'], ['2012', '5', '3', '1', '489.0', '234.0', '100.00'], ['2012', '5', '5', '1', '561.0', '292.0', '95.00'], ['2012', '6', '3', '1', '622.0', '221.0', '100.00'], ['2012', '6', '5', '1', '478.0', '204.0', '92.50'], ['2012', '7', '3', '1', '974.0', '290.0', '100.00'], ['2012', '7', '5', '1', '553.0', '269.0', '95.00'], ['2012', '8', '3', '1', '473.0', '158.0', '100.00'], ['2012', '8', '5', '1', '526.0', '174.0', '92.50'], ['2012', '9', '3', '1', '701.0', '189.0', '95.00'], ['2012', '9', '5', '1', '502.0', '179.0', '97.50'], ['2012', '10', '3', '1', '470.0', '184.0', '100.00'], ['2012', '10', '5', '1', '579.0', '218.0', '92.50']] The seventh column of each line is Y data,the fifth column and sixth column of each line are X data. I want to calculate "intercept" and "coef" with this list. If there is a csv file,I know how to do it,for example: import pandas as pd from sklearn import linear_model wine = pd.read_csv( r"D:/1.csv",sep=',' ) clf = linear_model.LinearRegression() X = wine.drop( 'point', axis=1 ) y = wine['point'] clf.fit( X, y ) print( clf.intercept_,clf.coef_[0],clf.coef_[1] ) My csv: But now,I need to calculate "intercept" and "coef" with list. How to do it?
has title: How to use sklearn "LinearRegression" with list?
has answer: http://stackoverflow.com/a/49250223
has answer: http://stackoverflow.com/a/49250582
possible better answer: http://stackoverflow.com/a/49250231
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85503772
answer count: 3
tagged with: pandas
score: 1
downvote count: 0
upvote count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/49250231
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49250223

http://stackoverflow.com/comment/85313842
comment on: http://stackoverflow.com/a/49152042
score: 0
type: AnswerComment
has text: Can you remove the `@api.one` decorator and test it again?
type: Comment

http://stackoverflow.com/comment/85276060
has text: Thats exactly I mean, using C or C++ completely makes sense but i have seen people using other languages and use other data structure to implement this , which doesn't make any sense to me.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49135555

http://stackoverflow.com/comment/104770975
type: AnswerComment
comment on: http://stackoverflow.com/a/54019799
has text: I am using **keras==2.2.5** and **tensorflow==1.5.0** and am getting the same error as well. **Though I get this error while trying to save a sequential model.**
type: Comment
score: 0

http://stackoverflow.com/q/49201658
has answer: http://stackoverflow.com/a/49201725
has title: Using Image (Pillow)/Pytesseract (Python): FineNotFound: [WinError 2] The system cannot find the file specified
answer count: 1
tagged with: python
has body: On a little project I had an issue with on of the two modules, so I created a short code to see where the problem comes from. Here is my code: import pytesseract from PIL import Image text= pytesseract.image_to_string(Image.open('pict.jpg')) With this, I get the same error: FileNotFoundError: [WinError 2]The system cannot find the file specified and PyScripter open the subprocess.py file and show me the following line: # Start the process try: hp, ht, pid, tid = _winapi.CreateProcess(executable, args, # no special security None, None, int(not close_fds), creationflags, env, cwd, startupinfo) When I googled this issue, it looked like my version of pytesseract was causing this. I tried to install different versions of pytesseract or Pillow, but the error still occurs. What should I do ? How can I be sure that my installation is proper ? Thanks. EDIT1: I tried adding this to make sure the module directory is in the system path: sys.path.insert(0,'C:\Python34\Lib\site-packages\pytesseract')
type: AnsweredQuestion
score: 0
type: Question
accepted answer: http://stackoverflow.com/a/49201725

http://stackoverflow.com/q/49209338
type: Question
tagged with: numpy
has body: I am using FbProphet and we should covert the data to log values in orer to normalize the data like this:df['y'] = np.log(df['y']) But once I have predicted the values, then I get a dataframe like this: ds n_tickets yhat 0 2018-02-17 2202 7.545468 1 2018-02-18 2449 7.703022 2 2018-02-19 2409 7.705301 3 2018-02-20 2364 7.675143 4 2018-02-21 2306 7.693359 5 2018-02-22 2492 7.728534 6 2018-02-23 2300 7.669022 7 2018-02-24 2359 7.534430 8 2018-02-25 2481 7.691983 9 2018-02-26 2446 7.694263 Here, yhat are my predicted values but they are log values and n_tickets are my actual values. So, I need to convert yhat back to normal number to make a comparison. I am trying to find out but getting confused.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85423555
tagged with: dataframe
tagged with: python
score: 3
tagged with: pandas
upvote count: 3
answer count: 1
downvote count: 0
has title: Converting log values back to number
has answer: http://stackoverflow.com/a/50980215
favorite count: 0

http://stackoverflow.com/comment/85412299
comment on: http://stackoverflow.com/a/49200806
score: 1
type: Comment
has text: Then how would one type input into your program? "Reading from stdin" means reading from the console when input is not redirected.
type: AnswerComment

http://stackoverflow.com/q/49130879
linked to: http://stackoverflow.com/q/13908615
has comment: http://stackoverflow.com/comment/85291400
has comment: http://stackoverflow.com/comment/85267416
has body: I was following first chapter of the nltk book. It asks us to install book corpus by running nltk.dowwnload(). I am getting getattrinfo failed error while doing ntlk.download(). After reading online, I came to know that this has something to do with my proxy. So I tried setting proxies in different ways (trying http or https, %40 or @ in password): nltk.set_proxy('http://proxy.mycompany.com:8080',('123456','password%40123')) nltk.set_proxy('http://proxy.mycompany.com:8080',('123456','password@123')) nltk.set_proxy('https://proxy.mycompany.com:8080',('123456','password%40123')) nltk.set_proxy('https://proxy.mycompany.com:8080',('123456','password@123')) (I was able to succesfully set proxy for pip and install nltk, but not sure if I am making mistake in case of nltk proxy) Then I also tried C:\Users\123456&gt;python -m nltk.downloader all [nltk_data] Error loading all: &lt;urlopen error [Errno 11004] [nltk_data] getaddrinfo failed&gt; Error installing package. Retry? [n/y/e] Next I tried &gt;&gt;&gt;nltk.download('book') But this too gives same error: &gt;&gt;&gt; nltk.download('book') [nltk_data] Error loading book: &lt;urlopen error [Errno 11004] [nltk_data] getaddrinfo failed&gt; Then I also tried by changing server index url as suggested here, but no use. Also the pre populated index is alive (and I am able to open it in the browser), so I guess I need not change server index url.
tagged with: nltk-book
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85510707
has comment: http://stackoverflow.com/comment/85267477
tagged with: nltk
type: UnansweredQuestion
tagged with: python
tagged with: nlp
has title: Setting up ntlk proxy
linked to: http://stackoverflow.com/q/27750608
has comment: http://stackoverflow.com/comment/85268257
has comment: http://stackoverflow.com/comment/85295407
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85295434
downvote count: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85294679

http://stackoverflow.com/q/49237889
tagged with: graph
tagged with: scope
possible better answer: http://stackoverflow.com/a/72951674
has answer: http://stackoverflow.com/a/49238452
score: 7
has answer: http://stackoverflow.com/a/72951674
tagged with: python
has body: When choosing a name for a tensorflow variable, this is ok: &gt;&gt; tf.Variable(2, name='a') &lt;tf.Variable 'finegrained_1/decoder/unreadable/a:0' shape=() dtype=int32_ref&gt; However, this is not: &gt;&gt; tf.Variable(2, name='a:b') --------------------------------------------------------------------------- ValueError Traceback (most recent call last) ~/mm/appy-finegrained/sign_classification/model_finegrained.py in &lt;module&gt;() ----&gt; 1 tf.Variable(2, name='a:b') ~/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/variables.py in __init__(self, initial_value, trainable, collections, validate_shape, caching_device, name, variable_def, dtype, expected_shape, import_scope, constraint) 211 dtype=dtype, 212 expected_shape=expected_shape, --&gt; 213 constraint=constraint) 214 215 def __repr__(self): ~/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/variables.py in _init_from_args(self, initial_value, trainable, collections, validate_shape, caching_device, name, dtype, expected_shape, constraint) 287 with ops.control_dependencies(None): 288 with ops.name_scope(name, "Variable", [] if init_from_fn else --&gt; 289 [initial_value]) as name: 290 291 if init_from_fn: ~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in __enter__(self) 4930 self._g_manager.__enter__() 4931 self._name_scope = g.name_scope(self._name) -&gt; 4932 return self._name_scope.__enter__() 4933 4934 def __exit__(self, type_arg, value_arg, traceback_arg): ~/anaconda3/lib/python3.6/contextlib.py in __enter__(self) 79 def __enter__(self): 80 try: ---&gt; 81 return next(self.gen) 82 except StopIteration: 83 raise RuntimeError("generator didn't yield") from None ~/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in name_scope(self, name) 3512 # (viz. '-', '\', '/', and '_'). 3513 if not _VALID_SCOPE_NAME_REGEX.match(name): -&gt; 3514 raise ValueError("'%s' is not a valid scope name" % name) 3515 else: 3516 # Scopes created in the r…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49238452
answer count: 2
has comment: http://stackoverflow.com/comment/85479215
has comment: http://stackoverflow.com/comment/85479116
downvote count: 0
linked to: http://stackoverflow.com/q/36150834
tagged with: variables
upvote count: 7
tagged with: tensorflow
favorite count: 0
has title: What characters are allowed in tensorflow variable names?
type: Question

http://stackoverflow.com/q/49126249
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49126418
has title: Lemmatize using Textblob in python
tagged with: python
score: 0
tagged with: lemmatization
has comment: http://stackoverflow.com/comment/85257286
has comment: http://stackoverflow.com/comment/85257283
has body: I have written code for lemmatize sentence in Python using text blob but I am not getting the expected result: def get_lemmatize_text(transcript): transcript = transcript.strip() blob = TextBlob(transcript) for word in blob: expected_str = Word(word) expected_str = expected_str.lemmatize() return expected_str print(get_lemmatize_text("he had not received the four letters we d sent him as he had been travelling for the whole of august and hadn t received any call or text from us . he has just arrived today and has called us straight away . he has also just of his account when he had asked for it to be cancelled before it switched from the first additions datestr . he says he received contact from us that we were looking into this but doesnot have that to hand")) I get following as output: d What has gone wrong? Can anyone help me or correct me?
answer count: 1
tagged with: textblob
type: Question

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

http://stackoverflow.com/comment/85252148
comment on: http://stackoverflow.com/q/49121746
score: 1
type: Comment
type: QuestionComment
has text: Note that `1e100` is a mathematical notation for the number from which Google took their company name. This is one of their infrastructure domains.

http://stackoverflow.com/comment/121571180
type: Comment
has text: I am getting KeyError: 'VIRTUAL_ENV' this error how can i get rid off from this i am following your tutorial. I have also posted this error as separate question on stackoverflow.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/61979107

http://stackoverflow.com/comment/85309336
score: 0
comment on: http://stackoverflow.com/q/49143024
has text: Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49195236
has title: \n not working in the output
tagged with: newline
has answer: http://stackoverflow.com/a/49195397
tagged with: python
has body: Hi I currently have an output of: 'root:$6$aYGtvxKp/bl6Fv2y$sdZ3FbdJYQlP8VcfFZT.Y67We5EQmqcHW4I9Gl/3pXp8v4.nu9qMIEkmOcdRuD0lBTvEtnMHosEo7OEaYgG4E0::0:99999:7:::\nbin::17110:0:99999:7:::\ndaemon::17110:0:99999:7:::\nadm::17110:0:99999:7:::\nlp::17110:0:99999:7:::\nsync::17110:0:99999:7:::\nshutdown::17110:0:99999:7:::\nhalt::17110:0:99999:7:::\nmail::17110:0:99999:7:::\noperator::17110:0:99999:7:::\ngames::17110:0:99999:7:::\nftp::17110:0:99999:7:::\nnobody::17110:0:99999:7:::\nsystemd-bus-proxy:!!:17572::::::\nsystemd-network:!!:17572::::::\ndbus:!!:17572::::::\npolkitd:!!:17572::::::\ntss:!!:17572::::::\nsshd:!!:17572::::::\npostfix:!!:17572::::::\nchrony:!!:17572::::::\funky:$1$EgZiG263$4W/wMljYzhOqnupg9cJ7W/:17599:0:99999:7:::\n' From my code: command = "cat /etc/shadow " process = os.popen(command) results = str(process.read()) I'm trying to make it look like the one in the command prompt wherein it is in a table form but for some reason when I transfer it to python it does do the new line function "\n" does not work. What is wrong with my code?
has comment: http://stackoverflow.com/comment/85395330
has comment: http://stackoverflow.com/comment/85395271
answer count: 2
upvote count: 0
type: UnansweredQuestion
downvote count: 2
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49195385
tagged with: spacing
score: -2

http://stackoverflow.com/comment/85538949
comment on: http://stackoverflow.com/q/49262649
score: 0
has text: Please make a simple, self-contained, complete example.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49202124
has comment: http://stackoverflow.com/comment/85446828
has comment: http://stackoverflow.com/comment/85484292
type: Answer
has comment: http://stackoverflow.com/comment/85498841
score: 0
has comment: http://stackoverflow.com/comment/85446947
answers question: http://stackoverflow.com/q/49185907
has body: This a tricky issue, which comes up when computing daily climatologies over many years. You want your computations to include 366 days even for non-leap years but to use NaN for Feb. 29. You don't mention what language you are using to create your NetCDF files. There is an answer using Python and Pandas, in the context of creating climatologies at this question: Compute daily climatology using pandas python which might help get you started. My answer to that question shows a method for dealing with the leap year issue. I've created 30 year daily climatology files, using this method and Panoply has no problems viewing them.
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/85438044
score: 0
type: Comment
type: QuestionComment
has text: what page are you scraping?
comment on: http://stackoverflow.com/q/49216971

http://stackoverflow.com/q/49163835
has title: Seq2Seq: Decoder predictions not depends on Encoder inputs
tagged with: lstm
has comment: http://stackoverflow.com/comment/85353152
has body: I'm training Seq2Seq model on OpenSubtitles dialogs - Cornell-Movie-Dialogs-Corpus. My work based on the following papers: (1) Sequence to Sequence Learning with Neural Networks, Sutskever et al. 2014 (2) A Neural Conversational Model, Vinyals, Le, 2015 The training converges well, but when I checked what the network is actually predicting - I discovered that the encoder's input doesn't matter at all for decoder's predictions. What matters are only words presented to the decoder. For example after the tag &lt;s&gt; the decoder predicts always the word 'i'. The pseudo-code of my architecture looks like this (I'm using Tensorflow 1.5): seq1 = tf.placeholder(...) seq2 = tf.placeholder(...) embeddings = tf.Variable(tf.zeros([vocab_size, 300])) seq1_emb = tf.nn.embedding_lookup(embeddings, seq1) seq2_emb = tf.nn.embedding_lookup(embeddings, seq2) # Encoder init_state is a random_uniform of: -0.08, 0.08 (according to paper [1]) encoder_out, state1 = tf.nn.dynamic_rnn(BasicLSTMCell(), seq1_emb) decoder_out, state2 = tf.nn.dynamic_rnn(BasicLSTMCell(), seq2_emb, initial_state=state_1) logit = Dense(decoder_out, use_bias=False) crossent = tf.nn.saparse_softmax_cross_entropy_with_logits(logits=logit, labels=target) crossent = mask_padded_zeros(crossent) loss = tf.reduce_sum(crossent) / number_of_words_in_batch # Gradient is Clipped-By-Norm with 5 (according to paper [1]) train = tf.train.GradientDescentOptimizer(learning_rate=0.7).minimize(loss) I would be very glad for your help!
score: 0
has comment: http://stackoverflow.com/comment/85355248
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/85335468
type: Question
has comment: http://stackoverflow.com/comment/85355109
answer count: 0
type: UnansweredQuestion
tagged with: neural-network
tagged with: machine-learning
tagged with: python

http://stackoverflow.com/q/49151225
has comment: http://stackoverflow.com/comment/89218820
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/85307244
has body: What does @@ mean in Tensorflow source code? For example, in this link https://github.com/tensorflow/tensorflow/blob/r1.6/tensorflow/python/ops/array_ops.py#L19 What follows the @@ symbols seems to be some function names. What is the purpose of including such section in the beginning of the source code? Besides, in this page, it says the tf.placeholder_with_default is defined in tensorflow/python/ops/gen_array_ops.py But I cannot find the respected python files in the github repository. Where can I find the source code for this function? https://github.com/tensorflow/tensorflow/tree/r1.6/tensorflow/python/ops
tagged with: python
has title: What does @@ means in the Tensorflow source code?
answer count: 0
upvote count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/36783977
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/85313984
favorite count: 0
type: Question

http://stackoverflow.com/a/49284249
type: Answer
answers question: http://stackoverflow.com/q/49275602
score: 2
upvote count: 2
downvote count: 0
has body: Your best bet would be to use a logging.Filter such as: class MyFilter(logging.Filter): def filter(self, record): record.expandedFuncName = '%s.%s.%s' % (record.name, record.module, record.funcName) return True and then use a format string something like %(asctime)s %(levelname)-5s [%(threadName)-10s] %(expandedFuncName)-20.20s : %(message)s You'd need to ensure that an instance of this filter was applied to every handler which uses a formatter with expandedFuncName in the format string. You can't do this with basicConfig, so I'd recommend using the dictConfig logging configuration API instead. Note that the logger name will generally include the module name if you use the convention logger = logging.getLogger(__name__) as recommended in the logging documentation, though this won't apply exactly in the case of the __main__ module.

tensorflow
tags question: http://stackoverflow.com/q/49266801
tags question: http://stackoverflow.com/q/49267264
type: Tag
tags question: http://stackoverflow.com/q/49135653
tags question: http://stackoverflow.com/q/49190610
tags question: http://stackoverflow.com/q/49206051
tags question: http://stackoverflow.com/q/49161663
tags question: http://stackoverflow.com/q/49213607
tags question: http://stackoverflow.com/q/49227400
tags question: http://stackoverflow.com/q/49245642
tags question: http://stackoverflow.com/q/49206732
tags question: http://stackoverflow.com/q/49161339
tags question: http://stackoverflow.com/q/49169389
tags question: http://stackoverflow.com/q/49229234
tags question: http://stackoverflow.com/q/49126929
tags question: http://stackoverflow.com/q/49209128
tags question: http://stackoverflow.com/q/49126004
tags question: http://stackoverflow.com/q/49160972
tags question: http://stackoverflow.com/q/49244969
tags question: http://stackoverflow.com/q/49214921
tags question: http://stackoverflow.com/q/49165914
tags question: http://stackoverflow.com/q/49208326
tags question: http://stackoverflow.com/q/49161316
tags question: http://stackoverflow.com/q/49155463
tags question: http://stackoverflow.com/q/49163592
tags question: http://stackoverflow.com/q/49158140
tags question: http://stackoverflow.com/q/49227958
tags question: http://stackoverflow.com/q/49158935
tags question: http://stackoverflow.com/q/49219958
tags question: http://stackoverflow.com/q/49193435
tags question: http://stackoverflow.com/q/49182351
tags question: http://stackoverflow.com/q/49272597
tags question: http://stackoverflow.com/q/49241502
tags question: http://stackoverflow.com/q/49252970
tags question: http://stackoverflow.com/q/49193932
tags question: http://stackoverflow.com/q/49141002
tags question: http://stackoverflow.com/q/49268743
tags question: http://stackoverflow.com/q/49191497
tags question: http://stackoverflow.com/q/49148375
tags question: http://stackoverflow.com/q/49276413
tags question: http://stackoverflow.com/q/49141796
tags question: http://stackoverflow.com/q/49136043
tags question: http://stackoverflow.com/q/49165112
tags question: http://stackoverflow.com/q/49124814
tags question: http://stackoverflow.com/q/49203098
tags question: http://stackoverflow.com/q/49161208
tags question: http://stackoverflow.com/q/49155874
tags question: http://stackoverflow.com/q/49189711
tags question: http://stackoverflow.com/q/49240338
tags question: http://stackoverflow.com/q/49220892
tags question: http://stackoverflow.com/q/49278016
tags question: http://stackoverflow.com/q/49242279
tags question: http://stackoverflow.com/q/49169016
tags question: http://stackoverflow.com/q/49175961
tags question: http://stackoverflow.com/q/49146065
tags question: http://stackoverflow.com/q/49225326
tags question: http://stackoverflow.com/q/49278571
tags question: http://stackoverflow.com/q/49241401
tags question: http://stackoverflow.com/q/49239478
tags question: http://stackoverflow.com/q/49248833
tags question: http://stackoverflow.com/q/49155206
tags question: http://stackoverflow.com/q/49178891
tags question: http://stackoverflow.com/q/49174596
tags question: http://stackoverflow.com/q/49267730
tags question: http://stackoverflow.com/q/49212526
tags question: http://stackoverflow.com/q/49221654
tags question: http://stackoverflow.com/q/49278504
tags question: http://stackoverflow.com/q/49213432
tags question: http://stackoverflow.com/q/49232895
tags question: http://stackoverflow.com/q/49122044
tags question: http://stackoverflow.com/q/49160481
tags question: http://stackoverflow.com/q/49221391
tags question: http://stackoverflow.com/q/49226523
tags question: http://stackoverflow.com/q/49135929
tags question: http://stackoverflow.com/q/49218685
tags question: http://stackoverflow.com/q/49226579
tags question: http://stackoverflow.com/q/49163835
tags question: http://stackoverflow.com/q/49161174
tags question: http://stackoverflow.com/q/49266894
tags question: http://stackoverflow.com/q/49261007

http://stackoverflow.com/a/49207772
upvote count: 6
answers question: http://stackoverflow.com/q/49207688
has comment: http://stackoverflow.com/comment/85420562
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49207688
has comment: http://stackoverflow.com/comment/85420470
has comment: http://stackoverflow.com/comment/85420487
has body: One possible solution is use numpy.log: print (np.log(df.mask(df &lt;=0)).fillna(0)) Or pure numpy: df1= pd.DataFrame(np.ma.log(df.values).filled(0), index=df.index, columns=df.columns)
score: 6
downvote count: 0
type: Answer

http://stackoverflow.com/a/52029539
upvote count: 1
answers question: http://stackoverflow.com/q/49262712
has comment: http://stackoverflow.com/comment/91504815
score: 1
type: Answer
has body: this is caused by an issue in IronPython, the python version that is used in streamlabs chatbot (yea i know you're talking about that one ^^ ). It is a problem in the ssl module that urllib uses. This is also the reason why chatbot forsees the following functions: https://github.com/AnkhHeart/Streamlabs-Chatbot-Python-Boilerplate/wiki/API-Requests i am looking for a solution myself, but so far i've had to rewrite everything to use these functions. This is the same reason why urllib2, requests and many other modules will not work.
downvote count: 0

http://stackoverflow.com/comment/85257961
type: Comment
comment on: http://stackoverflow.com/a/49126067
score: 0
type: AnswerComment
has text: I made these changes and it helped with the structure of the website but the problem still remains. I added additional context at the bottom of my question in the EDIT section.

http://stackoverflow.com/comment/85436129
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49215611
type: Comment
has text: The does not detect, opencv verifies if the format of the image matches one that has been supported since the formats do not provide raw data since they are compressed.

http://stackoverflow.com/a/51032107
downvote count: 0
answers question: http://stackoverflow.com/q/49216197
has body: I was having the same problem with the Jupyter notebook. I realized that Jupiter gets too slow when I set the limits too high. For example, import pandas as pd pd.set_option('display.max_columns', 50000) was causing serious time issues. I changed it to: pd.set_option('display.max_columns', 50) and the problem was solved. In your case, you can use: $jupyter notebook --NotebookApp.iopub_data_rate_limit=1000000 I think this will solve your problem. Thanks
has comment: http://stackoverflow.com/comment/119715791
type: Answer
has comment: http://stackoverflow.com/comment/119395343
score: 20
has comment: http://stackoverflow.com/comment/118364654
has comment: http://stackoverflow.com/comment/119684355
upvote count: 20

http://stackoverflow.com/q/49270817
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: nltk
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52412814
has comment: http://stackoverflow.com/comment/85545281
tagged with: python
has title: Flesch-Kincaid readability test in python
score: 2
tagged with: tokenize
upvote count: 2
tagged with: flesch-kincaid
answer count: 1
linked to: http://stackoverflow.com/q/49251629
downvote count: 0
has body: I need help with this problem I'm having. I need to write a function that returns a FRES (Flesch reading-ease test) from a text. Given the formula: In other words my task is to turn this formula into a python function. this is the code from the previous question I had: import nltk import collections nltk.download('punkt') nltk.download('gutenberg') nltk.download('brown') nltk.download('averaged_perceptron_tagger') nltk.download('universal_tagset') import re VC = re.compile('[aeiou]+[^aeiou]+', re.I) def count_syllables(word): return len(VC.findall(word)) from itertools import chain from nltk.corpus import gutenberg def compute_fres(text): """Return the FRES of a text. &gt;&gt;&gt; emma = nltk.corpus.gutenberg.raw('austen-emma.txt') &gt;&gt;&gt; compute_fres(emma) # doctest: +ELLIPSIS 99.40... """ for filename in gutenberg.fileids(): sents = gutenberg.sents(filename) words = gutenberg.words(filename) num_sents = len(sents) num_words = len(words) num_syllables = sum(count_syllables(w) for w in words) score = 206.835 - 1.015 * (num_words / num_sents) - 84.6 * (num_syllables / num_words) return(score) And this is the result I get: Failure Expected :99.40... Actual :92.84866041488623 ********************************************************************** File "C:/Users/PycharmProjects/a1/a1.py", line 60, in a1.compute_fres Failed example: compute_fres(emma) # doctest: +ELLIPSIS Expected: 99.40... Got: 92.84866041488623 My task is to pass the doctest and result in 99.40... I'm also not allowed the change the following code since it was given to me with the task itself: import re VC = re.compile('[aeiou]+[^aeiou]+', re.I) def count_syllables(word): return len(VC.findall(word)) I feel like I'm getting close but not sure why I get a different result. Any help will be much appreciated.

http://stackoverflow.com/comment/85509031
comment on: http://stackoverflow.com/q/49252573
type: Comment
type: QuestionComment
has text: you mean speed?
score: 0

http://stackoverflow.com/comment/85280234
score: 1
type: Comment
type: QuestionComment
has text: But `r` is not a string, so why send it to `fromstring`. `r.text` was probably what you are looking for.
comment on: http://stackoverflow.com/q/49137385

http://stackoverflow.com/q/49132343
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85278327
downvote count: 0
answer count: 0
tagged with: bokeh
has title: Bokeh Error Model 'Slider' does not exist. This could be due to a widget or a custom model not being registered before first usage
has comment: http://stackoverflow.com/comment/85278283
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/89536605
type: UnansweredQuestion
tagged with: data-visualization
has body: I'm working on the standard gapminder dataset and want to analyse the different parameters annually and find correlations between them. I intend to add a slider which changes the year and drop down menus for the x and y axes which will help me pick the parameter I want on the respective axis. import pandas as pd data=pd.read_csv('gapminder_tidy.csv',index_col='Year') # Import the necessary modules from bokeh.io import curdoc from bokeh.io import output_file, show from bokeh.models import ColumnDataSource from bokeh.plotting import figure # Make the ColumnDataSource: source source = ColumnDataSource(data={ 'x' : data.loc[1970].fertility, 'y' : data.loc[1970].life, 'country' : data.loc[1970].Country, 'pop' : (data.loc[1970].population / 20000000) + 2, 'region' : data.loc[1970].region, }) # Save the minimum and maximum values of the fertility column: xmin, xmax xmin, xmax = min(data.fertility), max(data.fertility) # Save the minimum and maximum values of the life expectancy column: ymin, ymax ymin, ymax = min(data.life), max(data.life) # Create the figure: plot plot = figure(title='Gapminder Data for 1970', plot_height=400, plot_width=700, x_range=(xmin, xmax), y_range=(ymin, ymax)) # Add circle glyphs to the plot plot.circle(x='x', y='y', fill_alpha=0.8, source=source) # Set the x-axis label plot.xaxis.axis_label ='Fertility (children per woman)' # Set the y-axis label plot.yaxis.axis_label = 'Life Expectancy (years)' # Make a list of the unique values from the region column: regions_list regions_list = data.region.unique().tolist() # Import CategoricalColorMapper from bokeh.models and the Spectral6 palette from bokeh.palettes from bokeh.models import CategoricalColorMapper from bokeh.palettes import Spectral6 # Make a color mapper: color_mapper color_mapper = CategoricalColorMapper(factors=regions_list, palette=Spectral6) # Add the color mapper to the circle glyph plot.circle(x='x', y='y', fill_alpha=0.8, source=source, color=dict(field='region', transform=color_mapp…
tagged with: python

http://stackoverflow.com/q/49233193
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49235697
upvote count: 3
has answer: http://stackoverflow.com/a/49233978
possible better answer: http://stackoverflow.com/a/49233978
tagged with: python-unicode
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
accepted answer: http://stackoverflow.com/a/49235697
downvote count: 0
has title: unicodedata.decomposition() vs. unicodedata.normalize(NFD/NFKD)?
tagged with: unicode
has body: According to py3 doc: unicodedata.decomposition(chr) Returns the character decomposition mapping assigned to the character chr as string. An empty string is returned in case no such mapping is defined. Here I don't quite understand how character decomposition mapping is defined and what's the relationship/difference between unicodedata.decomposition() and unicodedata.normalize(NFD/NFKD)? See following examples: $ python3 &gt;&gt;&gt; import unicodedata &gt;&gt;&gt; unicodedata.decomposition('⑴') '&lt;compat&gt; 0028 0031 0029' &lt;-- why not just '0028 0031 0029'? &gt;&gt;&gt; unicodedata.normalize('NFKD', '⑴') '(1)' &gt;&gt;&gt; unicodedata.decomposition('①') '&lt;circle&gt; 0031' &lt;-- why not just '0031'? &gt;&gt;&gt; unicodedata.normalize('NFKD', '①') '1' &gt;&gt;&gt; unicodedata.decomposition('è') '0065 0300' &lt;-- like this? &gt;&gt;&gt; unicodedata.normalize('NFD', 'è') == '\u0065\u0300' True &gt;&gt;&gt;

http://stackoverflow.com/comment/85336604
has text: Hmmm, I thought that would be the point in using the django authentication, so I don't have to code it myself. In the whole project is only this other views.py (see Edit 2), but there is also no render function of the form. I can provide some screenshots, after clicking the login/submit button the form fields appear.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49165201

python-3.x
tags question: http://stackoverflow.com/q/49157556
tags question: http://stackoverflow.com/q/49163439
tags question: http://stackoverflow.com/q/49122033
tags question: http://stackoverflow.com/q/49150115
tags question: http://stackoverflow.com/q/49249731
tags question: http://stackoverflow.com/q/49138450
tags question: http://stackoverflow.com/q/49263547
tags question: http://stackoverflow.com/q/49258049
tags question: http://stackoverflow.com/q/49191749
tags question: http://stackoverflow.com/q/49212832
tags question: http://stackoverflow.com/q/49125752
tags question: http://stackoverflow.com/q/49131584
tags question: http://stackoverflow.com/q/49227501
tags question: http://stackoverflow.com/q/49206475
tags question: http://stackoverflow.com/q/49152399
tags question: http://stackoverflow.com/q/49210445
tags question: http://stackoverflow.com/q/49165933
tags question: http://stackoverflow.com/q/49240103
tags question: http://stackoverflow.com/q/49263257
tags question: http://stackoverflow.com/q/49204505
tags question: http://stackoverflow.com/q/49261303
tags question: http://stackoverflow.com/q/49265512
tags question: http://stackoverflow.com/q/49163558
tags question: http://stackoverflow.com/q/49222472
tags question: http://stackoverflow.com/q/49273059
tags question: http://stackoverflow.com/q/49157075
tags question: http://stackoverflow.com/q/49171769
tags question: http://stackoverflow.com/q/49220097
tags question: http://stackoverflow.com/q/49201431
tags question: http://stackoverflow.com/q/49225195
tags question: http://stackoverflow.com/q/49216575
tags question: http://stackoverflow.com/q/49225177
tags question: http://stackoverflow.com/q/49263903
tags question: http://stackoverflow.com/q/49136597
tags question: http://stackoverflow.com/q/49177473
tags question: http://stackoverflow.com/q/49243216
tags question: http://stackoverflow.com/q/49245524
tags question: http://stackoverflow.com/q/49125167
tags question: http://stackoverflow.com/q/49143929
tags question: http://stackoverflow.com/q/49214393
tags question: http://stackoverflow.com/q/49147353
tags question: http://stackoverflow.com/q/49223576
tags question: http://stackoverflow.com/q/49155472
tags question: http://stackoverflow.com/q/49243663
tags question: http://stackoverflow.com/q/49142463
tags question: http://stackoverflow.com/q/49246775
tags question: http://stackoverflow.com/q/49189749
tags question: http://stackoverflow.com/q/49140117
tags question: http://stackoverflow.com/q/49132617
tags question: http://stackoverflow.com/q/49151299
tags question: http://stackoverflow.com/q/49187041
tags question: http://stackoverflow.com/q/49205243
tags question: http://stackoverflow.com/q/49195660
tags question: http://stackoverflow.com/q/49230426
tags question: http://stackoverflow.com/q/49132517
tags question: http://stackoverflow.com/q/49161691
tags question: http://stackoverflow.com/q/49168042
tags question: http://stackoverflow.com/q/49176042
tags question: http://stackoverflow.com/q/49186703
tags question: http://stackoverflow.com/q/49274803
tags question: http://stackoverflow.com/q/49222820
tags question: http://stackoverflow.com/q/49140383
tags question: http://stackoverflow.com/q/49155113
tags question: http://stackoverflow.com/q/49140666
tags question: http://stackoverflow.com/q/49155418
tags question: http://stackoverflow.com/q/49256788
tags question: http://stackoverflow.com/q/49131940
tags question: http://stackoverflow.com/q/49216652
tags question: http://stackoverflow.com/q/49121764
tags question: http://stackoverflow.com/q/49136756
tags question: http://stackoverflow.com/q/49178659
tags question: http://stackoverflow.com/q/49230389
tags question: http://stackoverflow.com/q/49177583
tags question: http://stackoverflow.com/q/49272364
tags question: http://stackoverflow.com/q/49200832
tags question: http://stackoverflow.com/q/49156008
tags question: http://stackoverflow.com/q/49200536
tags question: http://stackoverflow.com/q/49226149
tags question: http://stackoverflow.com/q/49219608
tags question: http://stackoverflow.com/q/49165589

http://stackoverflow.com/q/49193464
type: Question
has comment: http://stackoverflow.com/comment/85391480
has answer: http://stackoverflow.com/a/49193505
accepted answer: http://stackoverflow.com/a/49193505
tagged with: multithreading
has body: I have a simple thread that looks (simplified) like this: import threading import time def print_coordinates(): return listener = threading.Thread(name = "listener", target = print_coordinates) while(1): listener.start() time.sleep(1) listener.start() time.sleep(1) Now, I receive the error RuntimeError: threads can only be started once. As far as I understood, return should cause the thread to "silently exit", as mentioned here. What am I doing wrong?
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
has title: Thread target function's return does not cause thread to exit
answer count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/q/49202160
tagged with: django
tagged with: django-rest-framework
favorite count: 0
type: Question
score: 3
has body: I'm using the Writable Nested Serializer to serialize my request. I had no problem serializing doing PUT/POST when the data is nested in 1 layer. (i.e. {name:'personA', project:{ name:'projA', client:'clientA'}}) However, I ran into a problem when it is nested in 2 layers - I couldn't figure out on how to modify the update() function. Please help! data sample { "id": 6106, "name": { "id": 213, "name": "personA" }, "project": { "id": 1663, "project": "ProjectA", "client": { "id": 72, "name": "ClientA" }, "project_manager": { "id": 32, "name": "personB" } }, "booking": 100, "date": "2017-12-01" } serializers.py class projectSerializer(serializers.ModelSerializer): client = clientSerializer() project_manager = userSerializer() class Meta: model = project fields = ('id', 'project', 'client', 'project_manager') class bookingListSerializer(serializers.ModelSerializer): project = projectSerializer() name = userSerializer() class Meta: model = bookingList fields = ('id', 'name', 'project', 'booking', 'date') def update(self, instance, validated_data): project_data = validated_data.pop('project') name_data = validated_data.pop('name') try: project_instance = project.objects.filter(**project_data)[0] name_instance = user.objects.filter(**name_data)[0] except IndexError: raise serializers.ValidationError # update the project if request is valid instance.project = project_instance instance.name = name_instance instance.save() return instance views.py # other viewsets... class bookingListViewSet(viewsets.ModelViewSet): queryset = bookingList.objects.all() serializer_class = bookingListSerializer
has title: Django serialize POST & PUT request in a nested object
tagged with: django-models
tagged with: python
answer count: 0
upvote count: 3
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/a/49169868
downvote count: 0
has comment: http://stackoverflow.com/comment/85344924
upvote count: 1
has comment: http://stackoverflow.com/comment/85345241
has comment: http://stackoverflow.com/comment/85345540
has comment: http://stackoverflow.com/comment/85345055
has body: import requests import execjs url = 'http://www.sgx.com/JsonRead/JsonstData?qryId=RAll' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'} page = requests.get(url,headers=headers) content = page.content[len('{}&amp;&amp; '):] if page.content.startswith('{}&amp;&amp; ') else page.content data = execjs.get().eval(content) print(data) The data is JavaScript Object, in literal notation. We can use PyExecJs to eval it and get corresponding python dict.
type: Answer
has comment: http://stackoverflow.com/comment/85345148
answers question: http://stackoverflow.com/q/49169585
score: 1
has comment: http://stackoverflow.com/comment/85345135

http://stackoverflow.com/comment/85275632
score: 1
has text: Where does the "somethingX" come from?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49135476

http://stackoverflow.com/q/49259839
tagged with: odbc
type: AnsweredQuestion
tagged with: sql-server
tagged with: azure-sql-database
upvote count: 1
score: 1
answer count: 1
downvote count: 0
has body: I am using pyodbc to connect to an azure sql database. My source code looks like this: import pyodbc server = 'sqlserver.database.windows.net' database = 'database' username = 'username' password = 'password' conn= pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server}'+';SERVER='+server+';PORT=1443;DATABASE='+database+';UID='+username+';PWD='+ password ';Encrypt=yes;TrustServerCertificate=no;Connection Timeout=30;') cursor = conn.cursor() cursor.execute("query") I am able to connect to a sql database. The only thing which is not working properly is that pyodbc does not connect to the database I have specified in the database variable. It always connects to the master database. What I have tried so far is to print the name of the databases on the target sql server using SELECT * FROM sys.databases while being connected to the master database. I was able to see the database I am trying to connect to. Anyone got an idea what goes wrong in my source code?
favorite count: 0
type: Question
has title: pyodbc always connects to master database
has answer: http://stackoverflow.com/a/49264883
accepted answer: http://stackoverflow.com/a/49264883
tagged with: python
tagged with: pyodbc

http://stackoverflow.com/a/49195844
has comment: http://stackoverflow.com/comment/85397011
has comment: http://stackoverflow.com/comment/85397301
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/85396925
has body: The idea would be to create a list of numbers to use as your x data, from 0 to 150: x_data = range(150) Then slice this so that for the first set of data, your x axis uses numbers 0 to 149. Then the second set of data needs to be sliced to use the numbers 100 to 149. plt.plot(x_data[:], test1[:150]) plt.plot(x_data[100:], predictions1[100:150], color='red') Note that Python indexing starts at 0, not 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49195660
answers question: http://stackoverflow.com/q/49195660
score: 5

http://stackoverflow.com/comment/85413326
has text: Nothing changed since the time, the fixed location is [still fixed](https://github.com/pypa/setuptools/blob/118edbb2b715c96620b51018c1d28e81f2318053/setuptools/package_index.py#L1026).
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49203272
type: Comment

http://stackoverflow.com/comment/129823631
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49184317
has text: how can i pass multiple arguments
score: 0

vlookup
tag name: vlookup
tags question: http://stackoverflow.com/q/49251163
tags question: http://stackoverflow.com/q/49210051
type: Tag

http://stackoverflow.com/comment/85491230
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49243663
type: QuestionComment
has text: Maybe subcommands? https://docs.python.org/3/library/argparse.html#sub-commands

http://stackoverflow.com/a/49242698
has body: This is how pandas will achieve it df.loc[df.age==0, 'bal']= df.loc[df.age==0, 'bal']+ df.loc[df.age&lt;0, 'bal'].values df Out[339]: age bal cohort 0 -1 100 1 1 0 1100 1 2 1 1400 1 3 2 1500 1 4 -1 120 2 5 0 1120 2 6 1 1200 2 7 2 1300 2 Update : df.loc[df.age==0, 'bal']=df.loc[df.age&lt;=0].groupby('cohort').bal.sum().values
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85489311
accepted answer of: http://stackoverflow.com/q/49242577
type: Answer
answers question: http://stackoverflow.com/q/49242577
score: 0

http://stackoverflow.com/a/49283211
score: 0
type: AcceptedAnswer
has body: the problem was with my version of matplotlib I've installed v.2.2.0. uninstalled it and installed v.2.1.2 then this code start working.
answers question: http://stackoverflow.com/q/49277331
type: Answer
accepted answer of: http://stackoverflow.com/q/49277331

http://stackoverflow.com/q/49162010
has body: I have two list variables: a = ["a", "b"] b = ["a (x)"] I need to find and replace all elements in list a with elements from list b where substring of element before ( from list b is equal to element from list a. So I need to get this: a = ["a (x)", "b"] b = ["a (x)"] It is a bit complicated to exlplain, but I hope you understand. This is what I have so far, but I don't know how to continue. for bx in b: for ax in a: if ax == bx[:bx.find(" (")]: #I don't know what to do next Do you have some ideas, please?
score: 0
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49162073
has title: How to replace element in list in python
upvote count: 1
tagged with: python
tagged with: dictionary
tagged with: replace
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/49162073

http://stackoverflow.com/comment/85507164
comment on: http://stackoverflow.com/q/49246504
type: Comment
has text: It's trivial to use PDFBox text extraction restricted to the crop box, if that would be a solution for you.
score: 1
type: QuestionComment

google-bigquery
tags question: http://stackoverflow.com/q/49153143
tags question: http://stackoverflow.com/q/49278393
tags question: http://stackoverflow.com/q/49265480
tags question: http://stackoverflow.com/q/49186510
type: Tag
tags question: http://stackoverflow.com/q/49140722
tag name: google-bigquery

http://stackoverflow.com/comment/85805549
score: 0
type: QuestionComment
has text: It's version: `8.3.2`
type: Comment
comment on: http://stackoverflow.com/q/49178797

http://stackoverflow.com/q/49135754
has answer: http://stackoverflow.com/a/49135971
tagged with: leap-year
tagged with: anaconda
has comment: http://stackoverflow.com/comment/85276365
has comment: http://stackoverflow.com/comment/85276326
upvote count: 3
score: 0
has comment: http://stackoverflow.com/comment/85276340
has comment: http://stackoverflow.com/comment/85276298
downvote count: 3
favorite count: 0
has comment: http://stackoverflow.com/comment/85276277
tagged with: return
has body: I am writing a Python code that determines whether a year is a leap year. I think my algorithm is fine, but the result of my code is not as desired. def isLeapYear(n): if n % 400 == 0: print ("The year", n, "is a leap year:") return True if n % 100 == 0: print ("The year", n, "is a leap year:") return False if n % 4 == 0: print ("The year", n, "is a leap year:") return True else: print ("The year", n, "is a leap year:") return False isLeapYear(2000) If the code is run, the results are as follows: runfile('C:/Users/username/Desktop/isLeapYear.py', wdir='C:/Users/username/Desktop') The year 2000 is a leap year The first issue is that I do not understand why the runfile filepath is showing. Second, I would like my code to output whether or not the statement is True or False. So ideally, I'm looking for: The year 2000 is a leap year: True
has comment: http://stackoverflow.com/comment/85276314
type: Question
tagged with: function
answer count: 2
has answer: http://stackoverflow.com/a/49135875
tagged with: python
has title: Python Function return True/False
type: UnansweredQuestion

http://stackoverflow.com/q/49193044
type: Question
has comment: http://stackoverflow.com/comment/85391798
has comment: http://stackoverflow.com/comment/102340154
has body: I am using Youtube Data API v3 for fetching comments for a video. I followed official documentation https://developers.google.com/youtube/v3/docs/commentThreads/list Using https://www.googleapis.com/youtube/v3/commentThreads?key=MY_KEY&amp;videoId=ay4MKe1u7Ec&amp;part=id,snippet,replies&amp;maxResults=2 I get { "kind": "youtube#commentThreadListResponse", "etag": "\"RmznBCICv9YtgWaaa_nWDIH1_GM/lPy9jihUjGu4N-8qmo83AkMD81E\"", "nextPageToken": "QURTSl9pMW1lUmhuMHNKaWVDQWhOUUs3UzltVWpEa3JBTW5VdTNQY3I2al9OMmg3VUhUcVRId0lRYkZwV0RiLWdGbG90d3lHQlhzT3dSUnVObmdmaEdpY0RCOGlqRnNUR0pUM05lenpsaVJCUkpFZUFlWDF0SVNyVGFNMURYZ3M=", "pageInfo": { "totalResults": 2, "resultsPerPage": 2 }, "items": [ { "kind": "youtube#commentThread", "etag": "\"RmznBCICv9YtgWaaa_nWDIH1_GM/-srkOOUlK2u6VrOhrHLwNvW9uhY\"", "id": "Ugwud1sVfboCaSWuyR54AaABAg", "snippet": { "videoId": "ay4MKe1u7Ec", "topLevelComment": { "kind": "youtube#comment", "etag": "\"RmznBCICv9YtgWaaa_nWDIH1_GM/EdeFN_0T_dycmIDzkqVgskOHm6U\"", "id": "Ugwud1sVfboCaSWuyR54AaABAg", "snippet": { "authorDisplayName": "Gulnaz Saydullaeva", "authorProfileImageUrl": "https://yt3.ggpht.com/-9jnflsaG9cs/AAAAAAAAAAI/AAAAAAAAAAA/NRge-Hcjxg8/s28-c-k-no-mo-rj-c0xffffff/photo.jpg", "authorChannelUrl": "http://www.youtube.com/channel/UCKoQIiDBhLNU8cpEMKPfLrQ", "authorChannelId": { "value": "UCKoQIiDBhLNU8cpEMKPfLrQ" }, "videoId": "ay4MKe1u7Ec", "textDisplay": "А у меня не Android 4. 4. 2 у меня на моём стоит Android 5 0 1", "textOriginal": "А у меня не Android 4. 4. 2 у меня на моём стоит Android 5 0 1", "canRate": true, "viewerRating": "none", "likeCount": 1, "publishedAt": "2018-01-22T15:27:39.000Z", "updatedAt": "2018-01-22T15:27:39.000Z" } }, "canReply": true, "totalReplyCount": 0, "isPublic": true } }, { "kind": "youtube#commentThread", "etag": "\"RmznBCICv9YtgWaaa_nWDIH1_GM/Mdis62b6IE0Y3r5zGlGLEDj71pI\"", "id": "UgxPYBqwH2v_tW2cQjt4AaABAg", "snippet": { "videoId": "ay4MKe1u7Ec", "topLevelComment": { "kind": "youtube#comment", "etag": "\"RmznBCIC…
tagged with: python
has title: Youtube Data API v3 does not send nextPageToken on selecting fields in resource
has comment: http://stackoverflow.com/comment/85392857
answer count: 0
has comment: http://stackoverflow.com/comment/85401477
upvote count: 1
type: UnansweredQuestion
score: 1
tagged with: youtube-data-api
downvote count: 0
has comment: http://stackoverflow.com/comment/85394899
favorite count: 0

http://stackoverflow.com/a/49210381
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49210153
has comment: http://stackoverflow.com/comment/85425858
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85425852
has comment: http://stackoverflow.com/comment/85425714
has body: You can use the modulo operator: &gt;&gt;&gt; n = 4 &gt;&gt;&gt; i,j,k = np.ogrid[:n, :n-1, :n] &gt;&gt;&gt; ((j-i+k)%n &lt;= j).reshape(n, -1).view(np.int8) array([[1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1], [0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1], [0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0], [0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1]], dtype=int8) Sandwiched between columns of 0s and 1s: &gt;&gt;&gt; i, jk = np.ogrid[:n, :n*n - n + 2] &gt;&gt;&gt; j, k = divmod(jk + n - 1, n) &gt;&gt;&gt; print(((j-i+k-1)%n &lt; j).view(np.int8)) [[0 1 0 0 0 1 0 0 1 1 0 1 1 1] [0 0 1 0 0 1 1 0 0 1 1 0 1 1] [0 0 0 1 0 0 1 1 0 1 1 1 0 1] [0 0 0 0 1 0 0 1 1 0 1 1 1 1]]
answers question: http://stackoverflow.com/q/49210153

http://stackoverflow.com/q/49140383
tagged with: python-3.x
tagged with: split
answer count: 2
upvote count: 1
has title: Pandas fill column with string.split() from different column based on condition
downvote count: 0
possible better answer: http://stackoverflow.com/a/49140502
tagged with: python
has body: What I want to achieve can be seen in the following tables: So, the idea is to only fill column lag_id if column Port includes string Lag. If so, I shall split such string, keep the number and insert it into the desired column. In order to achieve that, I tried the following: df['lag_id'] = df[df['Port'].str.contains('Lag')]['Port'].apply(lambda s:s.split(' ')[1]) That will partially do the job. I do get string splitting, but the rest of the column lag_id is being emptied. Ideas on how to achieve that? Thanks! Lucas
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
score: 1
has answer: http://stackoverflow.com/a/49140502
has answer: http://stackoverflow.com/a/49140511
accepted answer: http://stackoverflow.com/a/49140511
type: Question

http://stackoverflow.com/q/49245918
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49590743
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85495690
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
tagged with: finance
answer count: 1
has body: I have a df that I scraped from coinmarketcap. I am trying to calculate volitlity metrics for the close_price column but when I use a groupby I'm getting an error message: final_coin_data['vol'] = final_coin_data.groupby('coin_name')['close_price'].rolling(window=30).std() TypeError: incompatible index of inserted column with frame index df structure (the 'Unnamed:0' came after I loaded my CSV): Unnamed: 0 close_price coin_name date high_price low_price market_cap open_price volume 0 1 9578.63 Bitcoin Mar 11, 2018 9711.89 8607.12 149,716,000,000 8852.78 6,296,370,000 1 2 8866.00 Bitcoin Mar 10, 2018 9531.32 8828.47 158,119,000,000 9350.59 5,386,320,000 2 3 9337.55 Bitcoin Mar 09, 2018 9466.35 8513.03 159,185,000,000 9414.69 8,704,190,000 3 1 9578.63 Monero Mar 11, 2018 9711.89 8607.12 149,716,000,000 8852.78 6,296,370,000 4 2 8866.00 Monero Mar 10, 2018 9531.32 8828.47 158,119,000,000 9350.59 5,386,320,000 5 3 9337.55 Monero Mar 09, 2018 9466.35 8513.03 159,185,000,000 9414.69 8,704,190,000 (ignore the incorrect prices, this is the basics of the df) When using the following code: final_coin_data1['vol'] = final_coin_data.groupby('coin_name')['close_price'].rolling(window=30).std().reset_index(0,drop=True) I got a MemoryError. I thought I was using groupby correctly. If I take out the final_coin_data1['vol'] = then I get a series which appears correct, but it won't let me insert back into the df. When I first started this project. I had just 1 coin and used the code below and it calculated volatility no problem. final_coin_data1['vol'] = final_coin_data['close_price'].rolling(window=30).std()
favorite count: 0
accepted answer: http://stackoverflow.com/a/49590743
score: 9
type: Question
upvote count: 9
has title: Why is groupby and rolling not working together?

http://stackoverflow.com/comment/85516032
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49255916
has text: We need to see what code you have used so far. That said it is likely you can use the `insert()` method to get what you want in a gui setting.
type: Comment

http://stackoverflow.com/q/49138462
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85282059
upvote count: 0
accepted answer: http://stackoverflow.com/a/49231231
answer count: 1
has answer: http://stackoverflow.com/a/49231231
favorite count: 0
type: Question
has body: I am working on a website with weekly votations, but only the first three weeks of the month, so in each instance I have a start_date and end_date field. I'd like to know if there's a way to automitically create these instances based on the current date, for instance: Today it is 6 of March, and votations end tomorrow, so a function should be run (tmrw) that, taking into account this month calendar, would fill in the appropiate dates for the next votations. What calendar do you recommend me, and how shoul I do it? (Never mind the automatically run part, I'll go with celery). Thanks!
score: -2
downvote count: 2
tagged with: django
tagged with: python
has title: Calendar in python/django

http://stackoverflow.com/a/49271374
has body: If the fact that text1 and text3 disappeared in your example is just an oversight, I don't think you need multiple capturing groups, just the one for the file name. The brackets and the img string are constant, so you can recreate them. Your pattern should be something like \[img\[([^]])\]\]. You'd replace it with &lt;img src="\1"&gt;. I say "something like" that pattern because I'm not entirely sure how you need to format it to make sure it gets to the regex engine with all the escape characters intact. In Python you'd want to use a raw string, but I have no idea how you apply a regex using Calibre. Similarly, I don't know if the backreference using \1 will work (but I expect that's the most likely form to work in an unknown regex environment).
has comment: http://stackoverflow.com/comment/85583897
type: Answer
has comment: http://stackoverflow.com/comment/85584083
has comment: http://stackoverflow.com/comment/85583984
score: 0
has comment: http://stackoverflow.com/comment/85583090
answers question: http://stackoverflow.com/q/49269581

http://stackoverflow.com/a/68687626
type: Answer
has body: You convert the tensorflow TENSOR into NUMPY ARRAY in the 4 steps (1-4): You convert the INT or FLOAT into the tensorflow TENSOR in the 2 steps (A-B): In my opinion it is recomended to use dtype='float' not dtype='int'. In my model loss int doesn't work. You create a custom loss function in Keras like this. A converting tensorflow tensor into a python list makes it easier to use for a pythoneer. #STEP1 IMPORT TENSORFLOW AND KERAS LOSS import tensorflow as tf from keras.losses import Loss #TO MAKE YOUR LOSS FUNCTION WORK YOU MUST DEFINE A CALL FUNCTION IN A CLASS INHERITING FROM KERAS LOSS CLASS class yourLoss (Loss): def __init__ (self): super().__init__() def call (self, y_true, y_pred): #STEP_A: MAKE A VARIABLE HOLDING YOUR MODEL TENSOR PARAMETERS #MULTIPLYINIG IT BUT 0 MAKES IT EMPTY shapeHolder = y_pred * 0 #STEP3 CAST YOUR TENSOR y_true = tf.cast (y_true, dtype='float') y_pred = tf.cast (y_pred, dtype='float') #STEP4 CONVERT IT TO NUMPY ARRAY y_pred = y_pred.numpy () y_true = y_true.numpy () #YOU CAN CONVERT A TENSOR INTO PYTHON LIST AS WELL #YOU CAN WRITE THE STEPS IN ONE CODE LINE y_true = tf.cast (y_true, dtype='float').numpy ().tolist () y_pred = tf.cast (y_pred, dtype='float').numpy ().tolist () #loss = your loss function #STEP_B: CONVERT THE INTEGER LOSS TO THE WANTED TENSOR #ADDING AN INT TO ZERO TENSOR MAKES ALL TENSOR NUMBERS THE INT #BUT I THINK IT'S BETTER TO USE FLOAT NOT INT return shapeHolder + loss #STEP2 TURN ON TRACING tf.config.run_functions_eagerly (True) model.fit (....) #IT IS RECOMENDED TO TURN IT OFF LATER, A TRACING IS EXPENSIVE tf.config.run_functions_eagerly (False)
score: 0
answers question: http://stackoverflow.com/q/49192051

http://stackoverflow.com/q/49171370
has body: I have an "onclick" element in a webpage whose HTML reads as follows: Fastener I want to search this element using the string "fastener" or "Fastener" using Python + Selenium. The number "3625" will change depending on previous inputs, and hence cannot be searched for. I tried the following, but in vain: br.find_element_by_css_selector("a[@onlick*='fastener']").click() Please suggest ways to do this. Thank you! P.S.: I am using Python 2.7, with Chrome WebDriver and Chrome v62.
type: Question
has answer: http://stackoverflow.com/a/49172673
tagged with: python
upvote count: 4
tagged with: css
has answer: http://stackoverflow.com/a/49172206
accepted answer: http://stackoverflow.com/a/49172206
answer count: 4
has answer: http://stackoverflow.com/a/49175761
tagged with: xpath
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85349505
tagged with: python-2.7
score: 3
possible better answer: http://stackoverflow.com/a/49171616
tagged with: selenium
downvote count: 1
has answer: http://stackoverflow.com/a/49171616
has title: Python + Selenium: How can click on "onclick" elements?
favorite count: 0

http://stackoverflow.com/a/54840006
score: 0
type: Answer
has body: I'm working toward the same goal. I want to DRY up my factories since I'm using polymorphic models. the bad news is the factoryboy DSL removes Meta and Params classes from the attributes. I'm not sure why they do this, possibly it simplifies how they inherit pre and post vars from parent factories? I think they are trying to emulate FactoryGirl from ruby, but don't have the ability to monkey-patch because python... here is the relevant doc. https://factoryboy.readthedocs.io/en/latest/internals.html?highlight=params good luck. PS. I got a little farther by putting the parent Param class outside the parent Factory, but it still doesn't work. import factory class BaseParam: foo=True, bar=False class MyFactory(factory.Factory): class Meta: abstract=False model=Yolo class Params(BaseParam): baz=factory.Trait( foo=False ) MyFactory(baz=True) gives me this TypeError: 'foo' is an invalid keyword argument for this function so Param is clearly not inheriting anything, and is not acting as a normal class.
answers question: http://stackoverflow.com/q/49178024

http://stackoverflow.com/a/49127611
answers question: http://stackoverflow.com/q/49127464
has body: Try using regular expressions: import re lines = """ One_Number_ = "0" if [ One_Number_ == "0" ] """ r = re.compile(r'(\w+)_Number_') print r.findall(lines) Output: ['One', 'One'] Documentation: Python re module: https://docs.python.org/2/library/re.html Regular expression syntax: http://www.regular-expressions.info/
has comment: http://stackoverflow.com/comment/85259775
has comment: http://stackoverflow.com/comment/85275291
score: 0
type: Answer

http://stackoverflow.com/comment/85505653
has text: Really appreciate for your help! I actually need to write the whole list "lis" into csv file instead of only writing one unicode. I still tried yours, edit '/tmp/test' as 'test.csv' and 'w' as 'a', but when I opened the csv file, it shows "? ?" instead of "萬"
comment on: http://stackoverflow.com/a/49250305
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85360612
comment on: http://stackoverflow.com/q/49176476
type: Comment
type: QuestionComment
has text: Is librdkafka installed separately? If not that might be the problem.
score: 0

escpos
tags question: http://stackoverflow.com/q/49186670
type: Tag
tag name: escpos

http://stackoverflow.com/a/49211199
score: 0
type: Answer
has body: This is my solution. However this is not a fast solution. It uses a recursive implementations of the search function. At each recursion it explores all the possible product values for each row (excluding the first elements of the current row, until the diagonal value), and checks if the current solution is valid. If it reaches the recursion's end, it will append the current matrix solution. hypothetically it explore n! solutions, but because I break the search when the solution is incorrect, the search stops before it reach all the possible solutions. import sys, copy from itertools import product def recursiveSearch(actual, index, size, matrices): if index==size-1: for j in range(size): if sum([actual[i][j] for i in range(size)])&gt;1: return if sum([actual[i][j] for i in range(size) for j in range(size)]) == size: matrices.append(actual) return return cur_row = len(actual) for j in range(size): if sum([actual[i][j] for i in range(cur_row)])&gt;1: return pr = product([0, 1], repeat=size-index-1) for p in pr: new_row = [0 for k in range(index+1)] + list(p) new_matrix = copy.deepcopy(actual) new_matrix.append(new_row) recursiveSearch(new_matrix, index+1, size, matrices) if __name__ == '__main__': input_ = int(sys.argv[1]) pr = product([0,1], repeat=input_) matrices = [] for p in pr: recursiveSearch([list(p)], 0, input_, matrices) for m in matrices: print(m) A more efficient solution will be a search for column, and not for row which is how I'm doing the search now, because the check for correctness will require less computation (you need to check only if the current column sums exactly to 1) And of course , the search for columns will need to shift the only 1 along the column
answers question: http://stackoverflow.com/q/49209700

http://stackoverflow.com/a/49273428
has comment: http://stackoverflow.com/comment/85549493
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49273406
type: Answer
answers question: http://stackoverflow.com/q/49273406
score: 3
has body: json.load() is for loading from file. You need json.loads(): data = json.loads(the_page)
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/85295294
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49144891
type: Comment
has text: You have to remove price assignment and assign int(input)) to it. So when ever user enters input price will have it.

http://stackoverflow.com/comment/87160182
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49147829
type: QuestionComment
has text: Also, which OS/distro (including exact version) are you using? And if you know which glibc version, that too.

http://stackoverflow.com/comment/85422322
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49208444
has text: Could you provide [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) to save us a burden of going through the whole tutorial and figuring out where exactly is the data you want to plot?
score: 1

http://stackoverflow.com/a/49244531
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49233871
accepted answer of: http://stackoverflow.com/q/49233871
type: AcceptedAnswer
type: Answer
has body: Ok, I have found the solution for this problem, changing the method from on_data to on_status removed all the issues causing the error 420.
downvote count: 0

http://stackoverflow.com/comment/85278430
type: Comment
type: QuestionComment
has text: 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. In particular, it's not clear what output you expect. If you want to get the sequence in its given order, then your x-axis values need to be that ordering (i.e. [1, 2, 3, 4, 5, ...] This leaves you with *two* lists to plot ... ?
comment on: http://stackoverflow.com/q/49136668
score: 1

http://stackoverflow.com/q/49201735
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85409482
upvote count: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/85408931
downvote count: 0
accepted answer: http://stackoverflow.com/a/49202186
tagged with: python
has comment: http://stackoverflow.com/comment/85409631
has comment: http://stackoverflow.com/comment/85409038
tagged with: timeit
has comment: http://stackoverflow.com/comment/85409526
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/85408704
tagged with: performance
tagged with: random
has comment: http://stackoverflow.com/comment/85409459
has title: Conflicting performance results of random number generators
has comment: http://stackoverflow.com/comment/85409088
has comment: http://stackoverflow.com/comment/85408694
answer count: 1
has body: Coming from my question on Code-Review, some analysis of the performance of random number generating libraries was done, specifically python and numpy's random facilities. One would assume that there would be some differences of performance on different machines, but the overall conclusion would be the same, x is faster than y. However, that is not the case. In Oscar Smith's answer, he performed a test, and got the following results, run on Ubuntu, Python 2.7 and 3.6, NumPy 1.14.1: timeit.timeit('rand(0,1000)', setup='from numpy.random import uniform as rand') 0.7485988769913092 timeit.timeit('rand(0,1000)', setup='from random import uniform as rand') 0.2676771300029941 I performed the same test, and got opposite results, run on RHEL 7.4, Python 2.7.5, NumPy 1.7.1: timeit.timeit("rand(0, 1000)", setup="from numpy.random import uniform as rand") 0.1250929832458496 timeit.timeit("rand(0, 1000)", setup="from random import uniform as rand") 0.47645998001098633 I would expect that these values would be different, but proportionally the same, ie he would get 0.5, 0.1, and I would get 0.25, 0.05. However, we got direct opposite results. What's going on here? And if possible, which library is officially considered faster? An interesting sidenote, run within an online interpreter https://repl.it/languages/python3, native python is faster: Python 3.6.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux import timeit import numpy numpy.__version__ =&gt; '1.14.1' timeit.timeit('rand(0,1000)', setup='from numpy.random import uniform as rand') =&gt; 2.416280833000201 timeit.timeit('rand(0,1000)', setup='from random import uniform as rand') =&gt; 1.0206557700003032
has answer: http://stackoverflow.com/a/49202186
has comment: http://stackoverflow.com/comment/85408767
has comment: http://stackoverflow.com/comment/85409419

http://stackoverflow.com/comment/85485008
has text: Thanks to both of you... I updated my test cases and hope I hope you find these interesting as well as I do.
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49239862

http://stackoverflow.com/q/49148281
score: 0
has answer: http://stackoverflow.com/a/49151394
tagged with: bash
has comment: http://stackoverflow.com/comment/85302375
has body: I filtered issues without subtasks by python: #!/usr/bin/python import sys import json sys.stdout = open('output.txt','wt') datapath = sys.argv[1] data = json.load(open(datapath)) for issue in data['issues']: if len(issue['fields']['subtasks']) == 0: print(issue['key']) in output.txt tasks without subtasks are stored (and it works fine): TECH-729 TECH-124 Now have different issue, it seems values in $p variable isn't passed to CURL (able to login to JIRA but not to create subtasks): while read -r p; do echo $p curl -D- -u user:pass -X POST --data "{\"fields\":{\"project\":{\"key\":\"TECH\"},\"parent\":{\"key\":\"$p\"},\"summary\":\"TestChargen#Nr\",\"description\":\"some description\",\"issuetype\":{\"name\":\"Sub-task\"},\"customfield_10107\":{\"id\":\"10400\"}}}" -H "Content-Type:application/jso#n" https://jira.companyu.com/rest/api/latest/issue/ done &lt;output.txt echo output is as it should TECH-731 TECH-729 (so curl should run twice for every output value But curl just logs in without creating subtasks, when hardcoding instead of $p then curl executes twice for same project ID
tagged with: jira-rest-api
has comment: http://stackoverflow.com/comment/85307705
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/85303066
has comment: http://stackoverflow.com/comment/85306946
has comment: http://stackoverflow.com/comment/85301401
type: UnansweredQuestion
tagged with: python
has title: Search txt file line by line into variable and for each value run CURL command

http://stackoverflow.com/comment/85343549
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49168978
has text: Thank you for your very swift response, the first one works perfectly, but I will look into the others as well. Could you explain what you mean with 'the difficulty of vectorizing the replacement operation'?

http://stackoverflow.com/q/49221269
has answer: http://stackoverflow.com/a/49221620
has comment: http://stackoverflow.com/comment/85446541
tagged with: scrapy
type: Question
type: UnansweredQuestion
has title: Scrapy Crawl Page and Supage but crawls only one item
answer count: 1
tagged with: python
has body: I Have an issue with my Spider. I tried to follow some tutorial to understand the scrapy a little bit better and extended the tutorial to crawl also subpages. The issue of my spider is that it only crawls one element of the entry page and not 25 as it should be on the page. I have no clue where the failure is. Perhaps somebody of you can help me here: from datetime import datetime as dt import scrapy from reddit.items import RedditItem class PostSpider(scrapy.Spider): name = 'post' allowed_domains = ['reddit.com'] def start_requests(self): reddit_urls = [ ('datascience', 'week') ] for sub, period in reddit_urls: url = 'https://www.reddit.com/r/' + sub + '/top/?sort=top&amp;t=' + period yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): # get the subreddit from the URL sub = response.url.split('/')[4] # parse thru each of the posts for post in response.css('div.thing'): item = RedditItem() item['title'] = post.css('a.title::text').extract_first() item['commentsUrl'] = post.css('a.comments::attr(href)').extract_first() ### scrap comments page. request = scrapy.Request(url=item['commentsUrl'], callback=self.parse_comments) request.meta['item'] = item return request def parse_comments(self, response): item = response.meta['item'] item['commentsText'] = response.css('div.comment div.md p::text').extract() self.logger.info('Got successful response from {}'.format(response.url)) yield item Thanks for your help. BR
has comment: http://stackoverflow.com/comment/85446035
score: 0

http://stackoverflow.com/a/49190912
has body: Are you sure you want to do that ? All 12 digit hex numbers would fill up the largest supercomputer (281474976710656 values). Actually, all first 100000000 addresses have a zero for the first five digits (as 16^7 = 268435456). Do you really need to store all these addresses ? If yes, I would recommend to use a single range(100000000) and leave the values as integers, only convert to hex when needed. This will spare a lot of space. If not possible, it is probably more efficient to work with a string of 12 hex characters that you increment yourself rather than using a costly formatting operation. And please, don't store those 500000000 ':' useless separators.
type: Answer
has comment: http://stackoverflow.com/comment/85388451
has comment: http://stackoverflow.com/comment/85423505
answers question: http://stackoverflow.com/q/49190186
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85393737
type: AnswerComment
has text: I had already tried that, but it dosn't work, the image isn't created
type: Comment
comment on: http://stackoverflow.com/a/49194412
score: 0

http://stackoverflow.com/comment/85472961
type: Comment
comment on: http://stackoverflow.com/a/49231354
score: 0
type: AnswerComment
has text: Can i ask one more question along with this? How do i get exclusive C2s count for each C1?. In the above example a- 0 , b-0 , c-1

http://stackoverflow.com/comment/85352986
type: Comment
score: 0
has text: Is the order important?
comment on: http://stackoverflow.com/q/49173955
type: QuestionComment

http://stackoverflow.com/q/49225177
has comment: http://stackoverflow.com/comment/85495174
favorite count: 0
type: Question
tagged with: python-3.x
has title: Invalid Syntax Error on Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85454093
has comment: http://stackoverflow.com/comment/85454033
tagged with: python
has body: warrants = ["Adela","Arya","The Big D","Wei Xuen","Rebecca"] Fines = [] totalFines= 0 def enterFine(): global totalFines name = input("Enter the full name of the driver: ") checkwarrant(name) validInput = False while validInput == False: try: speedlimit = int(input("Enter the speed limit across your area :")) speed = int(input("Enter the speed of the driver : ")) amountOver = speed - speedlimit if amountOver &gt; 0: validInput = True if amountOver &lt; 10: print("This person should be charged $30") totalFines +=30 elif amountOver &lt; 15: print("This person should be charged $45") totalFines +=45 elif amountOver &lt; 20: print("This person should be charged $60") totalFines +=60 else: print("This person is to be charged $420") fines.append([name, amountOver]) else: print("Error") except: print("Error") def checkWarrant(name): for person in warrants: if person == name: print(person.upper(),"is wanted for using Hooktronic cheats") def printsummary(): print("Total Fines for today :" , len(fines)) for number in range(0, len(fines)): print(number +1, ") Name: ", fines[number][0]," Amount Over Limit: $", fines[number][1] print("Total amount of fines: $", totalFines) moreInput = "Y" while moreInput == "Y": enterFine() askIntput = "X" while askInput != "Y" and askIntput != "N": askInput = input("Do you wish to enter another person to the database? (Y/N): ") if askInput == "N": moreInput = "N" printsummary() Hi, i have an error with this code, when i run this program it comes up with an invalid syntax message. It would be nice if you guys help me out. Thank you Hi, i have an error with this code, when i run this program it comes up with an invalid syntax message. It would be nice if you guys help me out. Thank you Hi, i have an error with this code, when i run this program it comes up with an invalid syntax message. It would be nice if you guys help me out. Thank you Hi, i have an error with this code, when i run this program it comes up with an invalid syntax message. It wo…
tagged with: syntax-error
downvote count: 4
has comment: http://stackoverflow.com/comment/85455192
tagged with: syntax
has comment: http://stackoverflow.com/comment/85454028
upvote count: 0
score: -4
answer count: 1
has answer: http://stackoverflow.com/a/49225939

http://stackoverflow.com/q/49227183
linked to: http://stackoverflow.com/q/3723220
has comment: http://stackoverflow.com/comment/85563776
favorite count: 0
type: Question
score: 5
tagged with: python-imaging-library
accepted answer: http://stackoverflow.com/a/49296707
upvote count: 5
has comment: http://stackoverflow.com/comment/85578363
has comment: http://stackoverflow.com/comment/85566753
tagged with: django
has answer: http://stackoverflow.com/a/49296707
tagged with: python
has comment: http://stackoverflow.com/comment/85578236
type: AnsweredQuestion
has body: I'm using PIL to compress uploaded images(FileField). However I'm getting an error which I believe is a problem of double saving? (saving my image, and then saving the whole form which includes the image). I wanted to perform commit=False when I'm saving the image but it doesn't appear it's possible. Here's my code: ... if form_post.is_valid(): instance = form_post.save(commit=False) instance.user = request.user if instance.image: filename = instance.image instance.image = Image.open(instance.image) instance.image.thumbnail((220, 130), Image.ANTIALIAS) instance.image.save(filename, quality=60) instance.save() returns 'JpegImageFile' object has no attribute '_committed' error on the last line (instance.save()) Can someone identify the problem? - and any idea how I can fix it? Full Traceback: File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/zorgan/Desktop/app/lib/python3.5/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/Users/zorgan/Desktop/project/site/post/views.py" in post 68. if uploaded_file_type(instance) is True: File "/Users/zorgan/Desktop/project/site/functions/helper_functions.py" in uploaded_file_type 12. f = file.image.read(1024) Exception Type: AttributeError at /post/ Exception Value: 'JpegImageFile' object has no attribute 'read' Full models: class Post(models.Model): user = models.ForeignKey(User, blank=True, null=True) title = models.TextField(max_length=95) image = models.FileField(null=True, blank=True) and the accompanying Po…
has title: 'JpegImageFile' object has no attribute '_committed' error when using PIL
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85590341

http://stackoverflow.com/a/49214519
has body: Here is a collections.Counter solution, which has O(n) complexity. The results of the count can easily be brought back into pandas, if required. from collections import Counter c = sum((Counter(df['num']) for df in [df1, df2, df3]), Counter()) c_masked = {k: v for k, v in c.items() if v&gt;=2} # {23: 2, 34: 3, 90: 3, 56: 2} df = pd.DataFrame.from_dict(c_masked, orient='index') # 0 # 23 2 # 34 3 # 90 3 # 56 2
upvote count: 2
answers question: http://stackoverflow.com/q/49214286
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/q/49185342
has answer: http://stackoverflow.com/a/49185403
has comment: http://stackoverflow.com/comment/85376372
type: Question
has answer: http://stackoverflow.com/a/49185381
tagged with: python
score: -2
has title: how to add values in dictionary that also already in dictionary by using .get()
tagged with: dictionary
has answer: http://stackoverflow.com/a/49185404
favorite count: 0
has body: I want to add multiple values in overlapped(same one, i mean) key by using .get() I already searched google with these kewords but they were kinda different problems. So, I'm just looking for new method to solve this. ''' dictionary = {} dictionary[key] = dictionary.get(key, {}) + {value} ''' but apparently this code is impossible and there's TypeError +: 'set' and 'set' so I tried to make two dictionary and put default is [] and + [value] but it wasn't work, too... ''' for example, key = exercise, study, music, etc... values = exercise : basketball, football , study : science, history, math , muscic : classic etc Result that i want is... {'excercise': {'basketball', 'football'}, 'study': {'science', 'history', 'math'}, 'muscic': {'classic'} ..} ''' What should I do?
upvote count: 0
downvote count: 2
answer count: 3
type: UnansweredQuestion

http://stackoverflow.com/q/49232823
accepted answer: http://stackoverflow.com/a/49232907
has body: I have a list that its elements are composed of a letters and numbers as shown below : ['H1', 'H100', 'H10', 'H3', 'H2', 'H6', 'H11', 'H50', 'H5', 'H99', 'H8'] I wanted to sort it, so I used the function sort, but I got as output : &gt;&gt;&gt; a = ['H1', 'H100', 'H10', 'H3', 'H2', 'H6', 'H11', 'H50', 'H5', 'H99', 'H8'] &gt;&gt;&gt; print sorted(a) ['H1', 'H10', 'H100', 'H11', 'H2', 'H3', 'H5', 'H50', 'H6', 'H8', 'H99'] However, I want the output to be : ['H1', 'H2', 'H3', 'H5', 'H6', 'H8', 'H10', 'H11', 'H50', 'H99', 'H100'] Does anyone has an idea how to do this please? Thank you
type: AnsweredQuestion
has title: Python: Sort a list of strings composed of letters and numbers
tagged with: list
score: 5
answer count: 1
linked to: http://stackoverflow.com/q/4836710
downvote count: 0
tagged with: sorting
duplicate of: http://stackoverflow.com/q/4836710
favorite count: 0
type: Question
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/49232907

excel
tags question: http://stackoverflow.com/q/49138618
tags question: http://stackoverflow.com/q/49170390
tags question: http://stackoverflow.com/q/49258105
tags question: http://stackoverflow.com/q/49135870
tags question: http://stackoverflow.com/q/49157523
tags question: http://stackoverflow.com/q/49167418
tag name: excel
tags question: http://stackoverflow.com/q/49240707
tags question: http://stackoverflow.com/q/49234227
tags question: http://stackoverflow.com/q/49220409
tags question: http://stackoverflow.com/q/49276547
tags question: http://stackoverflow.com/q/49209826
tags question: http://stackoverflow.com/q/49260826
tags question: http://stackoverflow.com/q/49240332
type: Tag
tags question: http://stackoverflow.com/q/49153696
tags question: http://stackoverflow.com/q/49238746
tags question: http://stackoverflow.com/q/49271526
tags question: http://stackoverflow.com/q/49223493
tags question: http://stackoverflow.com/q/49251994
tags question: http://stackoverflow.com/q/49152950
tags question: http://stackoverflow.com/q/49234432
tags question: http://stackoverflow.com/q/49176248
tags question: http://stackoverflow.com/q/49209136
tags question: http://stackoverflow.com/q/49223999
tags question: http://stackoverflow.com/q/49197793
tags question: http://stackoverflow.com/q/49223809
tags question: http://stackoverflow.com/q/49271943
tags question: http://stackoverflow.com/q/49138153
tags question: http://stackoverflow.com/q/49204639
tags question: http://stackoverflow.com/q/49273261
tags question: http://stackoverflow.com/q/49213278
tags question: http://stackoverflow.com/q/49139905
tags question: http://stackoverflow.com/q/49266771
tags question: http://stackoverflow.com/q/49123132
tags question: http://stackoverflow.com/q/49243794

http://stackoverflow.com/comment/85473646
score: 3
comment on: http://stackoverflow.com/q/49234606
type: Comment
type: QuestionComment
has text: Please reduce your code to the [minimum](https://stackoverflow.com/help/mcve). Nobody here wants to debug hundreds of lines of unknown code.

http://stackoverflow.com/a/49192472
answers question: http://stackoverflow.com/q/49192291
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85390194
has comment: http://stackoverflow.com/comment/85391243
accepted answer of: http://stackoverflow.com/q/49192291
has body: This is a json string. Not sure why it isn't displaying russian characters in the raw, but if you do import json s = &lt;your long string&gt; obj = json.loads(s) print(obj) you'll get the correct display. [{'href': 'http://www.nord-remont.ru/remont_holodilnikov', 'index': '0', 'txt': 'Ремонт холодильников в Екатеринбурге Индезит, Атлант, Самсунг ...'}, {'href': 'http://holodilnik96.ru/', 'index': '1', 'txt': 'Ремонт холодильников на дому'}, {'href': 'http://iceberg-ekb.ru/', 'index': '2', 'txt': 'Ремонт холодильников на дому в Екатеринбурге'}, {'href': 'http://ekathomemaster.ru/', 'index': '3', 'txt': 'Ремонт холодильников на дому в Екатеринбурге. Недорого.'}, {'href': 'http://www.ekaterinburg.holmaster.ru/', 'index': '4', 'txt': 'Ремонт холодильников на дому в Екатеринбурге.'}, {'href': 'https://holodilnik66.ru/', 'index': '5', 'txt': 'Ремонт холодильников на дому в Екатеринбурге'}, {'href': 'http://rembt96.ru/remont-holodilnikov-ekaterinburg', 'index': '6', 'txt': 'Ремонт холодильников цены в Екатеринбурге - Техцентр ПОЛЮС'}, {'href': 'http://www.holodilnyj-centr-ekaterinburg.ru/', 'index': '7', 'txt': 'Ремонт холодильников в Екатеринбурге. НА ДОМУ!'}, {'href': 'http://remhol66.ru/', 'index': '8', 'txt': 'Ремонт холодильников на дому'}, {'href': 'http://holodprof.ru/', 'index': '9', 'txt': 'ХолодПрофи | Ремонт холодильников на дому с гарантией до 12 ...'}] To get the russian-character json back, do json.dumps(obj, ensure_ascii=False).
has comment: http://stackoverflow.com/comment/85391278
has comment: http://stackoverflow.com/comment/85390258
has comment: http://stackoverflow.com/comment/85390961
score: 1
has comment: http://stackoverflow.com/comment/85390616
has comment: http://stackoverflow.com/comment/85389993
type: Answer
has comment: http://stackoverflow.com/comment/85391105
has comment: http://stackoverflow.com/comment/85390233
downvote count: 0

http://stackoverflow.com/comment/85481716
type: AnswerComment
comment on: http://stackoverflow.com/a/49239032
score: 0
type: Comment
has text: I think this is not guaranteed to keep the order of the original array (because dictionaries are not sorted)

http://stackoverflow.com/q/49154433
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49155406
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85314525
has title: Accessing few frames only in an OME-TIFF format
answer count: 1
tagged with: image
downvote count: 1
favorite count: 0
type: Question
tagged with: tiff
has body: I am using the tifffile package for processing OME-TIFF files. My OME-TIFF file contains > 6000 images and I would like to read only a number of frames from the whole file. Is it possible to access the nth up to (n+m)th frame without reading the whole file?
upvote count: 0

http://stackoverflow.com/a/49216915
has comment: http://stackoverflow.com/comment/85438330
downvote count: 0
score: 7
upvote count: 7
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85438153
answers question: http://stackoverflow.com/q/49216866
has comment: http://stackoverflow.com/comment/85438046
has body: You can use a try-except block to ignore the exception like this: from selenium.common.exceptions import NoSuchElementException try: driver.find_element_by_xpath(...) except NoSuchElementException: print("Element not found")
type: Answer
has comment: http://stackoverflow.com/comment/85438054
accepted answer of: http://stackoverflow.com/q/49216866

http://stackoverflow.com/a/49229354
score: 0
answers question: http://stackoverflow.com/q/49228915
has body: For that you really don't need regex. You can perform faster than re. But still if you want to do with re following is solution. import re s = ['Hello','@sdfss','sdfh787s','World'] # copied from above solution print [i for i in s if re.match(r'[A-Za-z]+$', i) ]
type: Answer

http://stackoverflow.com/comment/85280258
type: QuestionComment
has text: Checking such error without running is theoretically impossible. You can solve halting problem with such solver.
score: 0
comment on: http://stackoverflow.com/q/49137369
type: Comment

http://stackoverflow.com/q/49167655
type: UnansweredQuestion
score: -2
has title: How to print nouns and respective adjectives from a sentence using spacy
tagged with: python
has answer: http://stackoverflow.com/a/49168341
has body: This is the python code. import spacy from nltk import Tree en_nlp = spacy.load('en') doc = en_nlp(u"Photos under low lighting are poor, both front and back cameras.") def tok_format(tok): return "_".join([tok.orth_, tok.tag_]) def to_nltk_tree(node): if node.n_lefts + node.n_rights &gt; 0: return Tree(tok_format(node), [to_nltk_tree(child) for child in node.children]) else: return tok_format(node) [to_nltk_tree(sent.root).pretty_print() for sent in doc.sents] The outputlooks like this: are_VBP _________________|___________________ | | | Photos_NNS | | | | | | | | | under_IN cameras_NNS | | | | | | | | lighting_NN front_NN | | | | _________|_________ poor_JJ ,_, ._. low_JJ both_CC and_CC back_NN Now, I want something like, [(Photos,poor),(lighting,low)] as (noun,adjective) pairs from this tree.
tagged with: spacy
downvote count: 2
answer count: 1
favorite count: 0
type: Question
upvote count: 0

http://stackoverflow.com/comment/85248866
type: Comment
type: QuestionComment
has text: You're passing a list to your function: `nextlink = findworld(headq)` and then comparing it to a string: `if(x == world[c][0])`. So that's never going to evaluate to true.
comment on: http://stackoverflow.com/q/49121605
score: 1

http://stackoverflow.com/comment/85569361
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49243018
has text: There are many strategies for dealing with NaNs in machine learning, you just need to decide which one is appropriate for you. This is part of feature engineering and is where data scientists have to earn their money. What does `percent_change` mean in this context? Daily fluctuation? If no trading, then there is no fluctuation, so just set to 0. Or maybe remove the row completely? Try both and see what effects there are in your model.

http://stackoverflow.com/comment/85929432
has text: Thanks for your input but I was looking for code that iterates through all chats but this code will only copy data of chat that is already open.
comment on: http://stackoverflow.com/a/49423913
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49163558
has comment: http://stackoverflow.com/comment/85332893
has comment: http://stackoverflow.com/comment/85333247
has comment: http://stackoverflow.com/comment/85332810
score: 1
has comment: http://stackoverflow.com/comment/85332703
has comment: http://stackoverflow.com/comment/85332789
has body: Hi guys so I wrote some code as a nested loop for school, which iterates over multiple lists inside a list which have grades for different subjects and then creates a new list with the averages of each of those courses like so. &gt;&gt;&gt; new_list = [] &gt;&gt;&gt; for x in range(len(grades)): sum_of_grades = 0 for i in range(len(grades[x])): sum_of_grades = sum_of_grades + grades[x][i] new_list.append(sum_of_grades / len(grades[x])) &gt;&gt;&gt; new_list [75.0, 85.0, 90.0] It works perfectly with no issues when I run this code in Idle. The issue is when I create a function on another file. It keeps saying new list is not defined. def averages(grades): ''' (list of a list of numbers) -&gt; list of float Return a new list in which each item is the average of the grades in the inner list at the corresponding position &gt;&gt;&gt; averages = [[70, 75, 80], [70, 80, 90, 100], [80, 100]] [75.0, 85.0, 90.0] ''' new_list = [] for x in range(len(grades)): sum_of_grades = 0 for i in range(len(grades[x])): sum_of_grades = sum_of_grades + grades[x][i] new_list.append(sum_of_grades / len(grades[x])) print(new_list) Any explanation to help me out would be greatly appreciated. Here is the error message: Traceback (most recent call last): File "&lt;pyshell#14&gt;", line 1, in &lt;module&gt; new_list NameError: name 'new_list' is not defined I created a insideloops.py file where I run the bottom code of: def averages(grades): And then i save the file and run module from idle and then call the function in idle with averages = [[70, 75, 80], [70, 80, 90, 100], [80, 100]]. I tried to troubleshoot as well using new_list as a global var and importing it into the function and it looks like nothing is being appended to the list. **Thanks for all the help everyone. I was calling the function like an array instead of like a function. ** How I was calling it: averages = [[70, 75, 80], [70, 80, 90, 100], [80, 100]] How I called it when it started to work: averages = ([[70, 75, 80], [70, 80,…
has comment: http://stackoverflow.com/comment/85332725
tagged with: python
has comment: http://stackoverflow.com/comment/85332879
has comment: http://stackoverflow.com/comment/85332680
has comment: http://stackoverflow.com/comment/85332900
has comment: http://stackoverflow.com/comment/85332700
has title: My array changes in IDLE but not when I import the function
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85332847
downvote count: 0
has comment: http://stackoverflow.com/comment/85332876
upvote count: 1
has comment: http://stackoverflow.com/comment/85333077
has comment: http://stackoverflow.com/comment/85332815
has comment: http://stackoverflow.com/comment/85332731
favorite count: 0
has comment: http://stackoverflow.com/comment/85332727
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85332832

http://stackoverflow.com/comment/85334910
comment on: http://stackoverflow.com/q/49164667
has text: do you really want the first element of tuples as string?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85329338
type: QuestionComment
score: 5
has text: Sounds like Virtual Studio doesn't support Python 3.7 yet. It's still in Beta, I wouldn't expect there to be wide support just yet. Why are you using a pre-release version of Python? Why not use Python 3.6 for now?
comment on: http://stackoverflow.com/q/49161805
type: Comment

http://stackoverflow.com/comment/85530680
type: Comment
type: QuestionComment
has text: Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [On topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here.
score: 1
comment on: http://stackoverflow.com/q/49263524

http://stackoverflow.com/comment/85267483
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49130258
has text: Can you share the url?

http://stackoverflow.com/q/49254128
upvote count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/49254565
has body: This question concerns the standard UserCreationForm within Django, and the way that passwords are stored, extracted and used through a request object. Specifically the fact that I seem to be able to print raw passwords through print(request.POST). File contents will be provided at the end of this post. I have created a registration page. I have set up a very basic class-based view that authenticates and logs the newly created user in. The actual HTML of that page is rendered automatically in this case, through {{ form.as_p }} where form is an instance of UserCreationForm. How come, when I execute print(request.POST), I get something along the lines of this returned: &lt;QueryDict: {'csrfmiddlewaretoken': ['keeping_this_private'], 'username': ['William'], 'password1': ['ACTUALPASSWORD'], 'password2': ['ACTUALPASSWORD'], 'button': ['']}&gt; Is this really secure? As I have only been programming for a couple of months, I am still learning. Views.py: class RegisterView(View): def get(self, request): form = UserCreationForm() return render(request, 'authentication/registration.html', {'form': form}) def post(self, request): form = UserCreationForm(request.POST) if form.is_valid(): print(request.POST) form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: return render(request, 'authentication/registration.html', {'form': form}) Registration.html {% extends 'base.html' %} {% block body %} &lt;body class="text-center"&gt; &lt;form method="post"&gt; {% csrf_token %} {{ form.as_p }} &lt;button type="submit" name="button"&gt;&lt;/button&gt; &lt;/form&gt; &lt;/body&gt; {% endblock %} Urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^register/$', RegisterView.as_view(), name='register'), ...
tagged with: python
has answer: http://stackoverflow.com/a/49254565
type: Question
answer count: 2
has title: Django: raw passwords via request.POST
tagged with: django
has answer: http://stackoverflow.com/a/49254519
accepted answer: http://stackoverflow.com/a/49254519
favorite count: 0
type: AnsweredQuestion
score: 3

http://stackoverflow.com/comment/85443873
comment on: http://stackoverflow.com/a/49220035
has text: yeah.. that was actually a mistake on my part, ive corrected it but still doesn't display the user's listing on the profile page
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85271713
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49129471
has text: R searches for packages in the `R_LIBS_USER` environment variable. My first suggestion would be to run R as `R_LIBS_USER=/path/to/conda/R/library R`. Alternatively, you can set the library path from inside R with `.libPaths("/path/to/conda/R/library")`.
type: Comment

http://stackoverflow.com/q/49207179
has answer: http://stackoverflow.com/a/49207224
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/49207224
type: Question
has title: How to read a text file from within Django view function?
has body: I have the following code in one of my view functions: def results(request): data_file = open('data.txt', 'r') data = data_file.read() context = {'rooms': data} return render(request, 'javascript/results.html',context) The file 'data.txt' is located in the same folder as my "views.py". However, I am getting "FileNotFoundError at /results" error. My 'results.html' looks like this: &lt;p&gt; {{ rooms }}&lt;/p&gt; What is the correct way to pass data from a text file to a Django view function, and then display the data in the template? Should I use static files instead?
tagged with: django
tagged with: python
possible better answer: http://stackoverflow.com/a/76655700
has answer: http://stackoverflow.com/a/76655700
type: AnsweredQuestion
score: 3
upvote count: 3
answer count: 2

http://stackoverflow.com/q/49220022
answer count: 5
has title: How can mypy ignore a single line in a source file?
has answer: http://stackoverflow.com/a/64787076
type: AnsweredQuestion
has body: I'm using mypy in my python project for type checking. I'm also using PyYAML for reading and writing the project configuration files. Unfortunately, when using the recommended import mechanism from the PyYAML documentation this generates a spurious error in a try/except clause that attempts to import native libraries: from yaml import load, dump try: from yaml import CLoader as Loader, CDumper as Dumper except ImportError: from yaml import Loader, Dumper On my system CLoader and CDumper aren't present, which results in the errors error: Module 'yaml' has no attribute 'CLoader' and error: Module 'yaml' has no attribute 'CDumper'. Is there a way to have mypy ignore errors on this line? I was hoping that I could do something like this to have mypy skip that line: from yaml import load, dump try: from yaml import CLoader as Loader, CDumper as Dumper # nomypy except ImportError: from yaml import Loader, Dumper
has answer: http://stackoverflow.com/a/76817009
tagged with: python-typing
favorite count: 0
has answer: http://stackoverflow.com/a/75438901
tagged with: mypy
accepted answer: http://stackoverflow.com/a/49220098
possible better answer: http://stackoverflow.com/a/59549683
type: Question
score: 292
upvote count: 292
has answer: http://stackoverflow.com/a/49220098
has answer: http://stackoverflow.com/a/59549683
downvote count: 0
tagged with: python

http://stackoverflow.com/q/49205092
downvote count: 0
has comment: http://stackoverflow.com/comment/85415477
tagged with: asynchronous
has comment: http://stackoverflow.com/comment/85415461
favorite count: 0
type: Question
upvote count: 2
tagged with: function
has answer: http://stackoverflow.com/a/49205148
accepted answer: http://stackoverflow.com/a/49205148
has title: Break out of loop while calling function in python
tagged with: python
has comment: http://stackoverflow.com/comment/85415474
score: 2
type: AnsweredQuestion
has body: I have a function called evaluate and it is a function that takes time to complete. It then resumes a loop, skipping that iteration: My code: array = []#some huge array containing different ways of expressing greetings def main(resumeLocation): for a in range(len(array)): i = array[a] if a &lt; resumeLocation: continue else: if (i == "Hello") answer(i, a) break def answer(input, resumeLocation): # process answer resumeLoop(resumeLocation) now, in order for the function not to loop infinitely, I need to skip the iteration where I process the answer, so I need to break the loop, call that function, then resume the loop, however, I cannot seem to work out how to do this. any suggestions are helpful. Thank you
answer count: 1

http://stackoverflow.com/q/49258642
score: 0
has comment: http://stackoverflow.com/comment/85521469
tagged with: url
has comment: http://stackoverflow.com/comment/85520406
type: Question
has comment: http://stackoverflow.com/comment/85520614
answer count: 0
has comment: http://stackoverflow.com/comment/85542833
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: regex
has body: I have an app in django - 1.11. When changing the language in the template, the address appears: localhost:8000/en/events/None/None/None Below solution is OK. My question is it possible to join these 4 regexes with one regex? For example, add something like or into regex? My dirty solution with few url regex: url(r'^$', views.ListView.as_view(), name='list'), url(r'^(?:/(?P&lt;filter1&gt;[a-zA-Z0-9-]+))?$', views.ListView.as_view(), name='list'), url(r'^(?:/(?P&lt;filter1&gt;[a-zA-Z0-9-]+))?(?:/(?P&lt;filter2&gt;[a-zA-Z0-9-]+))?$', views.ListView.as_view(), name='list'), url(r'^(?:/(?P&lt;filter1&gt;[a-zA-Z0-9-]+))?(?:/(?P&lt;filter2&gt;[a-zA-Z0-9-]+))?(?:/(?P&lt;filter3&gt;[a-zA-Z0-9-]+))?$', views.ListView.as_view(), name='list'),
has title: django url with or condition

http://stackoverflow.com/q/49134759
type: Question
has comment: http://stackoverflow.com/comment/85275009
has comment: http://stackoverflow.com/comment/85275932
has body: Specifically, I have django model objects I'd like to add properties to at runtime. It'd be great if this would work on any python class outside of Django. I have the following models models.py class person(models.Model): # ... firstname=models.TextField(max_length=100) lastname=models.TextField(max_length=100) type=models.TextField(max_length=100) address = models.ForeignKey(address, null=True) class event(models.Model): date=models.DateTimeField(auto_now=True ) name=models.CharField(max_length=100) attendees = models.ManyToManyField(person) def main(): p = person() p.fisrtsname="Firsty" p.lastname="Lasty" p.addnewproperty(newtemporaryproperty) p.newtemporaryproperty="This is a new temporary property" when i use person.newtemporaryproperty=property("") I get a "Can't set attribute error" when trying to add a value to it. I may be using it wrong. EDIT What i want to do is see if each person in a model has attended an event. and if they have, put a checkbox by their name. Here are the additional related files tables.py class AttendeesTable(tables.Table): firstname = tables.Column() lastname = tables.Column() here = tables.TemplateColumn('&lt;input id="attendee_{{ record.pk }}" {{ record.here }} type="checkbox" /&gt;', verbose_name="Here?") class Meta: attrs = {'id': 'attendancetable', 'width': '100%', 'class': 'table table-hover'} template = 'django_tables2/bootstrap.html' row_attrs = { 'id': lambda record: str(record.pk), } views.py def markattendancepage(request): person.here = "" people= person.objects.all() groups = group.objects.all() eventid= 1 #set to 1 for testing table=None for p in people: if event.objects.filter(id=eventid, attendees__pk=p.id).exists(): p.here = "checked" else: p.here = "" table = app.tables.AttendeesTable(people) RequestConfig(request, paginate=False).configure(table) return render(request, 'app/user/attendancechecker.html', {'attendeetable':table}) pass
has comment: http://stackoverflow.com/comment/85274586
answer count: 1
downvote count: 0
score: 6
tagged with: django
has comment: http://stackoverflow.com/comment/85274193
has comment: http://stackoverflow.com/comment/85274435
favorite count: 0
has comment: http://stackoverflow.com/comment/85275723
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85275347
has comment: http://stackoverflow.com/comment/85275785
accepted answer: http://stackoverflow.com/a/49135203
has comment: http://stackoverflow.com/comment/85274127
has comment: http://stackoverflow.com/comment/85274289
has answer: http://stackoverflow.com/a/49135203
has title: Add properties to django models at runtime?
tagged with: python
upvote count: 6

http://stackoverflow.com/comment/85353982
type: Comment
comment on: http://stackoverflow.com/a/49168255
score: 0
type: AnswerComment
has text: cratedb really lifts of, when you use it on several nodes, also the performance on unix based systems is better. you might want to use several connections writing to cratedb and also make sure sharding is optimized.

http://stackoverflow.com/comment/85250092
type: QuestionComment
has text: Please fix the indentation of the code in your question.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49122104

http://stackoverflow.com/a/49258707
has comment: http://stackoverflow.com/comment/85521978
has comment: http://stackoverflow.com/comment/85522881
has comment: http://stackoverflow.com/comment/85522537
has comment: http://stackoverflow.com/comment/85520941
score: 0
answers question: http://stackoverflow.com/q/49258269
type: Answer
has comment: http://stackoverflow.com/comment/85522806
has comment: http://stackoverflow.com/comment/85521831
has body: Another possible way, import csv data = csv.reader(open('example.csv', 'r')) emails = {'@example.co.uk', '@moreexamples.com', 'lastexample.com'} for row in data: if any(email in cell for cell in row for email in emails): print(row)

http://stackoverflow.com/a/49139661
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85284769
downvote count: 0
has comment: http://stackoverflow.com/comment/85284965
has body: If any of the inner ifs fail, it will return None, as the outer if/elif was taken and therefore the else: block will not be executed. To be clear, their entire function is equivalent to: def Win_Loss(my_history, their_history): if len(my_history) &gt; 1 and len(their_history) &gt; 1: if (their_history[-1] == 's' and my_history[-1] == 'r'): return 'p' else: return "p" because once that first if is taken, all the other elifs cannot be taken. Since they have the same condition, all of the elifs will never be reached. If you take the else: out, and just default return "p", it will guarantee a return value: elif len(my_history) &gt; 1 and len(their_history) &gt; 1: if (their_history[-1] == 'p' and my_history[-1] == 'p'): return 's' # If anything else happens return "p" but that doesn't fix the root issue. Alternatively, they could combine the conditionals: if len(my_history) &gt; 1 and len(their_history) &gt; 1 and (their_history[-1] == 's' and my_history[-1] == 'r'): return 'p' which will also avoid the issue, as no internal conditionals can jump the returns and the else: will work as expected. As others have mentioned, the whole outer if block is superfluous. For my girls (I teach 11-13 y/os), I'd suggest they move the default return to the top... then you don't have to check for each one whether the lists are large enough: if not (len(my_history) &gt; 1 and len(their_history) &gt; 1): return "p" # default value elif their_history[-1] == 's' and my_history[-1] == 'r': return 'p' elif their_history[-1] == 'r' and my_history[-1] == 'p': return 's' elif their_history[-1] == 'p' and my_history[-1] == 's': return 'r' elif their_history[-1] == 's' and my_history[-1] == 'p': return 'r' elif their_history[-1] == 'r' and my_history[-1] == 's': return 'p' elif their_history[-1] == 'p' and my_history[-1] == 'r': return 's' elif their_history[-1] == 's' and my_history[-1] == 's': return 'r' elif their_history[-1] == 'r' and my_history[-1] == 'r': return 'p' elif their_history[-1] …
type: Answer
has comment: http://stackoverflow.com/comment/85284753
has comment: http://stackoverflow.com/comment/85284648
answers question: http://stackoverflow.com/q/49139626
score: 3
accepted answer of: http://stackoverflow.com/q/49139626
upvote count: 3

http://stackoverflow.com/q/49175933
favorite count: 0
has comment: http://stackoverflow.com/comment/85358843
has comment: http://stackoverflow.com/comment/85357531
has comment: http://stackoverflow.com/comment/85357238
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85358368
tagged with: parsing
type: Question
has comment: http://stackoverflow.com/comment/85357145
tagged with: python-3.x
has title: How to get all urls on a specific google search python
has body: So I am trying to create a program that gets all the urls on a google webpage search, and returns a list of them all in order of where they are on that page. So if its the top url on a google search page for "random", this link, then the first item in the list that should be returned should be "https://www.random.org/". This is due to it being the first link when you search random on google in the source code. I am using urllib3 and the re module because I do not really know how to use beautiful soup or lxml but if you can do this in beautiful soup and/or lxml that would also be fine. This is my code so far: import urllib.request import re def find(start,end): urls = [] with open('data.txt', 'r') as myFile: pass # Needs to append the every instance of all urls between the start and end inputs in data.txt # Returns all instances of urls between the start and end paramaters in data.txt return urls def parse(query): # Creates the url with the query url = 'https://www.google.com/search?q=' + query # Gets past googles attempt to block parsing headers = {} headers['User-Agent'] = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17" # Fetches data req = urllib.request.Request(url, headers = headers) resp = urllib.request.urlopen(req) respData = resp.read() # Saves the source code in a txt file saveFile = open('data.txt','w') saveFile.write(str(respData)) saveFile.close() # Finds the urls and returns them newUrl = find('&lt;h3 class="r"&gt;&lt;a href="','"') return newUrl print(parse("random")) PROBLEM: My problem is making the find() function work, I am not sure how to get the urls from the source code saved in data.txt and the variable respData, I want to do make this efficient so I was thinking of using regular expressions. However I am not sure how to get it to get the urls from the source code based on where the url starts (the class bit which is a parameter for the find function) and where it starts (the inverted com…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85357278
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85357431
has answer: http://stackoverflow.com/a/49176641
upvote count: 1

http://stackoverflow.com/q/49130343
has body: I have some data which I have fitted a normal distribution to using the scipy.stats.normal objects fit function like so: import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm import matplotlib.mlab as mlab x = np.random.normal(size=50000) fig, ax = plt.subplots() nbins = 75 mu, sigma = norm.fit(x) n, bins, patches = ax.hist(x,nbins,normed=1,facecolor = 'grey', alpha = 0.5, label='before'); y0 = mlab.normpdf(bins, mu, sigma) # Line of best fit ax.plot(bins,y0,'k--',linewidth = 2, label='fit before') ax.set_title('$\mu$={}, $\sigma$={}'.format(mu, sigma)) plt.show() I would now like to extract the uncertainty/error in the fitted mu and sigma values. How can I go about this?
favorite count: 0
upvote count: 11
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49133301
downvote count: 0
tagged with: gaussian
score: 11
tagged with: data-fitting
accepted answer: http://stackoverflow.com/a/49131723
tagged with: statistics
possible better answer: http://stackoverflow.com/a/49133301
has answer: http://stackoverflow.com/a/49131723
type: AnsweredQuestion
tagged with: curve-fitting
has title: Is there a way to get the error in fitting parameters from scipy.stats.norm.fit?
tagged with: python

http://stackoverflow.com/comment/85541558
comment on: http://stackoverflow.com/a/49268133
type: AnswerComment
has text: Can you also explain what the error is bcz `r'H:\7 - Script\teste.csv'` is equivalent to `'H:\\7 - Script\\teste.csv'`
score: 0
type: Comment

http://stackoverflow.com/comment/85437226
has text: The object to be stored is another list with 4 floats and 1 integer. I never used numpy so I am not sure if it can handle it better than a multidimensional list. It must be fast to retrieve any given minute.
type: Comment
comment on: http://stackoverflow.com/a/49216591
type: AnswerComment
score: 0

http://stackoverflow.com/q/49243269
type: Question
has title: Can't send ethernet packages across my LAN
has answer: http://stackoverflow.com/a/49250191
tagged with: python
tagged with: wireshark
has body: I am playing around with scapy (module for Python). I want to build packages and send them across my local network from one host to another. When I buil my package like that, I do not receive anything on my destination host: packet = Ether() / IP(dst='192.168.0.6') / TCP(dport=8000) => sendp(packet). However, when I build it like that it works: packet = IP(dst='192.168.0.6') / TCP(dport=8000), send(packet). I capture the packages on my destination host with the help of wireshark. Why doesn't the Ethernet-Variant work? I have all my PCs connected with ethernet cables... Thanks for help!
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49250191
has comment: http://stackoverflow.com/comment/85496331
tagged with: scapy
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/85299607
comment on: http://stackoverflow.com/a/49147491
has text: `which python` is also a good way to find the path to the python executable
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85356331
has text: yes, I did try it without var_list.
score: 0
comment on: http://stackoverflow.com/q/49172914
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85447733
has text: @izaak_pyzaak, you can use a strong cryptographic hash (like SHA-3) if you're worried about collisions.
type: AnswerComment
comment on: http://stackoverflow.com/a/49221989
score: 0
type: Comment

http://stackoverflow.com/comment/85329312
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49161623
score: 0
has text: Also, if this really is Python 3 as your question tag suggests, then the `u` prefixes to the string literals are redundant. They are only needed in Python 2 or code that needs to remain compatible with Python 2.

http://stackoverflow.com/comment/85514001
type: AnswerComment
comment on: http://stackoverflow.com/a/49255486
score: 0
has text: I just found out the error is in the g.parse I think, since if I were to put the "right" URI in there it works fine. Check my edit for the explanation :) Once that g.parse works correctly it should be able to recognize those prefixes right?
type: Comment

http://stackoverflow.com/comment/85477448
comment on: http://stackoverflow.com/q/49236770
score: 2
has text: Just create a super-simple UI with a large text field (output) on top and an entry (input) on the bottom and read/write from/to those instead of using `input` and `print`. Also, the `while` should probably be replaced with a call to `after` or similar.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49228769
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/85461009
answer count: 0
downvote count: 0
tagged with: pip
has comment: http://stackoverflow.com/comment/85461029
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/9510474
has body: I've been looking around for the equivalent of brew cleanup or npm prune for pip (the package manager for python users), but ain't able to find one. cleanup and prune have done me a huge favor of detecting and removing extraneous and outdated packages on Mac, and the closest I get so far for pip is pip list --outdated --not-required, which only indicates the outdated and no-longer-required packages. Does such function exist for pip? or has it already been built in some subcommands of pip? If not, can anyone point me to any third-party script that does this?
has title: Equivalent of brew cleanup in pip
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85449486
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49222986
has text: You should paste the output of 'pip freeze' in your question.
score: 0

http://stackoverflow.com/comment/85636322
comment on: http://stackoverflow.com/a/49254289
has text: refer to the docs on how to do implement other features, you can do this by adding `double_tap_time = 1` as part of the arguments
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85400889
score: 0
type: Comment
type: QuestionComment
has text: hi, I did. I realized the problem is with the formulation of LpVariable for a matrix
comment on: http://stackoverflow.com/q/49194399

http://stackoverflow.com/q/49153230
has answer: http://stackoverflow.com/a/49153775
accepted answer: http://stackoverflow.com/a/49153475
tagged with: python
has answer: http://stackoverflow.com/a/49153652
type: AnsweredQuestion
has title: Python - How to iterate through a dataframe and replace a value in one cell with a value from another in the same row
answer count: 3
tagged with: pandas
has body: I'm trying to create a new column in a dataframe of food ingredients with unique values per row based on information from other cells in the same row. The table essentially looks like this: ingredient_name | ingredient_method | consolidated_name Cheese | [camembert, pkg] | Cheese | [cream, pastueri] | Egg | [raw, scrambled] | I'm trying to iterate through the rows and fill the consolidated_name column with values from either ingredient_name or ingredient_method. For example, if ingredient_name is "Cheese" I want that row's consolidated name to be the first element of the list in ingredient_method. This is the code I have so far: for i, row in df.iterrows(): consolidated = df['ingredient_name'] if (df['ingredient_name'] == 'Cheese').all(): consolidated = df['ingredient_method'][0] df.set_value(i,'consolidated_name',consolidated) The code runs without errors but none of the values change in the dataframe. Any ideas?
score: 1
has answer: http://stackoverflow.com/a/49153475
downvote count: 0
has comment: http://stackoverflow.com/comment/85311359
upvote count: 1
possible better answer: http://stackoverflow.com/a/49153775
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85311320

http://stackoverflow.com/comment/85498142
has text: @Rahul: Yes, that's why I said "it is a builtin name", and explained why it's bad to reuse that name, giving the example `list(tup)`, so you don't need to explain to me exactly the same things I said. But "in a way is reserved" is just not true. "Reserved" has a meaning—it means the specific, small set of words that you cannot use as identifier names without getting a `SyntaxError` (or confusing the parser), and `list` is not one of them.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49227843

http://stackoverflow.com/a/49251675
answers question: http://stackoverflow.com/q/49250963
has body: Vectorization" (simplified) is the process of rewriting a loop so that instead of processing a single element of an array N times, it processes (say) 4 elements of the array simultaneously N/4 times. [What is “vectorization”?] Vectorized code is faster, because multiple operations are executed in parallel. In contrast, in the loop version, these operations are executed sequentially, one after another. Vectorized code uses more memory, because the data for all operations, which are executed in parallel, have to be loaded into memory. In contrast, for the loop version, only the data for one operation (which is currently executed) have to be loaded. It is a typical tradeoff in computer science known as Space–time tradeoff.
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49250963
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85424337
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49209595
type: QuestionComment
has text: Your code seems to be valid. Where did you test in your code that you didn't received the right string. Why don't you add a print statement `print(business.css('a.email-business::attr(href)').extract()[7:])` and see if that prints the right result. If this is the case: what does the Item class do. Please provide with more information and details (in your original question and not as a comment). Otherwise it is really hard to help you.

http://stackoverflow.com/a/49128483
downvote count: 0
has body: You must distinguish between a processing instruction and the xml declaration Both are written in the same way: <?SomeName SomeContent ?>. Find details in section 2.6! While the xml-declaration must be in the first place and starts with <?xml other processing instructions might appear (almost) anywhere in the XML. A processing instruction must have a name, while the content is not formally restricted like an element's content. It is free text... So this is well-formed XML: test <?piName some test?> I do not work with python, but this would return your PI in SQL-Server: DECLARE @xml XML= N' test <?link id="752760" resource-uuid="UUID-9f0575a3-1847-1cde-fd35-f18014fdecf3" resource-id="570935" resource-type="fork" type="ResourceLink"?> '; SELECT @xml.query('/root/processing-instruction("link")'); Even if your content looks like attributes: Within the PI the content is free text. So you have to parse your information out of the content... This answer might help you.
answers question: http://stackoverflow.com/q/49128161
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/91618897
comment on: http://stackoverflow.com/a/50529438
score: 0
has text: Would be great if we could do this. Would change things a lot
type: Comment
type: AnswerComment

http://stackoverflow.com/a/62235670
score: 0
has comment: http://stackoverflow.com/comment/110412505
upvote count: 1
answers question: http://stackoverflow.com/q/49127425
has body: This worked for me: turn off your firewall. I was using 360 Firewall. After I turned it off, everything was fine and dandy. hope this help
type: Answer
downvote count: 1
has comment: http://stackoverflow.com/comment/110375449

http://stackoverflow.com/q/49218404
tagged with: python-3.x
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85440712
has answer: http://stackoverflow.com/a/49218440
score: 0
has title: Find unique entries in files
tagged with: python
has body: guess you have a solution concerning the following issue: I want to compare two lists for common entries (on the basis of column 10) and write common entries to one file and unique entries for the first list into another file. The code I wrote is: INFILE1 = open ("c:\\python\\test\\58962.filtered.csv", "r") INFILE2 = open ("c:\\python\\test\\83887.filtered.csv", "r") OUTFILE1 = open ("c:\\python\\test\\58962_vs_83887.common.csv", "w") OUTFILE2 = open ("c:\\python\\test\\58962_vs_83887.unique.csv", "w") for line in INFILE1: line = line.rstrip().split(",") if line[11] in INFILE2: OUTFILE1.write(line) else: OUTFILE2.write(line) INFILE1.close() INFILE2.close() OUTFILE1.close() OUTFILE2.close() The following error appears: 8 OUTFILE1.write(line) 9 else: ---&gt; 10 OUTFILE2.write(line) 11 INFILE1.close() TypeError: write() argument must be str, not list Does somebody know about help for this? Best
type: Question

http://stackoverflow.com/comment/85362559
score: 0
has text: Side note: file permissions are usually written in octal (base 8). While it makes no difference for `000`, in general mode value in a program must be written like `0o644` or `0o22`.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49175172

http://stackoverflow.com/q/49162218
score: 5
upvote count: 5
has title: cdef extern from ... NOGIL
tagged with: python
type: AnsweredQuestion
downvote count: 0
answer count: 1
tagged with: cython
favorite count: 0
has body: There's one thing I don't fully understand about the "nogil" applied to a cdef extern like this: cdef extern from "pthread.h" nogil: ctypedef struct pthread_mutex_t: pass cdef int pthread_mutex_init(pthread_mutex_t *, void *) cdef int pthread_mutex_destroy(pthread_mutex_t *) It isn't clear to me about the effect of that nogil, and I cannot find anything in the Cython's documentation about it. My interpetation is that the functions declared inside have the nogil implicitly. Am I right? And what about the struct? Thanks for any info.
has answer: http://stackoverflow.com/a/49171009
type: Question
accepted answer: http://stackoverflow.com/a/49171009

http://stackoverflow.com/comment/85480669
type: Comment
type: AnswerComment
has text: Yes I could do that, or calculate the node size based on the approximate area and the radius I want. But for what I want to do (mouse hovering, etc), I'm simply going to use matplotlib. A shame, because connecting nodes is easy with networkx.
comment on: http://stackoverflow.com/a/49238340
score: 0

http://stackoverflow.com/comment/85349877
comment on: http://stackoverflow.com/q/49172471
type: QuestionComment
has text: 1. you haven't print it, 2, use Euler's method, 3. print it
score: 0
type: Comment

http://stackoverflow.com/comment/85253951
score: 0
comment on: http://stackoverflow.com/q/49124214
type: Comment
type: QuestionComment
has text: Thanks @DyZ for pointing this out but in my past experiences whenever I have worked with huge lists or dictionaries my system kind of slows down, can you tell me what might be the reason behind this so that I can optimize my code accordingly.

http://stackoverflow.com/comment/85305151
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49150025
has text: Do you need `df['Conn_ses'].resample('30Min').first()` ?

http://stackoverflow.com/q/49141671
tagged with: list-comprehension
accepted answer: http://stackoverflow.com/a/49141765
type: Question
has answer: http://stackoverflow.com/a/49141765
answer count: 2
has title: How to create lists from a list each like the original but with one item missing
has comment: http://stackoverflow.com/comment/85289493
score: -4
has comment: http://stackoverflow.com/comment/85288925
downvote count: 5
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/49142008
favorite count: 0
has comment: http://stackoverflow.com/comment/85288941
has answer: http://stackoverflow.com/a/49142008
has body: I have 5 files in a list. I need to create lists where each file is left out once. Example: drive = [File_1, File_2, File_3 , File_4, File_5] new_list_1 = [File_1, File_2, File_3, File_4] # leaving out File_5 new_list_2 = [File_1, File_2, File_3, File_5] # leaving out File_4 new_list_3 = [File_1, File_2, File_4, File_5] # leaving File_3 And so on. Thank you!
type: AnsweredQuestion

http://stackoverflow.com/comment/85413835
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49204178
has text: Thanks Daniel. I tried that and got 'ValueError: None values not supported.' when I tried to train
score: 0

http://stackoverflow.com/a/65218194
answers question: http://stackoverflow.com/q/49234989
type: Answer
downvote count: 0
upvote count: 1
score: 1
has body: Good reading on the problem is the constructor of firefox_profile.FirefoxProfile() code. It directly states that def __init__(self, profile_directory=None): """ Initialises a new instance of a Firefox Profile :args: - profile_directory: Directory of profile that you want to use. If a directory is passed in it will be cloned and the cloned directory will be used by the driver when instantiated. This defaults to None and will create a new directory when object is created. """ in OOP you can subclass it, if you want. like this: import copy import json import os from selenium import webdriver from selenium.webdriver.firefox import firefox_profile class MyVeryFirefoxProfile(firefox_profile.FirefoxProfile): def __init__(self, profile_directory=None): """ Initialises a new instance of a Firefox Profile :args: - profile_directory: Directory of profile that you want to use. If a directory is passed it will be used as is, with no cloning attempts. Otherwise it will be handled as usual (new empty profile dir on user's temp) """ if (profile_directory == None): # just pass it to super super().__init__(profile_directory) return if not firefox_profile.FirefoxProfile.DEFAULT_PREFERENCES: with open(os.path.join(os.path.dirname(firefox_profile.__file__), firefox_profile.WEBDRIVER_PREFERENCES)) as default_prefs: firefox_profile.FirefoxProfile.DEFAULT_PREFERENCES = json.load(default_prefs) self.default_preferences = copy.deepcopy( firefox_profile.FirefoxProfile.DEFAULT_PREFERENCES['mutable']) self.profile_dir = profile_directory self.tempfolder = None # if smart enough, it will understand :-) #=================================================================== # newprof = os.path.join(self.tempfolder, "webdriver-py-profilecopy") # shutil.copytree(self.profile_dir, newprof, # ignore=shutil.ignore_patterns("parent.lock", "lock", ".parentlock")) # self.profile_dir = newprof # os.chmod(self.profile_dir, 0o755) #=================================================================== self._read_…

http://stackoverflow.com/comment/85490840
type: Comment
has text: There may be room to vectorize your function instead of looping. I do not see any issue with original line. If code works and in your specified time, this question may be better put on [Code Review](https://codereview.stackexchange.com/).
type: QuestionComment
comment on: http://stackoverflow.com/q/49239248
score: 0

http://stackoverflow.com/comment/122776431
score: 0
comment on: http://stackoverflow.com/a/69458121
type: Comment
has text: Please include an explanation
type: AnswerComment

http://stackoverflow.com/comment/101096487
type: Comment
score: 0
type: AnswerComment
has text: The answer means that you should specify the path of the parent folder of some virtual env.
comment on: http://stackoverflow.com/a/49126446

http://stackoverflow.com/a/49219564
has body: You should map each of the distinct values of the string columns to a numerical label. Then, create columns for these labels and assign 0/1 depending on the prescence of the corresponding string value for that row. This is called One Hot Encoding. You should checkout Scikit-learn's CategoricalEncoding class. It does most of the work for you.
type: Answer
answers question: http://stackoverflow.com/q/49218954
score: 0

http://stackoverflow.com/comment/85548833
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49272908
type: AnswerComment
has text: @deceze After some testing I stand corrected, global keyword is not needed for mutation.

http://stackoverflow.com/comment/85287139
type: AnswerComment
has text: Yeah, that's exactly why
comment on: http://stackoverflow.com/a/49140812
type: Comment
score: 0

http://stackoverflow.com/a/49142543
downvote count: 1
has body: you can use importlib import importlib and then modB = importlib.import_module('package.modB') ... granted it's not optimal but still a working option if you're having persistent issues with relative path imports (never run into issues on POSIX and OSx, but on NT platform I have)
answers question: http://stackoverflow.com/q/49142463
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/comment/85629442
has text: `list(set(all_) - set(song)` is inside an udf so it works on one user at a time.It won't be a problem i guess. But since this code will involve high shuffling due to heavy operations such as join and groupby, i think it can become little slow.
type: AnswerComment
comment on: http://stackoverflow.com/a/49277642
score: 0
type: Comment

http://stackoverflow.com/q/49142439
answer count: 1
has title: reading any pc compatible racing wheel input
downvote count: 3
score: -1
has answer: http://stackoverflow.com/a/49143563
favorite count: 0
tagged with: c++
type: Question
has body: I am an Electrical Engineer student and I am currently doing a Final Year Project on setting up a simulation platform for driving to test my drowsiness detecting device. I am currently looking for methods that can retrieve racing wheel's input data such as steering wheel angle because I need those data to operate my device effectively. I have tried to look up on the internet and I only found these documents: https://learn.microsoft.com/en-us/uwp/api/windows.gaming.input.racingwheelreading https://learn.microsoft.com/en-us/windows/uwp/gaming/racing-wheel-and-force-feedback It seems like windows only support device that is compatible with xbox one or xbox 360 steering wheel. Due to our limiting allowed budget, we could only find some cheap steering wheels that are compatible with PS4/PS3 and PC. Is there any other way that can read input data like steering angle from any pc compatible racing wheel? By the way, I am using windows operating system. I would really appreciate any help.
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85290497
tagged with: python
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/85290907
tagged with: windows

http://stackoverflow.com/a/49134627
upvote count: 4
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49134404
has comment: http://stackoverflow.com/comment/85280557
type: Answer
has body: Cycle, zip, and unpack: mylist = [1,2,3,4,5,6,7,8,9,10] for value, iden in zip(mylist, itertools.cycle('A', 'B', 'C')): print(value, iden) Output: 1 A 2 B 3 C 4 A 5 B 6 C 7 A 8 B 9 C 10 A
score: 4
answers question: http://stackoverflow.com/q/49134404

http://stackoverflow.com/comment/85401657
score: 2
has text: Uh, too much text. Please provide a [mcve] with some small data samples in your question instead. Thanks.
type: QuestionComment
comment on: http://stackoverflow.com/q/49198342
type: Comment

http://stackoverflow.com/a/49130974
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49130850
has comment: http://stackoverflow.com/comment/85266989
score: 2
upvote count: 2
has body: After you have fit the model, you can either call the coef and intercept_ attributes to see what the coefficients and the intercept are respectively. But this would involve writing a constructed formula for your model. My recommendation is once you build your model, make the predictions and score it against the true y values - from sklearn.metrics import mean_squared_error mean_squared_error(y_test, y_pred) # y_test are true values, y_pred are the predictions that you get by calling regression.predict() If the goal is to calculate distances, you sklearn.metrics convenience functions instead of looking for the equation and hand-computing it yourself. The manual way to do that will be - import numpy as np y_pred = np.concatenate(np.ones(X_test.shape[0]), X_test) * np.insert(clf.coef_,0,clf.intercept_) sq_err = np.square(y_pred - y_test) mean_sq_err = np.mean(sq_err)

http://stackoverflow.com/q/49250269
answer count: 1
has body: An example of this would be the word "walk" which would produce a candidate set of ['awlk', 'wlak', 'wakl']. This is what I have currently: def main(): word = "jack" wordL = len(word) listS = [] for i in range((wordL)-1): current = word[i+1] word[i+1] = word[i] word[i] = current listS.append(word) print (listS) main() I am using the word "jack" as a test which should produce a set of candidate words. However, this doesn't seem to be working. I am new to python and would appreciate any help I can get.
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49250533
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49250533
type: AnsweredQuestion
score: 0
has title: I was tasked with creating a function that swaps adjacent letters of a word and returns the list of the candidate words.
tagged with: string

http://stackoverflow.com/a/49160375
score: 1
has comment: http://stackoverflow.com/comment/85326460
type: AcceptedAnswer
has body: The way you are running the test script testris.py (you are not disclosing that in your question so I'm not sure if the instructions are incomplete or if you aren't following them exactly) requires you to do chmod +x ./learntris.py before the test will actually successfully run your program at all. You just need to do this once, the execute permission will then stay there as long as you don't remove the file from the disk, even if you edit it or otherwise modify it.
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49159808
answers question: http://stackoverflow.com/q/49159808

http://stackoverflow.com/comment/85313344
comment on: http://stackoverflow.com/q/49154240
type: Comment
type: QuestionComment
has text: *my regex is also outputting the year* – no it is not. If the regex matches, you (not the regex!) write out the original text. Nothing changes, nothing gets added.
score: 1

http://stackoverflow.com/q/49151010
upvote count: 3
answer count: 2
has title: Check pandas dataframe column for string type
downvote count: 0
linked to: http://stackoverflow.com/q/39275533
tagged with: pandas
has answer: http://stackoverflow.com/a/49151321
tagged with: string
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85306798
score: 3
has comment: http://stackoverflow.com/comment/85306411
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/63898732
has comment: http://stackoverflow.com/comment/85306850
tagged with: python
has body: I have a fairly large pandas dataframe (11k rows and 20 columns). One column has a mixed data type, mostly numeric (float) with a handful of strings scattered throughout. I subset this dataframe by querying other columns before performing some statistical analysis using the data in the mixed column (but can't do this if there's a string present). 99% of the time once subsetted this column is purely numeric, but rarely a string value will end up in the subset, which I need to trap. What's the most efficient/pythonic way of looping through a Pandas mixed type column to check for strings (or conversely check whether the whole column is full of numeric values or not)? If there is even a single string present in the column I want to raise an error, otherwise proceed.

http://stackoverflow.com/a/56993864
has comment: http://stackoverflow.com/comment/112465521
score: 6
upvote count: 6
type: Answer
has body: I wrote about how to do this in keras. It's basically a functional multiple input model, which concatenates both feature vectors like this: nlp_input = Input(shape=(seq_length,), name='nlp_input') meta_input = Input(shape=(10,), name='meta_input') emb = Embedding(output_dim=embedding_size, input_dim=100, input_length=seq_length)(nlp_input) nlp_out = Bidirectional(LSTM(128))(emb) x = concatenate([nlp_out, meta_input]) x = Dense(classifier_neurons, activation='relu')(x) x = Dense(1, activation='sigmoid')(x) model = Model(inputs=[nlp_input , meta_input], outputs=[x])
answers question: http://stackoverflow.com/q/49175961
has comment: http://stackoverflow.com/comment/101622810
downvote count: 0
has comment: http://stackoverflow.com/comment/112408921

http://stackoverflow.com/q/49264652
linked to: http://stackoverflow.com/q/45983767
has body: I am attempting to use the Google Cloud Datastore, but importing google.cloud.datastore gives an ImportError: ERROR 2018-03-13 19:28:29,013 wsgi.py:263] Traceback (most recent call last): File "/home/&lt;user&gt;/Software/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/&lt;user&gt;/Software/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler handler, path, err = LoadObject(self._handler) File "/home/&lt;user&gt;/Software/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 85, in LoadObject obj = __import__(path[0]) File "/home/&lt;user&gt;/Projects/&lt;my_project&gt;/main.py", line 1, in &lt;module&gt; from my_project import app File "/home/&lt;user&gt;/Projects/&lt;my_project&gt;/&lt;my_project&gt;/__init__.py", line 2, in &lt;module&gt; from my_project.submit.controllers import submit File "/home/&lt;user&gt;/Projects/&lt;my_project&gt;/&lt;my_project&gt;/submit/controllers.py", line 6, in &lt;module&gt; from . import model_datastore File "/home/&lt;user&gt;/Projects/&lt;my_project&gt;/&lt;my_project&gt;/submit/model_datastore.py", line 2, in &lt;module&gt; from google.cloud import datastore File "/home/&lt;user&gt;/Projects/&lt;my_project&gt;/env/local/lib/python2.7/site-packages/google/cloud/datastore/__init__.py", line 57, in &lt;module&gt; from pkg_resources import get_distribution ImportError: No module named pkg_resources I am on Linux Mint attempting to run a Google App Engine local dev server. I am using a virtual environment. Both setuptools and pkg_resources are installed and updated in the virtual environment. When I enter the python cmd line interpreter from the virtual env and import pkg_resources, it works fine. When I run the google app engine dev server by doing dev_appserver app.yaml, everything works fine until I access the page that activ…
has title: "ImportError: No module named pkg_resources" when importing google.cloud.datastore
upvote count: 2
tagged with: google-cloud-datastore
answer count: 1
downvote count: 0
tagged with: pkg-resources
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: importerror
tagged with: google-app-engine
accepted answer: http://stackoverflow.com/a/49266990
tagged with: python
has answer: http://stackoverflow.com/a/49266990
score: 2

http://stackoverflow.com/comment/94876353
comment on: http://stackoverflow.com/q/49140450
type: Comment
type: QuestionComment
score: 0
has text: @Miguel switching to one thread worked for me

http://stackoverflow.com/q/49163125
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: curve-fitting
tagged with: python
has body: I am trying to create a curve fit for the data in "time" and "volts" np arrays. When I try and fit the data I get the error "covariance of parameters could not be estimated". If I put in other data points though it works. I am not sure what could be going wrong here. import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt import pandas as pd from pandas import Series, DataFrame time = np.array([100,80,70,60,55,50,45,40,35,30,25,22,20]) volts = np.array([6.28,6.04,5.72,5.32,5.08,4.80,4.44,3.96,3.40, 2.80,2.01,1.40,1.01]) ## Defining exp func for curve fit def func(x, a ,b): return a * (1 - 2*np.exp(-b * x)) params, extras = curve_fit(func, time, volts) print(params) plt.scatter(time, volts) x_data = np.arange(5,110) plt.plot(x_data, params[0]*(1-2*np.exp(-params[1]*x_data))) plt.show() enter image description here enter image description here For example if I use the data: volts = np.array([2.56, 2.54, 2.52, 2.46, 2.4, 2.38, 2.30, 2.26, 2.18, 2.08, 1.95, 1.80, 1.68, 1.44, 1.22, .9, .46]) time = np.array([]) for i in range(100, 15, -5): time = np.append(time, i) Then the fit works great.
score: 2
answer count: 1
tagged with: scipy
favorite count: 0
type: Question
tagged with: numpy
has title: Scipy covariance of parameters could not be estimated. Working for similar data why not this data.
has answer: http://stackoverflow.com/a/49163685

http://stackoverflow.com/a/49296707
type: AcceptedAnswer
upvote count: 17
answers question: http://stackoverflow.com/q/49227183
has comment: http://stackoverflow.com/comment/85622239
has comment: http://stackoverflow.com/comment/85598025
has comment: http://stackoverflow.com/comment/110654968
type: Answer
has comment: http://stackoverflow.com/comment/85621791
score: 17
has comment: http://stackoverflow.com/comment/125991432
has body: You must pass an instance of django's File object to FileField.save() to change the content of a file field. It works a bit differently from other types of model fields. FieldFile.save(name, content, save=True) This method takes a filename and file contents and passes them to the storage class for the field, then associates the stored file with the model field. If you want to manually associate file data with FileField instances on your model, the save() method is used to persist that file data. from PIL import Image from django.core.files.base import ContentFile if instance.image: im = Image.open(instance.image) im.thumbnail((220, 130), Image.ANTIALIAS) thumb_io = BytesIO() im.save(thumb_io, im.format, quality=60) instance.image.save(im.filename, ContentFile(thumb_io.getvalue()), save=False) instance.save() But if you are not using a remote file storage backend, you could just overwrite the file itself. The file was created when you called form.save(). Since you are using the same filename and location, you don't really have to touch the model or tell django that you are messing with the file itself. if instance.image: im = Image.open(instance.image) im.thumbnail((220, 130), Image.ANTIALIAS) im.save(im.filename, quality=60)
accepted answer of: http://stackoverflow.com/q/49227183
downvote count: 0
has comment: http://stackoverflow.com/comment/85601635

http://stackoverflow.com/q/49210484
favorite count: 0
has title: List to Dictionary conversion in Python
has answer: http://stackoverflow.com/a/49210566
type: Question
has comment: http://stackoverflow.com/comment/85425459
tagged with: python
tagged with: dictionary
has body: I have a list which is holding names as below d=[['Srini'], ['Rahul'], ['Mano'], ['Rahul'], ['Srini'], ['Mano], ['Srini'], ['Rahul']] I am using the below code to convert the list to dictionary which should hold names as Keys and the count of names as value. dic={} for words in d: dic[words]= dic.get(words,0)+1 print(dic) ERROR: TypeError Traceback (most recent call last) in () 1 dic={} 2 for words in d: ----> 3 dic[words]= dic.get(words,0)+1 4 print(dic) TypeError: unhashable type: 'list'
score: 2
tagged with: list
answer count: 2
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49210544

http://stackoverflow.com/a/49184946
type: AcceptedAnswer
score: 4
answers question: http://stackoverflow.com/q/49184885
has comment: http://stackoverflow.com/comment/85375849
downvote count: 0
has comment: http://stackoverflow.com/comment/85375958
has body: You can use itertools.groupby to create a dictionary where each key is a year, storing a dictionary with the Total Housing Units and Vacant Housing Units: import itertools import csv with open('filename.csv') as f: data = [[int(a), b, int(c)] for a, b, c in sorted(list(csv.reader(f))[1:], key=lambda x:int(x[0]))] final_data = {a:dict(i[1:] for i in b) for a, b in itertools.groupby(data, key=lambda x:x[0])} Output: {2008: {'Total Housing Units': 41194, 'Vacant Housing Units': 4483, 'Occupied Housing Units': 36711}, 2009: {'Total Housing Units': 39499, 'Vacant Housing Units': 3583, 'Occupied Housing Units': 35916}, 2010: {'Total Housing Units': 44642, 'Vacant Housing Units': 3635, 'Occupied Housing Units': 41007}, 2011: {'Total Housing Units': 44917, 'Vacant Housing Units': 4213, 'Occupied Housing Units': 40704}, 2012: {'Total Housing Units': 45121, 'Vacant Housing Units': 3013, 'Occupied Housing Units': 42108}, 2013: {'Total Housing Units': 47888, 'Vacant Housing Units': 4215, 'Occupied Housing Units': 43673}, 2014: {'Total Housing Units': 49109, 'Vacant Housing Units': 2814, 'Occupied Housing Units': 46295}}
type: Answer
has comment: http://stackoverflow.com/comment/85375964
has comment: http://stackoverflow.com/comment/85375934
upvote count: 4
has comment: http://stackoverflow.com/comment/85375815
has comment: http://stackoverflow.com/comment/85375951
has comment: http://stackoverflow.com/comment/85376000
accepted answer of: http://stackoverflow.com/q/49184885

http://stackoverflow.com/comment/85482090
score: 0
has text: thanks! is this a new feature or did I just miss it?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49239220

http://stackoverflow.com/q/49275822
downvote count: 1
has answer: http://stackoverflow.com/a/49278217
favorite count: 0
type: Question
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/49275960
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/49275972
has body: I'm trying to create an HTML file, which certains Python variables that have to be evaluated. My code looks like this: name = ['Nora', 'John', 'Jack', 'Jessica'] html = """ Names Mother: <%= name[0] %> Father: <%= name[1] %> Son: <%= name[2] %> Daughter: <%= name[3] %> """ Html_file = open("names.html","w") Html_file.write(html) Html_file.close() However, the array is not interpreted during output. My HTML source looks like this: ... Mother: <%= name[0] %> Father: <%= name[1] %> Son: <%= name[2] %> Daughter: <%= name[3] %> ... How can I evaluate the python code that's surrounded by <%= %>?
has answer: http://stackoverflow.com/a/49275960
linked to: http://stackoverflow.com/q/43123408
has title: How can Python code within html string be evaluated?
answer count: 4
has comment: http://stackoverflow.com/comment/85554401
accepted answer: http://stackoverflow.com/a/49276325
upvote count: 2
tagged with: string-formatting
has answer: http://stackoverflow.com/a/49276325

http://stackoverflow.com/q/49208326
has comment: http://stackoverflow.com/comment/85423011
tagged with: tensorflow
type: Question
has body: I'm new in this world of deep Learning. These days I'm triying to understand well how a neural network works so I'm doing different test. By now I'm using the MNIST database with the numbers from 0 to 9. I've apply a fully connected network with no hidden layers. Here is the code: from keras.datasets import mnist # subroutines for fetching the MNIST dataset import tensorflow as tf import matplotlib.pyplot as plt import numpy as np from keras.utils import np_utils # utilities for one-hot encoding of ground truth values from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) x_train = mnist.train.images y_train = mnist.train.labels x_test = mnist.test.images y_test = mnist.test.labels test = np.reshape(x_train,[-1,28,28]) #THRESHOLDING x_train = np.zeros([55000,28,28]) x_train[test &gt; 0.5] = 1 print(x_train.shape) x_train = np.reshape(x_train,[55000,784]) y_train = np_utils.to_categorical(y_train, 10) # One-hot encode the labels print(x_train.shape) print(y_train.shape) x_test = np.reshape(x_test,[10000,784]) input = tf.placeholder(tf.float32, name='Input') output = tf.placeholder(tf.float32, name = 'Output') syn0 = tf.Variable(2*tf.random_uniform([784,10],seed=1)-1, name= 'syn0') #syn0 = tf.Variable(tf.zeros([784,10], dtype = tf.float32), name= 'syn0') b1 = tf.Variable(2*tf.random_uniform([10],seed=1)-1, name= 'b1') #b1 = tf.Variable(tf.zeros([10],dtype = tf.float32), name= 'syn0') init = tf.global_variables_initializer() #model l1 = tf.nn.softmax((tf.matmul(input,syn0) + b1),name='layer1') error = tf.square(tf.subtract(l1,output),name='error') loss = tf.reduce_sum(error, name='cost') #optimizer with tf.name_scope('trainning'): optimizer = tf.train.GradientDescentOptimizer(0.01) train = optimizer.minimize(loss) #session sess = tf.Session() sess.run(init) syn0_ini = sess.run(syn0) #trainning for i in range (10000): batch_xs, batch_ys = mnist.train.next_batch(128) _,lossNow = sess.run([train,loss],{inp…
has title: Gradient Descent optimizer TensorFlow
tagged with: neural-network
tagged with: python
has comment: http://stackoverflow.com/comment/85422775
type: AnsweredQuestion
score: 0
tagged with: deep-learning
tagged with: mnist
answer count: 1
has answer: http://stackoverflow.com/a/49251575
accepted answer: http://stackoverflow.com/a/49251575

http://stackoverflow.com/q/49245027
tagged with: oauth
has comment: http://stackoverflow.com/comment/85494337
has body: So im writing a bot for a subreddit I moderate in python. The Bot is able to execute, and is able to reply to the comment correctly, except that it only replies with the final part of the list .(the comments are for the other people who use the sub). The code is not finished, i have only done it for one region so far, but everything seems to work except that one part. Please could you advise me on what i should do. Example: comment : u/crazy_angel1: automaester raven north reply: u/AutoMaesterGOT: u/CptAwsome12345 Code: import time #importing time module import praw #importing the thing that allows you to run all the code, if you want to run this on your own computer, you will need to install it, look for a tutorial on how to install PRAW online reddit = praw.Reddit(client_id='redacted', username='AutoMaesterGOT', client_secret='redacted', password='redacted', user_agent='It is a script that messages people every time a certain phrase is passed in my subreddit. Created by /u/crazy_angel1') print("logging in...") print(reddit.user.me()) #singing on to the bot with OAuth, again look up online if you want to use it WordCalls=['AUTOMAESTER RAVEN NORTH', 'AUTOMAESTER RAVEN CROWNLANDS', 'AUTOMAESTER RAVEN CROWNLANDS','AUTOMAESTER RAVEN WESTERLANDS', 'AUTOMAESTER RAVEN DORNE','AUTOMAESTER RAVEN VALE','AUTOMAESTER REACH', 'AUTOMAESTER RAVEN IRON ISLANDS'] #the terms that will call the bot CommentCache=[] #storing comments already sorted through NorthMembers=['u/crazy_angel1','u/StraightOuttaNYC','u/jgames2000','u/CptAwsome12345'] def BOTRUN(): #the bots main code for North subreddit = reddit.subreddit('StormOfSwordsRP')#connecting to the subreddit comments = subreddit.stream.comments()#sorting through comments for comment in comments: comment_body = comment.body#storing each individual comment comment_body = comment_body.upper()#making every comment uppercase isMatch = any(string in comment_body for string in WordCalls)#setting conditions for calling bot if isMatch and comm…
has comment: http://stackoverflow.com/comment/85504738
tagged with: python
accepted answer: http://stackoverflow.com/a/49251171
has answer: http://stackoverflow.com/a/49251171
type: AnsweredQuestion
score: 0
tagged with: reddit
has comment: http://stackoverflow.com/comment/85504292
answer count: 1
tagged with: praw
has title: Writing Reddit Automatic Bot code, Not commenting all parts of a list
has comment: http://stackoverflow.com/comment/85495219
type: Question
has comment: http://stackoverflow.com/comment/85524476
tagged with: python-3.x

http://stackoverflow.com/comment/85251406
score: 0
comment on: http://stackoverflow.com/q/49122916
has text: In that same terminal window are you running the django server to trigger the original error?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49248824
has comment: http://stackoverflow.com/comment/85501161
has answer: http://stackoverflow.com/a/49259261
type: AnsweredQuestion
score: 0
answer count: 2
has title: how to set equal intervals along boundaries of irregular shaped object in image in python?
has body: I'm trying to set equal intervals along the boundary of a black and white image. Is there a way to do it? I thought about first finding the edge of object using distance transform then scanning the image for the edge. I was thinking of starting with first pixel that is on the edge then find the pixel closest to it, eventually we'll get the list of edge pixels in order. But the runtime of that seems really slow. Can someone help me with this?
accepted answer: http://stackoverflow.com/a/49248905
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/49248905
tagged with: background-subtraction
possible better answer: http://stackoverflow.com/a/49259261
tagged with: python

http://stackoverflow.com/comment/85551016
score: 0
has text: It raised a `KeyError`, meaning it tried to request `'32'` from a dictionary, but the key was not found. So probably `file_obj.icons['32']` didn't exist. You could try posting some code where you are trying to access it. It might be an issue with the package itself.
comment on: http://stackoverflow.com/q/49274169
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85413194
type: Comment
has text: abs() does not return a float if an integer is input, it returns an integer. He is wondering why then when he inputs integer values in a complex variable that it returns a real. Well, there is no 'integer' complex type. (Would not be very useful would it.) Even though he typed integer coefficients, complex numbers are stored as two reals hence abs() of a complex number (with integer looking coefficients) always returns a real.
type: AnswerComment
comment on: http://stackoverflow.com/a/49200854
score: 0

http://stackoverflow.com/q/49225343
has answer: http://stackoverflow.com/a/49225415
tagged with: operator-keyword
has comment: http://stackoverflow.com/comment/85476978
has body: I am tring to do an extending function, one that will work as list.extend method, but i don't want it to contain list.extend method or the '+' operator, and in addition I need to extend 'x' and not to 'y' (you will see). first of all, this is x and y: x = [4, 5, 6] y = [1, 2, 3] I tried this: x = y, x But it is giving me this result: ([1, 2, 3], [4, 5, 6]), and I ran out of ideas... The thing that I want to do (without extend method and '+' operator) will look like this: x = [4, 5, 6] y = [1, 2, 3] extending_func(x, y) [1, 2, 3, 4, 5, 6] I want to do a function like "extending_func" but I dont succes to bring it all to one list, and i dont know if i need to chage the type of list to somthing else to do it, or that I need just a simple idea to solve it. I tried also to use list.append, but it is giving me the next result (just to try the idea, but as i wrote i need to extend x and not y): x = [4, 5, 6] y = [1, 2, 3] y.append(x) [1, 2, 3, [4, 5, 6]]
downvote count: 0
tagged with: methods
favorite count: 0
has answer: http://stackoverflow.com/a/49225400
type: Question
accepted answer: http://stackoverflow.com/a/49225415
has title: How to extend lists without list.extend method and without '+' operator
has comment: http://stackoverflow.com/comment/85454476
upvote count: 2
tagged with: function
tagged with: python
possible better answer: http://stackoverflow.com/a/49225400
has comment: http://stackoverflow.com/comment/85454503
tagged with: extend
has comment: http://stackoverflow.com/comment/85454413
has comment: http://stackoverflow.com/comment/85454489
type: AnsweredQuestion
score: 2
answer count: 2

http://stackoverflow.com/q/49144632
tagged with: python
tagged with: valueerror
favorite count: 0
has body: I am new to programming. I have to write a script for a calculator. I have two issues with it: My 3rd prompt to enter a number repeats itself, and I am not sure why. I get a ValueError instead of the calculation but I can't figure out what I am doing wrong. This is my code: def input_number1(): prompt = 'Enter a number\n' num1 = int(input(prompt)) if num1 &lt;= 0: print('Error') input_number1() else: return num1 input_number1() def input_operator(): prompt = 'Enter [1] to add, [2] to substract, [3] to multiply or [4] to divide?\n' operator = int(input(prompt)) if operator &lt; 1 or operator &gt; 4 : print('error') input_operator() else: return operator input_operator() def input_number2(): prompt = 'Enter a number\n' num2 = int(input(prompt)) if num2 &lt;= 0 : print('Error') input_number2() else: return num2 input_number2() num1 = input_number1() operator = input_operator() num2 = input_number2() def do_calc(): if operator == 1: print(num1 + num2) elif operator == 2: print(num1 - num2) elif operator == 3: print(num1 * num2) else: print(num1 / num2) do_calc() Can someone points me in the right direction please?
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49144690
answer count: 1
type: Question
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/49144690
has title: ValueError + repetition I can't figure out

http://stackoverflow.com/q/49145315
upvote count: 0
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49145462
tagged with: multidimensional-array
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85295624
tagged with: python
score: -1
has title: how to count the occurance of multidimentional arrays of string?
has body: [['Canal St &amp; Taylor St', 'Canal St &amp; Monroe St (*)'], ['Larrabee St &amp; Menomonee St', 'Sheffield Ave &amp; Kingsbury St'], ['Orleans St &amp; Chestnut St (NEXT Apts)', 'Ashland Ave &amp; Blackhawk St'], ['Franklin St &amp; Monroe St', 'Clinton St &amp; Tilden St'], ['Broadway &amp; Barry Ave', 'Sedgwick St &amp; North Ave'], ['State St &amp; Kinzie St', 'Wells St &amp; Polk St'], ['Wabash Ave &amp; Wacker Pl', 'Clinton St &amp; Tilden St'], ['Daley Center Plaza', 'Canal St &amp; Monroe St (*)'], ['Daley Center Plaza', 'Canal St &amp; Monroe St (*)'], ['Dayton St &amp; North Ave', 'Ogden Ave &amp; Chicago Ave'], ['Wilton Ave &amp; Diversey Pkwy', 'Halsted St &amp; Wrightwood Ave'], ['Canal St &amp; Madison St', 'LaSalle St &amp; Illinois St'], ['Theater on the Lake', 'Lakeview Ave &amp; Fullerton Pkwy'], ['Halsted St &amp; Maxwell St', 'Halsted St &amp; 18th St'], ['Ravenswood Ave &amp; Lawrence Ave', 'Clarendon Ave &amp; Gordon Ter']] This is my list of list. How do i count the occurance of ['Canal St &amp; Taylor St', 'Canal St &amp; Monroe St (*)'] the output should be ['Canal St &amp; Taylor St', 'Canal St &amp; Monroe St (*)'] : 1 ['Larrabee St &amp; Menomonee St', 'Sheffield Ave &amp; Kingsbury St'] : 2 etc
has answer: http://stackoverflow.com/a/49145472
tagged with: list
has answer: http://stackoverflow.com/a/49145713
answer count: 3

http://stackoverflow.com/q/49224029
has body: I am quite comfortable with python, but have recently gotten into trying some musical analysis. I have come across music21, and I would like to know how to extract the basic note data (pitch and duration) of every note in a musical .mxl file. I have gone through the documentation, but have struggled to digest it all and find something that does what I need. Due to my limited experience with .mxl files and music21 I cannot provide any real example of what I have tried so far. However, what I have gathered is that one can get a plot of the music by using s = converter.parse('exampleFile.mxl') test=s.measures(1, 10) test.plot('horizontalbar') which, for the particular piece that i used, looks like mxl example image This clearly shows that in the first measure, the notes C4, Eb and G are played where the length of the bars represent the note duration. Ultimately I would like a this data in a list format. By doing, test=s.measures(1, 5) test.show('text') I can get a list of the notes played, with their beats in position in measure, but it comes in what is printed is something like {0.0} &lt;music21.key.Key of E- major&gt; {0.0} &lt;music21.meter.TimeSignature 4/4&gt; {0.0} &lt;music21.note.Note C&gt; {0.5} &lt;music21.note.Note E-&gt; {1.0} &lt;music21.note.Note G&gt; {1.5} &lt;music21.note.Note E-&gt; {2.0} &lt;music21.note.Note C&gt; {2.5} &lt;music21.note.Note E-&gt; {3.0} &lt;music21.note.Note G&gt; {3.5} &lt;music21.note.Note E-&gt; But this still requires massaging to: 1) get the same information that the graph displays and 2), to get it into a list format that I would like. Any help with this would be really appreciated. In the meanwhile I will continue to read the documentation. Thanks in advance!
downvote count: 0
has comment: http://stackoverflow.com/comment/85451972
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/74229087
upvote count: 2
type: UnansweredQuestion
answer count: 1
tagged with: python
tagged with: list
score: 2
has title: Extracting note data from a .mxl file using music21
tagged with: music21

http://stackoverflow.com/comment/85539130
comment on: http://stackoverflow.com/a/49267799
has text: And at the service side is the syntax correct to fetch the username: user_name = request.authorization.username
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49171240
score: 0
accepted answer: http://stackoverflow.com/a/49173106
has comment: http://stackoverflow.com/comment/85348336
has body: # insertions with SQL # importing module import sqlite3 # connecting to the database conn = sqlite3.connect("illness.db") c = conn.cursor() def create_table(): c.execute("CREATE TABLE IF NOT EXISTS illnesses(illnessID INTAGER PRIMARY KEY NOT NULL, illness VARCHAR(30), illnessinfo VARCHAR(50)") c.execute("CREATE TABLE IF NOT EXISTS symptoms(symptomID INTAGER PRIMARY KEY NOT NULL, symptom VARCHAR(50)") def data_entry(): c.execute("INSERT INTO illnesses VALUES(,'Flu','Influenza - Common Cold.')") c.execute("INSERT INTO illnesses VALUES(,'Acne','Skin Condition')") c.execute("INSERT INTO illnesses VALUES(,'Alcohol Misuse','Mega Hangover')") c.execute("INSERT INTO symptoms VALUES(,'Headache')") c.execute("INSERT INTO symptoms VALUES(,'Spots')") c.execute("INSERT INTO symptoms VALUES(,'Breathing problems')") conn.commit() c.close() conn.close() create_table() data_entry() As per the title this is what i'm running on for a database (Using LiClipse) however it just doesn't work and i'm not sure why (As a note: I looked at youtube video's to try and sort this out and i'm just really new to python and not sure how to really go about doing this at all. On top of this i'm not even sure if using Liclipse is the best option at all. it was just suggested by a friend...
type: Question
has comment: http://stackoverflow.com/comment/85350220
has title: Python - Trying to make a questionaire pulling answers from a DB
answer count: 1
has comment: http://stackoverflow.com/comment/85350523
tagged with: python
has answer: http://stackoverflow.com/a/49173106
has comment: http://stackoverflow.com/comment/85347600
type: AnsweredQuestion
tagged with: sql

http://stackoverflow.com/comment/85428918
type: Comment
type: AnswerComment
has text: the `window.connect("key-press-event", self.key_press)` would be the same for you.
comment on: http://stackoverflow.com/a/49204887
score: 0

http://stackoverflow.com/comment/85423165
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49209260
has text: Almost certainly, this error message comes with a [stacktrace](https://en.wikipedia.org/wiki/Stack_trace) where you can exactly see what line has caused the problem. Can you post the stack trace as well?
type: Comment

http://stackoverflow.com/a/49683667
has body: It might not be possible. Guido van Rossum stated before that he didn't want recursive event loops And it seems like you're creating a nested event loops
type: Answer
answers question: http://stackoverflow.com/q/49154106
downvote count: 0
upvote count: 7
score: 7

http://stackoverflow.com/comment/85443353
type: Comment
score: 0
type: AnswerComment
has text: Many thanks for your detailed description. When you said: @decorator(arg1, arg2) def myfun(...): ... # Which is actually equivalent to... myfun = decorator(arg1, arg2)(myfun) I don't understand this syntax of function call (I'm a beginner), shouldn't all arguments of a function call be like (a1, a2, . . .)? What you suggests is fun (a1, a2) (...) I don't know this syntax.
comment on: http://stackoverflow.com/a/49211813

http://stackoverflow.com/q/49126063
answer count: 1
has title: Convert nested dictionary to multilevel dataframe
downvote count: 1
type: AnsweredQuestion
tagged with: python-2.7
tagged with: pandas
score: 1
tagged with: python
favorite count: 0
type: Question
has body: I have a dictionary which looks like this. { '11457': { 'Client Orders': { 'Z07640C': 422, 'Z04276B': 93, 'Z15421A': 178, 'Z77679': 4}, 'Name': 'SANDY', 'Total Orders': 697}, '1191': { 'Client Orders': { 'Z03456B': 101, 'Z10424A': 754, 'Z10453SR': 84, 'Z13454': 658, 'Z13846': 279}, 'Name': 'Deep', 'Total Orders': 1876}, '13139': { 'Client Orders': { 'Z32421A': 2, 'Z43487B': 24, 'Z44411LR': 6, 'Z54611SR': 2}, 'Name': 'Sran', 'Total Orders': 34}} I want to convert this to into a dataframe which looks like. | Code | Name | Total | Trading Account | Count | |11475 | SANDY| 697 | Z07640C | 422 | | | | | Z04276B | 93 | ... |13139 |Sran | 34 | Z32421A | 2 | | | | | Z43487B | 24 | ... My primary key is the code and the secondary key is Name. I want it to look like this when I export it to csv.
tagged with: export-to-csv
upvote count: 2
has answer: http://stackoverflow.com/a/49126113
accepted answer: http://stackoverflow.com/a/49126113

http://stackoverflow.com/a/51060365
score: 29
has body: For anyone running into this, this will create a bitmask with approximately 80% zero's directly on GPU. (PyTorch 0.3) torch.cuda.FloatTensor(10, 10).uniform_() &gt; 0.8
accepted answer of: http://stackoverflow.com/q/49216615
type: Answer
answers question: http://stackoverflow.com/q/49216615
upvote count: 29
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85523517
score: 0
type: Comment
type: QuestionComment
has text: In addition to [the duplicate](https://stackoverflow.com/questions/44642966/how-to-plot-multi-color-line-if-x-axis-is-date-time-index-of-pandas) also see [this question](https://stackoverflow.com/questions/47851492/plot-curve-with-blending-line-colors-with-matplotlib-pyplot) for possible optimizations.
comment on: http://stackoverflow.com/q/49259569

http://stackoverflow.com/comment/85383932
has text: For example, requests.post() may be able to simplify the steps and get the results faster.
score: 0
comment on: http://stackoverflow.com/q/49188515
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85479875
has text: `random.sample(range(len(cnames),k=6)` will sample without replacement 6 numbers between 0 and len(cnames). U can use `choices(...)` if you want them with replacement.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49236418
type: QuestionComment

http://stackoverflow.com/comment/85291011
score: 0
type: Comment
type: QuestionComment
has text: @CoreyGoldberg that's during generation time, but I want to specify this info at runtime
comment on: http://stackoverflow.com/q/49142551

http://stackoverflow.com/comment/85417153
type: QuestionComment
has text: You are more likely to get responses if you give a [**Minimal, Complete, Verifiable** Example](https://stackoverflow.com/help/how-to-ask) in your question.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49206003

http://stackoverflow.com/a/49174521
score: 0
answers question: http://stackoverflow.com/q/49174390
has comment: http://stackoverflow.com/comment/85354791
has comment: http://stackoverflow.com/comment/85354049
has comment: http://stackoverflow.com/comment/85354614
has comment: http://stackoverflow.com/comment/85355490
has body: If you are indexing rows for a particular column say 'a', you can use .iloc indexer (i stands for index, loc means location) to index on the columns. df = pd.DataFrame({'a': [1,2,3,4]}) print(df.a.iloc[:2]) # get first two values So, you can do: for i in range(3, 10): print(df.a.iloc[:i])
has comment: http://stackoverflow.com/comment/85354269
type: Answer

http://stackoverflow.com/comment/85276688
type: Comment
comment on: http://stackoverflow.com/a/49132483
type: AnswerComment
score: 0
has text: So `logs_from` is a coroutine, which is a special form of generator that can be interacted with asynchronously. Unfortunately, coroutines can't be used in ways a normal generator could, like inside something that consumes an iterable (`any` in our case). `x async for x in client...` is an asynchronous generator expression. So we're basically making a bridge between the `any` code, which is not asynchronous and the `logs_from` code, which is.

http://stackoverflow.com/a/49141485
type: AcceptedAnswer
has body: You are giving your ResourceSerializer the wrong model instances. resources = group.bookmarks.all() serialized = ResourceSerializer(resources, many=True) Here you are telling your serializer to use group.bookmarks.all() as data source which are instances of Bookmark, not Resource.
has comment: http://stackoverflow.com/comment/85318097
has comment: http://stackoverflow.com/comment/85318570
accepted answer of: http://stackoverflow.com/q/49140454
type: Answer
answers question: http://stackoverflow.com/q/49140454
score: 0
has comment: http://stackoverflow.com/comment/85317363

http://stackoverflow.com/q/49156749
has answer: http://stackoverflow.com/a/49159792
score: 1
has body: I have a list (QuerySet of 'DailyEnrollment' objects) of dictionaries that looks like this: [ {'location_id': 1, 'student_count': 780}, {'location_id': 4, 'student_count': 535}, {'location_id': 6, 'student_count': 496} ] There is a Location object which has an attribute name - the location_id in this list, correlates to a Location object but it is not a foreign key (in the models) due to how other apps interact with this in our project. Is there a simple way to iterate across this list, get each dictionaries location.name for the location_id and append it to the dictionary as location_name? I was considering a dictionary comprehension inside of a list comprehension - but I wasn't sure how Pythonic that was. Models: class Location(models.Model): name = models.CharField(max_length=50) short_name = models.CharField(max_length=50) The DailyEnrollment is data nabbed from a view built with external data class DailyEnrollment(SchoolModel): id = models.IntegerField(db_column='ID', primary_key=True) location_id = models.IntegerField(db_column='schoolID') grade = models.CharField(db_column='grade', max_length=10) end_year = models.IntegerField(db_column='endYear') run_date = models.DateField(db_column='runDate') student_count = models.IntegerField(db_column='studentCount') In the view this is how I get my Daily Enrollments # get past enrollments past_daily_enrollments = DailyEnrollment.objects.filter( run_date=datetime.strptime(since_date, '%m-%d-%Y'), location_id__lte='31', end_year='2018') I create a 'new list' of data with everything grouped on location_id, with the total student_count location_data = past_daily_enrollments.values('location_id').annotate( student_count=Sum('student_count') ) That's how I get to the issue I asked about. I have 'location_data', which is my list of dictionaries.
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85318277
type: AnsweredQuestion
has title: Get reverse relationship for item in a list of dictionaries
has comment: http://stackoverflow.com/comment/85318261
has comment: http://stackoverflow.com/comment/85319164
tagged with: django
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85319782
has comment: http://stackoverflow.com/comment/85318338
possible better answer: http://stackoverflow.com/a/49159792
accepted answer: http://stackoverflow.com/a/49173785
tagged with: list
answer count: 2
has answer: http://stackoverflow.com/a/49173785

asynchronous
tags question: http://stackoverflow.com/q/49205092
tags question: http://stackoverflow.com/q/49188763
type: Tag
tags question: http://stackoverflow.com/q/49185891
tags question: http://stackoverflow.com/q/49199638
tags question: http://stackoverflow.com/q/49150587
tag name: asynchronous

http://stackoverflow.com/comment/87176928
comment on: http://stackoverflow.com/a/50080269
type: AnswerComment
score: 0
has text: Looks promising. But it also looks like you found that by sifting through the source code. If at all possible, I'd prefer a solution that's backed by some documentation or a PEP or any other resource that indicates that this isn't just an implementation detail.
type: Comment

http://stackoverflow.com/comment/85502210
has text: It is success. I typed "sudo pip install paho-mqtt", but I tried so many times with this command.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49235590
type: QuestionComment

http://stackoverflow.com/q/49240235
type: Question
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/86644742
has comment: http://stackoverflow.com/comment/85532467
score: 1
downvote count: 0
upvote count: 1
tagged with: google-ads-api
has title: Google Adwords API v201802 not working
has body: I am using Adwords API googleads version 201710 and try to migrate to v201802. I didn't change anything except for "version = 'vxxxxxx'" (as I did when migrated to v201710) targeting_idea_service = client.GetService('TargetingIdeaService', version='v201802') However it returns: Unrecognized version for the AdWords API. Given: v201802 Supported: ['v201702', 'v201705', 'v201708', 'v201710'] I think v201802 should be working not. googleads version dates Is there anything I can do to migrate to v201802 now? Thanks!
favorite count: 0

http://stackoverflow.com/q/49274174
upvote count: 2
tagged with: numpy
has title: Performance of double np.einsum and how to speed up
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85551209
score: 2
has body: Consider this MWE: import numpy as np a = np.random.uniform(0,1,size=[14,25,25]) b = np.random.uniform(0,1,size=[14,25,25]) c = np.random.uniform(0,1,size=[14,25]) def my_func(a,b,c): InnerSum = np.einsum('lpk, lkm -&gt; lpm', a, b) OuterSum = np.einsum('lp, lpm -&gt; lm', c, InnerSum ) Result = 2 * OuterSum return Result my_func() was my first attempt to do the calculation but I wanted to speed it up. I then tried it with the following modified function: def my_func_2(a,b,c): OuterSum = np.einsum('lpk, lkm, lp -&gt; lm', a, b, c) Result = 2 * OuterSum return Result However, when I run %timeit on both functions, I get %timeit my_func(a,b,c) 293 µs ± 1.37 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) %timeit my_func_2(a,b,c) 347 µs ± 1.47 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) Why is the second approach slower than the first? How can I optimize my_func() to make it faster?
type: AnsweredQuestion
tagged with: performance
downvote count: 0
tagged with: python
tagged with: numpy-einsum
has comment: http://stackoverflow.com/comment/85550965
has answer: http://stackoverflow.com/a/49274754
accepted answer: http://stackoverflow.com/a/49274754
type: Question

http://stackoverflow.com/comment/85509218
type: Comment
type: QuestionComment
has text: This is a good time to read ["Understanding `repr()` function in Python"](https://stackoverflow.com/questions/7784148/understanding-repr-function-in-python). Long story short: `<Address object at 0x7fe...>` is the string representation of an `Address` object. In other words you're seeing exactly what you should be seeing, given `print(answer.adr)`. If you want to see emails of individual addresses, loop over the address objects.
score: 0
comment on: http://stackoverflow.com/q/49252722

http://stackoverflow.com/q/49200272
upvote count: 9
possible better answer: http://stackoverflow.com/a/49200302
tagged with: arrays
downvote count: 0
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/75791382
has comment: http://stackoverflow.com/comment/85405714
has answer: http://stackoverflow.com/a/49200389
accepted answer: http://stackoverflow.com/a/49200309
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49200329
has answer: http://stackoverflow.com/a/67475309
has answer: http://stackoverflow.com/a/49200309
has body: Usually when creating certain sequences of numbers, python and numpy offer some syntactic sugar to do so in a simple way, without generating them yourself with for-loops, e.g. range(start, stop, step). I'm having a rather simple problem that I'm struggling to solve in an elegant way: Generate a list of the powers of two. E.g. list = [1, 2, 4, 8, ...]. I came up with n_powers = 4 list = np.zeros(n_powers) for i in range(0, n_powers): list[i] = 2 ** i Is there a better way to do this?
has comment: http://stackoverflow.com/comment/85405818
has answer: http://stackoverflow.com/a/49200302
has comment: http://stackoverflow.com/comment/85405692
favorite count: 0
score: 9
type: Question
tagged with: numpy
has title: Generate a NumPy array with powers of 2

http://stackoverflow.com/comment/85433113
has text: The error sounds like it expects the object to have uv's and it doesn't. You should [unwrap it](https://docs.blender.org/manual/en/dev/editors/uv_image/uv/editing/unwrapping/introduction.html), or at least [create a new uvlayout](https://docs.blender.org/manual/en/dev/editors/uv_image/uv/layout_management.html#uv-maps-panel) and then try.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49199787

http://stackoverflow.com/a/49145399
answers question: http://stackoverflow.com/q/49145344
score: 1
has comment: http://stackoverflow.com/comment/85308606
type: Answer
has body: It seems you need to escape the backslashes in your file path. So the line should be: DOWNLOAD_BASE = 'file:H:\\New_folder\\models\\research\\object_detection'
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85493427
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49244171
type: Comment
has text: import numpy as np def Gaussian(sigma, x, mu): p = 1/(sigma*np.sqrt(2*np.pi))*np.exp(-(x-mu)**2/(2*sigma**2)) return p N = 10 x=[] for i in range(0,N): x.append(0.5) results = [] for i in range (0,N): y = x[i] + np.random.normal(0,0.01) H = Gaussian(1,y,1)/Gaussian(1,x[i],1) alpha = np.random.uniform(1,1) # print x[i] if H >= alpha: x.append(y) results.append(y) print(results) Read this code snippet, will work for you

http://stackoverflow.com/comment/85509195
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49252791
score: 1
has text: Sometimes there are valid use-cases to create a dictionary for classes in order to reference them by a dynamic string. But yours does not seem to be one of these cases.

http://stackoverflow.com/q/49136190
accepted answer: http://stackoverflow.com/a/49155149
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49155149
has title: Google App Engine Flexible Python service fails with "ModuleNotFoundError: No module named 'google'"
score: 0
has comment: http://stackoverflow.com/comment/85282742
answer count: 1
tagged with: python-3.x
has body: I am deploying a Python3 app to Google App Engine Flexible Environment. I have all my dependencies listed in the requirements.txt file. During deployment I received messages indicating the Google libraries have been deployed. But, when the service is started it fails with from google.cloud import storage ModuleNotFoundError: No module named 'google' This runs fine locally.
tagged with: importerror
type: Question
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/85279465
tagged with: python

http://stackoverflow.com/a/49177249
type: Answer
accepted answer of: http://stackoverflow.com/q/49177227
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49177227
downvote count: 0
score: 1
upvote count: 1
has body: I think one general solution is select first value by [0] for scalar: print (df2['x'].values[0]) 1 df['a'] = df['a'].fillna(df2['x'].values[0]) #similar solution for select by loc #df['a'] = df['a'].fillna(df2.loc[0, 'x']) print (df) a b 0 2.0 10 1 3.0 11 2 5.0 13 3 1.0 14 4 1.0 15

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

http://stackoverflow.com/comment/85355792
has text: Well did you define `x`? Maybe you meant `i`?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49175416
score: 3

http://stackoverflow.com/q/49252636
upvote count: 1
score: 1
has title: Grant permission to an app to interact with SSMS regardless of the user permission
has body: I have a python application that interacts with the database (create/delete tables, insert/delete records). Therefore, It should have a high permission on SQL management studio. What I would like to do is for the application to be able to interact with the DB regardless of the user permission. I created an application role and assign it to the app. I know that the application role is activated because it used to cause some problems (which I could solve). but I still have a big issue that is the app still relies on the user logins, so anyone with not enough permission is not able to use the code. Here is part of the python code where the connection with the server is established: server = '*****' database = '*****' driver = 'SQL+Server' connection_string = 'mssql+pyodbc://%s/%s?driver=%s? trusted_connection=true' % (server, database, driver) engine = create_engine(connection_string, pool_recycle=-1, echo=False) metadata = MetaData(bind=engine) Session = sessionmaker(bind=engine) Session = sessionmaker(bind=engine) session = Session() role = 'Python_app' role_password = '******' session.execute("EXEC sp_setapprole '%s', '%s'" % (role, role_password)) On this link a screenshot of the application role can be found I have tried a lot of different things but I was not able to solve the problem. I will be glad if someone could point me out in the right direction.
tagged with: sqlalchemy
favorite count: 0
type: Question
tagged with: ssms
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85510452
tagged with: python
tagged with: sql-server
has comment: http://stackoverflow.com/comment/85511354
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/85252124
has text: @cᴏʟᴅsᴘᴇᴇᴅ Thank you for your comment. I don't mind transforming it into a dataframe. Do you happen to know how to do this job on pandas?
comment on: http://stackoverflow.com/q/49123406
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49191671
score: 0
answers question: http://stackoverflow.com/q/49188794
type: AcceptedAnswer
has body: You have grades already in self.stdGrade So, you don't need to pass anything in the method AVGofGrades, as you are providing all the arguments needed when you create the Student Object. Your AVGofGrades can be as below: def AVGofGrades(self): return sum(self.stdGrade)/len(self.stdGrade) You can now create an instance of the class and get the AVGofGrades as below: std1 = Student("georges", 17, 80,23,50,34,80,78) print(std1.AVGofGrades())
type: Answer
accepted answer of: http://stackoverflow.com/q/49188794

gaussian
tags question: http://stackoverflow.com/q/49266014
tags question: http://stackoverflow.com/q/49256917
tags question: http://stackoverflow.com/q/49221909
tags question: http://stackoverflow.com/q/49131534
tags question: http://stackoverflow.com/q/49130343
type: Tag
tag name: gaussian
tags question: http://stackoverflow.com/q/49128526

http://stackoverflow.com/comment/85463428
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49229061
type: AnswerComment
has text: Thanks. By the way it's door open after door close. Seems to work. I will try it when I get home and I'll post here if it works :)

http://stackoverflow.com/comment/85426767
type: Comment
score: 0
type: AnswerComment
has text: Your answer is definitely helpful and hence I would upvote it, but I am not looking for external numpy arrays to K.variable conversion. I have updated the EDIT to clarify what I am seeking for!
comment on: http://stackoverflow.com/a/49196727

http://stackoverflow.com/comment/85454342
type: AnswerComment
comment on: http://stackoverflow.com/a/49224463
has text: yes, no need for lambda. it was a oneline function, but not necessary.
type: Comment
score: 0

merge
type: Tag
tags question: http://stackoverflow.com/q/49201814
tags question: http://stackoverflow.com/q/49268475
tags question: http://stackoverflow.com/q/49142836
tags question: http://stackoverflow.com/q/49216237
tags question: http://stackoverflow.com/q/49243151
tags question: http://stackoverflow.com/q/49231909
tags question: http://stackoverflow.com/q/49121631
tag name: merge
tags question: http://stackoverflow.com/q/49262327
tags question: http://stackoverflow.com/q/49202420
tags question: http://stackoverflow.com/q/49182288
tags question: http://stackoverflow.com/q/49122623
tags question: http://stackoverflow.com/q/49232939
tags question: http://stackoverflow.com/q/49245392
tags question: http://stackoverflow.com/q/49224355
tags question: http://stackoverflow.com/q/49203723

http://stackoverflow.com/a/49177727
score: 0
answers question: http://stackoverflow.com/q/49177583
has body: Try using pandas with something like df = pandas.read_csv('my_data.csv'). You'll have more granular control over how the data is read in. If you're worried about formatting, you can also set the delimiter for the csv from libreoffice to something that doesn't occur in nature like ;;
type: Answer

http://stackoverflow.com/a/49185064
has comment: http://stackoverflow.com/comment/85376003
has comment: http://stackoverflow.com/comment/85375876
downvote count: 0
has body: The result of urlopen obviously isn't a filename, so you can't pass in filename=f and expect it to work. I don't have Wand installed, but from the docs, there are clearly a bunch of alternative ways to construct it. First, urlopen is a file-like object. Of course "file-like object" is a somewhat vague term, and not all file-like objects work for all APIs that expect file-like objects (e.g., the API may expect to be able to call fileno and read from it at the POSIX level…), but this is at least worth trying (note file instead of filename): with Image(file=f) as img: If that doesn't work, you can always read the data into memory: buf = f.read() with Image(blob=buf) as img: Not as ideal (if you have giant files), but at least you don't have to store it on disk.
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49184969
type: Answer
answers question: http://stackoverflow.com/q/49184969

http://stackoverflow.com/q/49195814
has answer: http://stackoverflow.com/a/49197568
tagged with: python
accepted answer: http://stackoverflow.com/a/49197568
has body: I have a very very specific problem. I am trying to figure out a way to embed an HTML brower in my app, in order to show some generated HTML content with included javascript. I tried to do it with wx.html2, but the javascript part just seems to not work. So I decided to give a try to CEFPython by taking example of the provided wxPython.py demo. At first, it worked great in the UI I designed. BUT, the problem is that this UI is intended to be called from another application, as a sort of "plug-in UI". And when launching my wxPython UI from this application, it crashes as soon as cef is initialized (through: sys.excepthook = cef.ExceptHook settings = { "debug": True, "log_severity": cef.LOGSEVERITY_INFO, "log_file": "debug.log", } cef.Initialize(settings=settings) app = CefApp(False) app.MainLoop() del app cef.Shutdown() I keep getting this error: Python exception: AttributeError 'module' object has no attribute 'argv' Traceback (most recent call last): File "&lt;string&gt;", line 248, in &lt;module&gt; File "&lt;string&gt;", line 36, in main File "cefpython_py27.pyx", line 626, in cefpython_py27.Initialize (cefpython_py27.cpp:99136) AttributeError: 'module' object has no attribute 'argv' So in the end I have 2 questions: is there a way with wx.html2 to show HTML content embedding javascript if not, do you have a clue of what would cause the launched UI to crash? I guess it's a threading matter but I'm not even sure. Please excuse my english mistakes by the way, as I'm not native.
type: AnsweredQuestion
score: 1
downvote count: 0
answer count: 1
tagged with: wxpython
upvote count: 1
favorite count: 0
type: Question
tagged with: chromium-embedded
tagged with: cefpython
has title: CEFPython won't initialized when called from an application

http://stackoverflow.com/comment/85330939
type: QuestionComment
comment on: http://stackoverflow.com/q/49151662
score: 0
has text: Possible duplicate of [pip install -r: OSError: \[Errno 13\] Permission denied](https://stackoverflow.com/questions/31512422/pip-install-r-oserror-errno-13-permission-denied)
type: Comment

http://stackoverflow.com/a/72775998
downvote count: 1
has body: Try this one - df.columns.values
upvote count: 5
has comment: http://stackoverflow.com/comment/128547614
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/128664608
answers question: http://stackoverflow.com/q/49188960

http://stackoverflow.com/comment/85452206
type: Comment
comment on: http://stackoverflow.com/a/49222316
score: 0
has text: Tried and installed. It didn't help
type: AnswerComment

http://stackoverflow.com/q/49216609
answer count: 1
has body: Let say we have a map-dict and data-dict : m = { 1:2, 4:5, 3:7 } data = { 1:7, 4:1, 3:6 } we should replace all occurrences both key&amp;val in "data" according to "m" : data1 = { 2:7, 5:2, 7:6 } what is the shortest, fast way to do this ? I was thinking of converting data to list do the replacements and convert back to dict. But even that gets too involved. Converting list to dict is OK : dict(zip(lst[0::2], lst[1::2])) Converting dict to list is : data.items() but this one does not return list, but list of tuples, which make things too involved i.e we need to additionally flatten this LoT. I was wondering if there is a better way, with emphasis on speed/mem.
has comment: http://stackoverflow.com/comment/85437271
type: Question
tagged with: substitution
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/49216630
has answer: http://stackoverflow.com/a/49216630
has title: Best way to substitute both K&V based on a map?
type: AnsweredQuestion
score: 0
tagged with: list
tagged with: mapping

http://stackoverflow.com/a/55541231
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49194147
score: 34
upvote count: 34
answers question: http://stackoverflow.com/q/49194147
type: Answer
has body: Use click.echo with click.style click.echo(click.style("Error", fg="red") + ": This error is...")
type: AcceptedAnswer

http://stackoverflow.com/comment/85385241
type: Comment
type: AnswerComment
has text: Read the link again. It say that `APPLICATION_ROOT` handle the cockies and so on. Your WSGI (and similar) should handle the URL, They should remove the route prefix (for URL). So this part (and configuration) is on IIS side.
score: 0
comment on: http://stackoverflow.com/a/49189558

http://stackoverflow.com/q/49130108
has answer: http://stackoverflow.com/a/50881236
tagged with: keras
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/50880662
tagged with: python
has title: Tensorflow image classification - Probability prediction for input images
score: 0
answer count: 2
has body: I have trained my model using Keras for image classification using tensorflow, and here's the code where my model is trying to predict an input image. import numpy as np from keras.preprocessing import image test_image = image.load_img('C:/Python/3.png', target_size = (64, 64)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis = 0) result = classifier.predict(test_image) training_set.class_indices if result[0][0] == 1.0: prediction = 'Anthracite' if result[0][0] == 2.0: prediction = 'Bituminous' if result[0][0] == 3.0: prediction = 'Lignite' else: prediction = 'Peat' Basically, i am working on an image classification problem where i am training my model by giving 4 types of coal, and my prediction is almost 80% perfect as i have trained my model with 25 epochs. What i need is, the probability of each type of coal, let say, if my prediction says: It's lignite coal, it should also tell me the probability of accuracy that it's lignite, need help on this..
has comment: http://stackoverflow.com/comment/85278280
has comment: http://stackoverflow.com/comment/85294308

http://stackoverflow.com/comment/85545273
score: 0
has text: thank you, in general this works, but due to some reason, in my case some of the materials get combined in the same sectionCategory. In other words, the number of sectionCategories is less than the number of materials. Unfortunatelly, I cannot change the approach to the sections/sets assignment, because I get the .inp-files from outside and they contain too complicated geometry to change it manually.
comment on: http://stackoverflow.com/a/49263047
type: AnswerComment
type: Comment

http://stackoverflow.com/a/49156821
has comment: http://stackoverflow.com/comment/86528079
upvote count: 2
has comment: http://stackoverflow.com/comment/86395474
downvote count: 0
has body: tf.estimator.Estimator classes indeed create a new graph for each invocation and this has been the subject of furious debates, see this issue on GitHub. Their approach is to build the graph from scratch on each train, evaluate and predict invocations and restore the model from the last checkpoint. There are clear downsides of this approach, for example: A loop that calls train and evaluate will create two new graphs on every iteration. One can't evaluate while training easily (though there are workarounds, train_and_evaluate, but this doesn't look very nice). I tend to agree that having the same graph and model for all actions is convenient and I usually go with this solution. But in a lot of cases when using a high-level API like tf.estimator.Estimator, you don't deal with the graph and variables directly, so you shouldn't care how exactly the model is organized.
type: Answer
has comment: http://stackoverflow.com/comment/86527796
has comment: http://stackoverflow.com/comment/86526785
answers question: http://stackoverflow.com/q/49155206
score: 2

http://stackoverflow.com/comment/85382659
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49187039
has text: My error is that when I access my website I see an Internal Server Error message instead of my website
score: 0

http://stackoverflow.com/comment/85483673
has text: Hi, I think your solution is what I'm looking for but I have a problem with IndexError : too many indices. The array shape is (x,) (x is a number)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49239335
type: AnswerComment

http://stackoverflow.com/a/49226028
has body: surely the object does have that attribute since it is of the class "pigLatin_class"? But it's not. You do create an instance of pigLatin_class, but then you immediately replace it with an instance of str: words = pigLatin_class() words = "Hi I'm Amy" And str isn't pigLatin_class, and doesn't have a pLatin_converter method. I think you wanted something like this: words = pigLatin_class("Hi I'm Amy") words.pLatin_converter() But then you need to fix a few more bugs. Most crucially, the __init__ method of your class has to take a self parameter, as well as a string parameter, and then it needs to store things—including that string parameter value—on that self to be used later: def __init__(self, string): self.string = string self.pig = "" self.movetoend = "" self.index = 0 And then, your methods will also take self and can use those attributes: def pLatin_converter(self): listeng = self.string.split() # etc. You may have instead wanted something like this: words = pigLatin_class() words.pLatin_converter("Hi I'm Amy") In that case, you won't be taking string as a second parameter in __init__ and storing it in self.string, you'll instead be taking it as a second parameter in pLatin_converter. Hopefully you know enough now to change it to work that way, and to understand the difference.
accepted answer of: http://stackoverflow.com/q/49226004
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49226004
upvote count: 3
score: 3
type: Answer

http://stackoverflow.com/comment/85462909
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49228683
score: 0
has text: I loaded the three csv files with read_csv(...). Now i have selected the max values per column of the three csv files. Now I want to export these max values per location to a new csv file. However I'm didn't manage to execute the last step.

http://stackoverflow.com/q/49239475
answer count: 2
has title: How to use MDAnalysis to principal_axes and moment_of_inertia with a group of atoms?
downvote count: 0
has answer: http://stackoverflow.com/a/49268247
upvote count: 1
score: 1
favorite count: 0
tagged with: python-3.x
has body: I am trying to use MDAnalysis (MDAnalysis.__version__ == 0.17.0) API functions principal_axes() and moment_of_inertia() to calculate these matrices for a group of selected atoms as described in the doc: import MDAnalysis from MDAnalysis.tests.datafiles import PSF, DCD import numpy as np u = MDAnalysis.Universe(PSF, DCD) CA = u.select_atoms("protein and name CA") I = np.matrix(CA.moment_of_inertia()) U = np.matrix(CA.principal_axes()) print("center of mass", CA.center_of_mass()) print("moment of inertia", I) print("principal axes", U) print("Lambda = U'IU", np.transpose(U)*I*U) The output: center of mass [ 0.06873595 -0.04605918 -0.24643682] moment of inertia [[ 393842.2070687 -963.01376005 -6050.68541811] [ -963.01376005 474434.9289629 -3902.61617054] [ -6050.68541811 -3902.61617054 520207.91703069]] principal axes [[-0.04680878 -0.08278738 0.99546732] [ 0.01813292 -0.9964659 -0.08201778] [-0.99873927 -0.01421157 -0.04814453]] Lambda = U'IU [[ 519493.24344558 -4093.3268841 11620.96444297] [ -4093.3268841 473608.1536763 7491.56715845] [ 11620.96444297 7491.56715845 395383.6559404 ]] This looks wrong, one of the reason is that U'IU isn't diagonal as mentioned in the doc: Maybe I need to align the protein to the center of mass to calculate the moment of inertia with respect to that.
type: Question
tagged with: physics
has answer: http://stackoverflow.com/a/49249129
has comment: http://stackoverflow.com/comment/85516273
tagged with: python
tagged with: mdanalysis
has comment: http://stackoverflow.com/comment/85512665
tagged with: chemistry
possible better answer: http://stackoverflow.com/a/49249129
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49268247

http://stackoverflow.com/a/49241499
has comment: http://stackoverflow.com/comment/85486744
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49241470
has body: append doesn't return anything. The last line should just be: vdf_big_list.append(vdf_s_lines_list)
accepted answer of: http://stackoverflow.com/q/49241470
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49223358
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85473842
tagged with: neural-network
downvote count: 0
tagged with: machine-learning
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85472860
has comment: http://stackoverflow.com/comment/85453293
has comment: http://stackoverflow.com/comment/85474052
has comment: http://stackoverflow.com/comment/85472492
has body: I've build a neural network (NN) having only 6 inputs and 8 classes (it is thus a classifier I'm building). To give some more background: The number of training samples is 80,000 samples as is the dev/cross-validation set size (I know this is not a good split, but to compare my outputs to those of my colleague, I have to keep the train/dev sets as is). The input features are following relatively well defined probability density functions, albeit not Gaussian. Due to the large number of inputs relative to the number of features, the data set is 'practically impossible' to overfit, and I have not yet succeeded in doing this (even with very large networks). This is intuitively correct since the feature pdf's are overlapping and dense enough to prevent curve loops to gather more and more samples. Now, since I like to test the limits of algo's and thus also my NN, I've ran a week-long monte-carlo session varying all parameters, including the number of layers and the number of nodes per layer as hyperparameters. I've noticed that in many cases (when the number of layers and nodes per layer are large enough) the NN converges after some time (let's say 300+ interations), then levels out, but after a few hundred iterations more, it starts to diverge and become unstable (non-smooth and showing large jumps). I know from basic NN theory that for the case I'm describing (6 inputs, 8 classes) a single hidden layer with around 10 nodes should suffice (and it does by the way), but I would expect a NN having more layers and having more nodes per layer to at least not diverge and stay approximately around the minimum. Especially, since when the gradient is zero, the step size must become by definition zero, right? or am I missing something? Now my question is twofold: Is there some theory on how one can predict when a NN will diverge? Since I'm going to try my hand at a problem more suitable to solve via a (convolutional) NN, I would like to at least have some insight in this matter.…
tagged with: backpropagation
has comment: http://stackoverflow.com/comment/85474234
score: 1
has comment: http://stackoverflow.com/comment/85472924
has comment: http://stackoverflow.com/comment/85473747
favorite count: 0
type: Question
tagged with: numpy
has title: What makes a (too large) neural network diverge?
answer count: 0

http://stackoverflow.com/comment/85432796
score: 0
has text: python 3.6 (64 bit)
comment on: http://stackoverflow.com/q/49213469
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85477410
score: 0
comment on: http://stackoverflow.com/q/49222881
type: QuestionComment
has text: @Ryan Thanks! Yes indeed I have used "sudo install..." in the past, and now I see the consequences!
type: Comment

http://stackoverflow.com/a/49206468
has comment: http://stackoverflow.com/comment/85417911
score: 2
has comment: http://stackoverflow.com/comment/85417995
type: AcceptedAnswer
has body: Your method has to accept self as default parameter. change addsort method signature as below. Adding self as parameter makes the method available for all the objects/instances of the class. obj = App() obj.addsort() def addsort(self): self.mytable.append(['Evans', '4', '2:23.717']) print(self.sorted) If you don't want addsort to be called/used by an instance, make it a class method and make sure it is not dependent on any of the self parameters.
accepted answer of: http://stackoverflow.com/q/49206448
upvote count: 2
answers question: http://stackoverflow.com/q/49206448
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85287842
has text: @haifzhan that was a copying mistake, corrected now
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49141186

http://stackoverflow.com/comment/85463285
score: 0
has text: I think there's actually a good question buried in here that you just didn't ask right. I tried to answer that question as well as the one you actually did ask. If you're still confused, let me know what's confusing and I can probably improve it.
type: Comment
comment on: http://stackoverflow.com/q/49229538
type: QuestionComment

http://stackoverflow.com/q/49241077
type: UnansweredQuestion
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85487078
has comment: http://stackoverflow.com/comment/85486141
has comment: http://stackoverflow.com/comment/85486710
upvote count: 1
score: 1
has body: Given a csv file, where each line contains a set of number, i want to write a map reduce program which determines the maximum number of all numbers in the file. lets say the csv file is 3,4 5,6 the script should return 6. from mrjob.job import MRJob class MRWordCounter(MRJob): def mapper(self, key, line): for word in line.split(): yield word, 1 def reducer(self, word, occurrences): yield word, sum(occurrences) if __name__ == '__main__': MRWordCounter.run() Now this script i found returns the occurences, but does not work if you have multiple values in each line. How could i parse all the data on the csv file and return the maximum? UPDATE: so the input file that i tried to parse as a test is something this: 1,1,1,1 2 3 4 5 6 after changing the line.split() into line.split(",") it counted all the occurrences normally.
has comment: http://stackoverflow.com/comment/85486275
tagged with: mapreduce
tagged with: mrjob
favorite count: 0
type: Question
has title: python mapreduce mrjob max value
answer count: 0

http://stackoverflow.com/a/49165821
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49165767
has body: When you use input() the input comes as a string, and in your while loop you set your condition to be equal to 1 (as an integer). A solution to this would be: varname = int(input("")) #this way it converts your input into an integer
type: Answer
score: 2

ctypes
tags question: http://stackoverflow.com/q/49142169
tags question: http://stackoverflow.com/q/49159952
tags question: http://stackoverflow.com/q/49216412
tags question: http://stackoverflow.com/q/49266538
tags question: http://stackoverflow.com/q/49181097
tags question: http://stackoverflow.com/q/49266385
tags question: http://stackoverflow.com/q/49228106
tags question: http://stackoverflow.com/q/49257742
tags question: http://stackoverflow.com/q/49175959
tag name: ctypes
type: Tag
tags question: http://stackoverflow.com/q/49226640
tags question: http://stackoverflow.com/q/49208498

http://stackoverflow.com/q/49178816
upvote count: 0
tagged with: pyqt4
has comment: http://stackoverflow.com/comment/85365915
has comment: http://stackoverflow.com/comment/85364436
answer count: 1
has comment: http://stackoverflow.com/comment/85571810
has body: pyqt4, after successful login my login window close and next window open. i.e good but if i want close next window and go to login window the error shown here is my code Login.py import DD from PyQt4.QtGui import QMessageBox from PyQt4.QtGui import * from LoginError import LoginError import os class Ui_Login(object): def closeEvent(self, event): # type: (close) -&gt; object QtGui.QMainWindow.closeEvent(self, event) self.saveLayout() def loginCheck(self): username = self.lineEdit_adminusername.text() password = self.lineEdit_adminpassword.text() for line in open("password.txt", "r").readlines(): # Read the lines # str = in.readlines(); # str1 = in.readlines(); loginCheck_info = line.split() # Split on the space, and store the results in a list of two strings # if username == str and password == str1: if username == loginCheck_info[0] and password == loginCheck_info[1]: print("Correct credentials!") try: self.window = QtGui.QMainWindow() self.ui = DD.Ui_DD() self.ui.setupUi(self.window) self.window.show() Login.close() return True except LoginError: sys.exit() sys.exit(app.exec_()) else: print "Incorrect credentials!!!" widget = QWidget() message = QtGui.QMessageBox.warning(widget, "Warning", "Please enter valid username and password") return False # print("Incorrect credentials.") # return False line.close() def reboot(self, event): widget = QWidget() message = QtGui.QMessageBox.question(widget, "Reboot", "Do you really want to Reboot?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) if message == QtGui.QMessageBox.Yes: print "Rebooting..........." os.system("reboot") else: print "Continue" global true; true = 1; def shutdown(self, event): widget = QWidget() message = QtGui.QMessageBox.question(widget, "Shutdown", "Do you really want to Shutdown?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) if message == QtGui.QMessageBox.Yes: print "Going to shutting down..........." os.system("poweroff") else: print "Continue" global tr…
type: Question
has comment: http://stackoverflow.com/comment/85365840
has comment: http://stackoverflow.com/comment/85363016
has title: DD.close() NameError: global name 'DD' is not defined
downvote count: 3
has comment: http://stackoverflow.com/comment/85499521
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85367090
score: -3
favorite count: 0
has comment: http://stackoverflow.com/comment/85378961
has answer: http://stackoverflow.com/a/49284457
tagged with: pyqt
has comment: http://stackoverflow.com/comment/85378938

http://stackoverflow.com/comment/85444408
type: Comment
has text: this will produce an archive with all the file inside, it is true that it will be lighter (like 300mb) but it will be painfully slow. I don't want to just hide them...
type: AnswerComment
comment on: http://stackoverflow.com/a/49220417
score: 0

http://stackoverflow.com/a/49257449
score: 3
upvote count: 3
has body: I solved this issue adding the following to the class: def __del__(self): self.logger.removeHandler(self.handler) self.handler.close()
answers question: http://stackoverflow.com/q/49247356
downvote count: 0
type: Answer

http://stackoverflow.com/q/49183171
upvote count: 1
tagged with: variables
possible better answer: http://stackoverflow.com/a/49198152
tagged with: twython
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: python
tagged with: twitter
has title: Twython - Saving Tweet IDs in a Text File
type: Question
has answer: http://stackoverflow.com/a/49198152
accepted answer: http://stackoverflow.com/a/49183398
answer count: 2
has answer: http://stackoverflow.com/a/49183398
tagged with: save
has body: I am fairly new to Python, but have been enjoying it so far. I've been trying to write a code using Twython that saves the Tweet IDs of all the tweets that match my search query as variables in a file. I find that I can print all of the IDs that pertain to my search query with the following code: import sys from twython import Twython APP_KEY='XXXXXXXX' APP_SECRET='XXXXXXXX' OAUTH_TOKEN='XXXXXXXX' OAUTH_TOKEN_SECRET='XXXXXXXX' twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) I = 12345678910 result = twitter.search(q='WhateverImLooking4', since_id=str(I), count=100) for item in result['statuses']: print(item['id_str'].encode('ascii', 'ignore')) Now, when I change the last two lines to this instead: for item in result['statuses']: f = open('Results.txt','w') f.write(item['id_str'].encode('ascii', 'ignore')) f.close() It will save only the smallest ID number to a text file. I'd like to be able to save all the results to a file AND ideally as variables ready to be used in another python code. Hopefully this all makes sense! Thanks!!
downvote count: 0

http://stackoverflow.com/comment/85367431
comment on: http://stackoverflow.com/q/49180936
type: Comment
has text: are you using sklearn?
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85539435
type: QuestionComment
comment on: http://stackoverflow.com/q/49267816
type: Comment
has text: console log added !
score: 0

http://stackoverflow.com/comment/85387753
comment on: http://stackoverflow.com/q/49191379
score: 1
type: Comment
type: QuestionComment
has text: I really doubt it is working with the capital `I`.

http://stackoverflow.com/comment/85456744
has text: From the top of my head: fork twice, change pgroup, detach from the terminal, read Stevens's APUE
comment on: http://stackoverflow.com/q/49226394
type: QuestionComment
type: Comment
score: 2

recursion
type: Tag
tags question: http://stackoverflow.com/q/49175575
tags question: http://stackoverflow.com/q/49246992
tags question: http://stackoverflow.com/q/49158987
tags question: http://stackoverflow.com/q/49219139
tags question: http://stackoverflow.com/q/49247894
tags question: http://stackoverflow.com/q/49176652
tags question: http://stackoverflow.com/q/49169303
tags question: http://stackoverflow.com/q/49201573
tag name: recursion
tags question: http://stackoverflow.com/q/49249043
tags question: http://stackoverflow.com/q/49216095
tags question: http://stackoverflow.com/q/49165315
tags question: http://stackoverflow.com/q/49256063
tags question: http://stackoverflow.com/q/49222525
tags question: http://stackoverflow.com/q/49139939
tags question: http://stackoverflow.com/q/49204502
tags question: http://stackoverflow.com/q/49258739
tags question: http://stackoverflow.com/q/49185916
tags question: http://stackoverflow.com/q/49226978
tags question: http://stackoverflow.com/q/49185980
tags question: http://stackoverflow.com/q/49209700
tags question: http://stackoverflow.com/q/49199296
tags question: http://stackoverflow.com/q/49235666
tags question: http://stackoverflow.com/q/49249371
tags question: http://stackoverflow.com/q/49171197

http://stackoverflow.com/comment/85368685
has text: If `select count(*) from table` returns 100k, then you can be sure that only 100k rows are in the table (or at least, only 100k rows are visible to your current transaction). The 'problem' is not with Python or pyodbc, but squarely within the database.
type: QuestionComment
comment on: http://stackoverflow.com/q/49181433
score: 6
type: Comment

http://stackoverflow.com/comment/85354214
score: 2
comment on: http://stackoverflow.com/q/49174419
has text: Are any of the arguments to `worker.apply_async()` perhaps large data structures?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49205187
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49204735
score: 1
has body: Would it be easier to convert each of these individually and then combine them into one csv? Yes, it certainly would For example, this will put each JSON object/array (whatever is loaded from the file) onto its own line of a single CSV. import json, csv from glob import glob with open('out.csv', 'w') as f: for fname in glob("*.json"): # Reads all json from the current directory with open(fname) as j: f.write(str(json.load(j))) f.write('\n') Use glob pattern **/*.json to find all json files in nested folders Not really clear what for row in ... was doing for your data since you don't have an array. Unless you wanted each JSON key to be a CSV column?

http://stackoverflow.com/q/49185800
has answer: http://stackoverflow.com/a/49185862
upvote count: 1
favorite count: 0
has body: I am trying to implement a simple solitaire game in which the goal is to shift rows and columns of varying colors until they form a specific pattern. I am trying to represent the configuration of my game board using a 2d list: board = [['W', 'W', 'W', 'W'], ['W', 'W', 'W', 'W'], ['B', 'B', 'B', 'B'], ['B', 'B', 'B', 'B']] Let's suppose that we have the following goal board: goal = [['W', 'B', 'B', 'W'], ['W', 'W', 'W', 'W'], ['W', 'W', 'B', 'B'], ['B', 'B', 'B', 'B']] For a given move you may only shift the elements of one column up or down, or one row right or left. Elements that fall off the end of the board are cycled back to the opposite side of the column or row being shifted. How might I implement functions to achieve this functionality? The implementation for the shifting of elements along a row seems fairly straightforward to me, for example: def shift_left(board, row_num, num_tiles): for i in range(0, num_tiles): elem = board.pop(0) board.append(elem) Am I on the right track? How might I approach implementing the functions for shifting elements along a column?
type: Question
accepted answer: http://stackoverflow.com/a/49186055
possible better answer: http://stackoverflow.com/a/49185862
has answer: http://stackoverflow.com/a/49186055
tagged with: python
type: AnsweredQuestion
answer count: 2
has title: Sliding columns and rows in a 2D List
score: 1
downvote count: 0

http://stackoverflow.com/q/49237365
type: Question
has body: I have a difficulty in searching a string in a file that has multiple special characters and replace the whole line with some text having special characters. search string in a file a.bb.cc[hk].ccm[*].nib[*].gion[*].der[*].sam[*].ant[ck].sant[*].tags[*].rmp replace with dde.be.cc[hk].com[*].nib[*].gion[*].der[*].sam[*].ant[ck].sant[*].tags[*].rmp=200 tried using linux sed but that needs to escape all these special characters and I do not want to do. These special characters might change for other strings. perl -e "s/$to_replace/$replace_with/g" -pi /tmp/l1 sed -i -e "s/'$to_replace'/'$replace_with'/g" /tmp/l1 both these failed as they expecting escape characters. Any help here will be appreciated. Thanks
has comment: http://stackoverflow.com/comment/85479736
downvote count: 3
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85500430
tagged with: replace
tagged with: find
tagged with: sed
upvote count: 2
tagged with: perl
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49248696
has title: sed - find a string with special characters and replace in a file
favorite count: 0

http://stackoverflow.com/q/49261746
score: 1
has answer: http://stackoverflow.com/a/49261939
tagged with: python
type: Question
has body: I don't know how to get desired capabilities I've set with Appium Python client. What I need specifically to know is which platform is set, is it iOS or Android? I have Appium driver like this. self.driver = webdriver.Remote(config['server_url'], config['device_config']) server_url = http://localhost:4723/wd/hub device_config = samsung_galaxy_nexus_6_0 'samsung_galaxy_nexus_6_0': { 'app': '/Users/majdukovic/Documents/no_root_ux.apk', 'platformName': 'Android', 'platformVersion': '6.0', 'deviceName': 'Galaxy Nexus 6.0', 'avd': 'Galaxy_Nexus_6.0', I need something like this self.driver.get_capabilities('platformName') Thanks.
answer count: 2
has answer: http://stackoverflow.com/a/49296673
downvote count: 0
tagged with: automation
tagged with: appium
upvote count: 1
type: UnansweredQuestion
tagged with: selenium
tagged with: python-appium
favorite count: 0
has title: Get desired capabilities with Python

http://stackoverflow.com/comment/85506868
type: QuestionComment
type: Comment
score: 0
has text: For a background of docker check out their [tutorial](https://docs.docker.com/get-started/)
comment on: http://stackoverflow.com/q/49250401

http://stackoverflow.com/q/49133915
tagged with: dbpedia
score: 2
upvote count: 3
answer count: 1
has body: I wrote a python script that goes through a list of URI's and runs the following query on each of them: query = "SELECT ?subject WHERE {&lt;http://dbpedia.org" + uri + "&gt; dct:subject ?subject.}" This works when the given URI is correct, such as /resource/Android_TV. But in my list of URI's I also have other URI's such as /resource/Sheldon_J._Plankton. When I run this query it doesn't find anything, but if I go to the corresponding DBPedia page http://dbpedia.org/resource/Sheldon_J._Plankton it changes to http://dbpedia.org/page/Plankton_(character). So apparantly the correct URI for this page would be: resource/Plankton_(character). Is it possible to write the query in such a way that it changes the URI to be correct? This list of URI's is very, very long so I can't manually check and fix them unfortunately.
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49135478
has comment: http://stackoverflow.com/comment/85275673
has answer: http://stackoverflow.com/a/49135478
tagged with: python
tagged with: sparql
type: AnsweredQuestion
has title: Python sparql query on "wrong" URI's

http://stackoverflow.com/a/49214402
answers question: http://stackoverflow.com/q/49214210
has body: " ".join() the args first, then split by --. import sys args = " ".join(sys.argv) # join by spaces args = [a.strip() for a in args.split("--")] # split by --, remove any extra spaces print(args) print("\n".join(args)) Output: $ python plot.py --w --Develop origin plot --+3.5 ['plot.py', 'w', 'Develop origin plot', '+3.5'] plot.py w Develop origin plot +3.5
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85433320
score: 1
accepted answer of: http://stackoverflow.com/q/49214210
type: Answer

http://stackoverflow.com/comment/85541025
comment on: http://stackoverflow.com/q/49268864
type: Comment
type: QuestionComment
has text: Did you try anything?
score: 2

http://stackoverflow.com/comment/85271229
has text: Also, it seems this question might be better asked on superuser or serverfault. stackoverflow is oriented towards software development questions.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49133198

http://stackoverflow.com/comment/85316814
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49155839
has text: Or try `webdriver.Chrome(executable_path="/usr/bin/chromedriver")`
score: 1

http://stackoverflow.com/q/49200369
score: 1
has comment: http://stackoverflow.com/comment/85406271
tagged with: jupyter-notebook
type: Question
tagged with: jupyter-lab
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49370656
upvote count: 1
has comment: http://stackoverflow.com/comment/85406352
favorite count: 0
has title: jupyter lab importing modules
has body: I am using jupyter lab on linux, and I have started it various working directories, including /, but I am having problems importing a module I installed with pip. Here is what I did: pip install primer3-py Then run ipython Within ipython run import primer3 works as expected where primer3.calcTm('GTAAAACGACGGCCAGT') returns 49.16808228911765 However, if I run jupyter lab Open a console and run import primer3 I now get an import error: --------------------------------------------------------------------------- ImportError Traceback (most recent call last) &lt;ipython-input-1-1493f16bb490&gt; in &lt;module&gt;() ----&gt; 1 import primer3 ImportError: No module named primer3 Am I doing something wrong here?
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85406240

numpy
tags question: http://stackoverflow.com/q/49146201
tags question: http://stackoverflow.com/q/49155699
tags question: http://stackoverflow.com/q/49135308
tags question: http://stackoverflow.com/q/49167574
tags question: http://stackoverflow.com/q/49239916
tags question: http://stackoverflow.com/q/49245996
tags question: http://stackoverflow.com/q/49150187
tags question: http://stackoverflow.com/q/49207275
tags question: http://stackoverflow.com/q/49226605
tags question: http://stackoverflow.com/q/49140589
tags question: http://stackoverflow.com/q/49232854
tags question: http://stackoverflow.com/q/49164134
tags question: http://stackoverflow.com/q/49247016
tags question: http://stackoverflow.com/q/49183439
tags question: http://stackoverflow.com/q/49158789
tags question: http://stackoverflow.com/q/49127947
tags question: http://stackoverflow.com/q/49180601
tags question: http://stackoverflow.com/q/49219152
tags question: http://stackoverflow.com/q/49150748
tags question: http://stackoverflow.com/q/49199578
tags question: http://stackoverflow.com/q/49228532
tags question: http://stackoverflow.com/q/49157514
tags question: http://stackoverflow.com/q/49181070
tags question: http://stackoverflow.com/q/49141359
tags question: http://stackoverflow.com/q/49193766
tags question: http://stackoverflow.com/q/49158145
tags question: http://stackoverflow.com/q/49196195
tags question: http://stackoverflow.com/q/49213155
tags question: http://stackoverflow.com/q/49186350
tags question: http://stackoverflow.com/q/49188198
tags question: http://stackoverflow.com/q/49133702
tags question: http://stackoverflow.com/q/49235611
tags question: http://stackoverflow.com/q/49209338
tags question: http://stackoverflow.com/q/49124610
tags question: http://stackoverflow.com/q/49162578
tags question: http://stackoverflow.com/q/49245739
tags question: http://stackoverflow.com/q/49250148
tags question: http://stackoverflow.com/q/49201431
tags question: http://stackoverflow.com/q/49130551
tags question: http://stackoverflow.com/q/49176543
tags question: http://stackoverflow.com/q/49151170
tags question: http://stackoverflow.com/q/49233403
tags question: http://stackoverflow.com/q/49259210
tags question: http://stackoverflow.com/q/49151547
tags question: http://stackoverflow.com/q/49176042
tags question: http://stackoverflow.com/q/49177169
tags question: http://stackoverflow.com/q/49211949
tags question: http://stackoverflow.com/q/49266989
tags question: http://stackoverflow.com/q/49228144
tags question: http://stackoverflow.com/q/49245963
tags question: http://stackoverflow.com/q/49121764
tags question: http://stackoverflow.com/q/49134252
tags question: http://stackoverflow.com/q/49199818
tags question: http://stackoverflow.com/q/49137777
tags question: http://stackoverflow.com/q/49157566
tags question: http://stackoverflow.com/q/49162498
tags question: http://stackoverflow.com/q/49130679
tags question: http://stackoverflow.com/q/49192051
tags question: http://stackoverflow.com/q/49205075
tags question: http://stackoverflow.com/q/49172608
tags question: http://stackoverflow.com/q/49141965
tags question: http://stackoverflow.com/q/49204115
tags question: http://stackoverflow.com/q/49201063
tags question: http://stackoverflow.com/q/49135539
tags question: http://stackoverflow.com/q/49209826
tags question: http://stackoverflow.com/q/49175855
tags question: http://stackoverflow.com/q/49145852
tags question: http://stackoverflow.com/q/49204453
tags question: http://stackoverflow.com/q/49246127
tags question: http://stackoverflow.com/q/49268410
tags question: http://stackoverflow.com/q/49197366
tags question: http://stackoverflow.com/q/49235020
type: Tag
tags question: http://stackoverflow.com/q/49274345
tags question: http://stackoverflow.com/q/49268116
tags question: http://stackoverflow.com/q/49200272
tags question: http://stackoverflow.com/q/49258553
tags question: http://stackoverflow.com/q/49138716
tags question: http://stackoverflow.com/q/49161663
tags question: http://stackoverflow.com/q/49215273

http://stackoverflow.com/q/49226358
has title: Predicting test data with fewer features than training set
has comment: http://stackoverflow.com/comment/85457991
has comment: http://stackoverflow.com/comment/85460617
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49353818
answer count: 3
score: 1
has comment: http://stackoverflow.com/comment/85469862
downvote count: 0
upvote count: 1
tagged with: scikit-learn
has body: I am using the KNeighborsClassifier() library from Scikit-Learn to predict football outcomes using team names. My training data has 18 statistics of a match, such as goals and number of fouls, and for my test set I can only use 2 team names. The problem is the number of training features must match the number of test features or else I get ValueError: query data dimension must match training data dimension How can I overcome this, while keeping my training set with past statistics and test set with only the team names? Code df = pd.read_csv('2013p.csv') # Training data dftest= pd.read_csv('2014p.csv') # Test Data X = np.array(df.drop(['FTR','BbAvH','BbAvD','BbAvA'],1)) #features y = np.array(df['FTR']) #labels classes Xtest = np.array(dftest.drop(['FTHG','FTAG','FTR','HTHG','HTAG','HS','AS','HST','AST','HF','AF','HC','AC','HY','AY','HR','AR','BbAvH','BbAvD','BbAvA'],1))#features ytest = np.array(dftest['FTR']) #labels classes clf= neighbors.KNeighborsClassifier(n_neighbors =19)#New Classifier clf.fit(X, y)#Fit on train data results = clf.predict(Xtest) Data HomeTeam, AwayTeam, FTHG, FTAG, FTR, HTHG, HTAG, HS, AS, HST, AST, HF, AF 401, 301, 2 , 3 , -1 , 1 , 1 , 5 , 7 , 3 , 5 , 2 , 4
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49233780
possible better answer: http://stackoverflow.com/a/49226437
has answer: http://stackoverflow.com/a/49233780
has answer: http://stackoverflow.com/a/49226437
tagged with: python

http://stackoverflow.com/q/49255248
answer count: 4
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49255351
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49261136
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49256897
tagged with: pandas
upvote count: 3
has body: Im trying to generate a numpy array of minutes from 9:30 to 16:00. (6.5 hours*60 minutes=390 elements) Is there something similar to: import pandas as pd pd.date_range("09:30", "16:00", freq="1min") Of course after it to convert to numpy is easy...
score: 3
has title: Generating a list of hour:minute in Python
has answer: http://stackoverflow.com/a/49255416

http://stackoverflow.com/comment/85428491
comment on: http://stackoverflow.com/q/49208617
type: QuestionComment
score: 0
has text: @JakubBartczuk, Having less iterations made no difference in predictions. I get same lable all the time as before. Meanwhile i tried to make data balanced by training with fit() instead of partial_fit and pass the coef of 1st model to 2nd model. But i was not succesful there too. Please have a look here: https://stackoverflow.com/questions/49133188/how-to-initialize-coef-init-and-intercept-init-for-a-new-training-model.
type: Comment

http://stackoverflow.com/comment/85602398
score: 0
has text: @ArtemisFowl you are misusing exec. Python functions always return `None` if they do not return something implicitly. Exec does not return anything. So it returns None. Read [exec](https://docs.python.org/3/library/functions.html#exec) - the first paragraf, carefully.
type: Comment
comment on: http://stackoverflow.com/a/49261504
type: AnswerComment

http://stackoverflow.com/a/49165260
type: Answer
answers question: http://stackoverflow.com/q/49165004
score: 0
has body: Maybe you have tried to use pip3 which located in your real python environment. But actually your django has been installed in virtual environment. From your example, maybe you should check the python interpreter something like this: venv/bin/python3.4. By the way, before you use django-admin command, you should make sure you have already in virtual env. For example, if you are in virtual env, it will be someting like this: (venv)Mac:myproject michael$ pip install jinja2 ... Successfully installed jinja2-2.7.3 markupsafe-0.23 (venv)Mac:myproject michael$ python myapp.py ... If you want to get into the real python environment: (venv)Mac:myproject michael$ deactivate Mac:myproject michael$ So, you should make sure you have been in the same environment with both packages and interpreter.

http://stackoverflow.com/comment/136118441
has text: I changed this in the setting. Also added `"cwd": "${fileDirname}"` in the settings.json as per some other answer here. But still when I open any python file in vs, it starts with the open directory folder path instead of actual file path. So let's say I have opened `.\documents\python\practice\ ` folder and the file that I am working is in `.\documents\python\practice\project 1\ ` folder along with other files I am opening, still vs code looks for those files in the practice folder instead of project 1 folder. How to solve this?
type: Comment
comment on: http://stackoverflow.com/a/49275867
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85327667
type: Comment
type: AnswerComment
score: 1
has text: @user3053216 yw~ :-) happy coding
comment on: http://stackoverflow.com/a/49161030

http://stackoverflow.com/a/49236326
accepted answer of: http://stackoverflow.com/q/49236166
has comment: http://stackoverflow.com/comment/85475724
answers question: http://stackoverflow.com/q/49236166
has body: You can use the FunctionTransformer class. If your goal is to have a transformer that takes a matrix of indexes and outputs a 3d tensor with word vectors, then this should suffice: # this assumes you're using numpy ndarrays word_vecs_matrix = get_wv_matrix() # pseudo-code def transform(x): return word_vecs_matrix[x] transformer = FunctionTransformer(transform) Be aware that, unlike keras, the word vector will not be fine tuned using some kind of gradient descent
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/85475736
type: Answer

http://stackoverflow.com/q/49144256
has answer: http://stackoverflow.com/a/49239707
score: 5
type: UnansweredQuestion
upvote count: 5
has title: convert list to bytestring for Google pub/sub
tagged with: python
has body: I am running into an issue while publishing messages to google cloud pub/sub service from a python client. I have rest based public API which returns JSON data. The returned data is in dictionary form within in a list. I have extracted the values from the dictionary into a list and using bytes() to convert to the bytestring however it is still throwing the exception below. ['EB', 'Pulaski', '2018-03-06 21:50:18.0', '0.5', '41.7930671862', '41.793140551', '-87.7136071496', 'W', 'Central Park', '-1', '1', '-87.7231602513', '55th'] response = requests.get("https://data.cityofchicago.org/resource/8v9j-bter.json") traffic = response.json() result_list = [] for d in traffic: result_list.append([v for k, v in d.items()]) for x in result_list: print(x) publisher.publish(topic_path, data = bytes(x))
tagged with: google-cloud-platform
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85294506
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85294058

http://stackoverflow.com/comment/85487164
comment on: http://stackoverflow.com/a/49241570
type: Comment
score: 0
type: AnswerComment
has text: @user9443097 I would assume that is the idea. You could probably use python's `uuid` library to generate the random prefixes.

http://stackoverflow.com/a/49265498
answers question: http://stackoverflow.com/q/49265461
upvote count: 3
downvote count: 0
score: 3
has body: You have to join the contents of zoo as well: zoo=('python','elephant','penguin') new_zoo=('monkey','camel',','.join(zoo)) final_zoo = ','.join(new_zoo) Output: 'monkey,camel,python,elephant,penguin' However, you can also iterate over the contents of new_zoo and apply str.join: zoo=('python','elephant','penguin') new_zoo=('monkey','camel',zoo) final_zoo = ','.join([i if not isinstance(i, tuple) else ','.join(i) for i in new_zoo]) Output: 'monkey,camel,python,elephant,penguin'
type: Answer

http://stackoverflow.com/comment/85540534
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49267999
type: Comment
has text: Possible duplicate of [Error when opening xml file in python 3 with sublime text 3](https://stackoverflow.com/questions/36974461/error-when-opening-xml-file-in-python-3-with-sublime-text-3)

http://stackoverflow.com/comment/85462386
has text: 1- Try a CGI script without aplication 2-Check file permissions 3-Check the application to be triggered(python, what is python ?) 4- The ISS cannot follow the system path, it requires special authorization to get out of the given directories. 5-Main broadcast service address forwarding (ISS processed address block >> CGI Script) No idea which is missed.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49189246
type: QuestionComment

http://stackoverflow.com/a/49138092
has comment: http://stackoverflow.com/comment/85288886
type: AcceptedAnswer
has body: Its a little unclear to me what exactly you are doing, but I was able to adapt your code and get it to work. First of all, T[0] is a float (.5) and won't work for your iterator. I am assuming you wanted to loop over the length of each variable to make b 100x3, in which case you should use range(len(b[0])), or use a variable to define the length of b[0], and use that variable to define your iterator as well. Also, in the last line you put j in brackets, making it a list, which is unnecessary if you want it to multiply as a number. Did you want the iterator (0,1,2) to multiply S[i] or the specific value in T? I wrote the former below, but if you want the latter change j to T[j] The following code runs without error for me import numpy as np S = np.linspace(0,37,100) T = np.array([5.,25.,30.]) delta = 25. - T f = 1575e6 tt = T.reshape(3,1) beta = S*tt length_of_b_0=100 b = np.zeros(np.shape(beta)).reshape(length_of_b_0,3) #Calculate and put into a 3x100 or 100x3 array for i in range(length_of_b_0): for j in range(len(T)): b[i,j]= 1.00 + 2.282e-5*S[i]*j - 7.638e-4*S[i] - 7.76e-6*S[i]**2 + 1.105e-8*S[i]**3
has comment: http://stackoverflow.com/comment/85534548
accepted answer of: http://stackoverflow.com/q/49137698
type: Answer
answers question: http://stackoverflow.com/q/49137698
has comment: http://stackoverflow.com/comment/85536473
score: 0

http://stackoverflow.com/q/49141478
has title: How do I handle errors
has body: The Stripe API has an example of how to switch a customer's subscription: https://stripe.com/docs/subscriptions/upgrading-downgrading # Set your secret key: remember to change this to your live secret key in production # See your keys here: https://dashboard.stripe.com/account/apikeys stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2" subscription = stripe.Subscription.retrieve('sub_49ty4767H20z6a') stripe.Subscription.modify('sub_49ty4767H20z6a', items=[{ 'id': subscription['items']['data'][0].id, 'plan': 'plan_CBb6IXqvTLXp3f', }] ) How would I write an error-handling block for this code in cases where there's a problem charging the customer's credit card?
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/49142002
has comment: http://stackoverflow.com/comment/85289169
has comment: http://stackoverflow.com/comment/85288630
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
tagged with: stripe-payments
favorite count: 0
score: 1

http://stackoverflow.com/q/49179006
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has body: Description I have a categorical dataframe which contains nan values at few places. I am trying to perform data cleaning in which I back fill the nan values for 1 day before the label ( error). My dataset look like: dataframe Date Error Type 1 Error Type 2 Error Type 3 2010-03-07 13:12:25 NaN NaN NaN 2010-03-08 12:12:25 NaN G35 NaN 2010-03-09 15:12:25 P5 NaN NaN 2010-03-10 08:12:25 P5 NaN NaN 2010-03-11 12:05:25 NaN NaN F2 2010-06-13 11:06:25 P1 G1 F1 The dataframe I hope to get Date Error Type 1 Error Type 2 Error Type 3 2010-03-07 10:12:25 NaN G35_1 NaN 2010-03-08 12:12:25 P5_1 G35_1 NaN 2010-03-09 15:12:25 P5_1 NaN NaN 2010-03-10 08:12:25 P5 NaN F2_1 2010-03-11 12:05:25 NaN NaN F2_1 2010-06-13 11:06:25 P1 G1 F1 I found similar question back fill missing data with a label for a window of a time but didn't have any answer for nonuniform timestamp. My main dataset have over 100 columns too. I have no idea how to solve this. Can anyone give me some hints? Thanks a lot!!
favorite count: 0
linked to: http://stackoverflow.com/q/49158268
type: Question
tagged with: fillna
tagged with: pandas
has comment: http://stackoverflow.com/comment/85367255
score: 1
tagged with: group-by
has comment: http://stackoverflow.com/comment/85367887
tagged with: dataframe
tagged with: python
has title: Backfill data a dataframe with nonuniform timestamp in pandas
has comment: http://stackoverflow.com/comment/85366745

http://stackoverflow.com/a/49137177
score: 0
type: Answer
has body: &gt;&gt;&gt; for line in 'hello': ... print(line) ... h e l l o You are iterating over characters. Calling the variable line does not make the interpreter iterate over lines. You have to splitlines() and iterate over the resulting list: &gt;&gt;&gt; for line in 'hello\nbye'.splitlines(): ... print(line) ... hello bye
accepted answer of: http://stackoverflow.com/q/49137087
answers question: http://stackoverflow.com/q/49137087
type: AcceptedAnswer

http://stackoverflow.com/comment/85543991
has text: maybe you have a variable which is string. remove that variable or use one hot encoding.
type: Comment
comment on: http://stackoverflow.com/q/49247530
score: 0
type: QuestionComment

http://stackoverflow.com/a/49157429
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49154901
has body: I have figured out how to read the intended days of data without using the wildcard, but by writing a python function. The idea is to create an array of all the read operations and then to flatten the array and use that as your input to your pipeline. def read_files(pipeline, intended_day): collections = [] previous_day = (datetime.strptime(intended_day, '%Y%m%d') - timedelta(days=1)).strftime('%Y%m%d') days = [intended_day, previous_day] path = "gs://sensors/{}/&lt;hash&gt;/*" for day in days: try: file_name = path.format(day) collection = pipeline | ('Read Past for %s' % day) &gt;&gt; beam.io.ReadFromText(file_name) collections.append(collection) except IOError: logging.error("Failed to read for day %s" % day) return collections Then call your function in your pipeline like this: p = beam.Pipeline(runner=runner, argv=argv) intended_day = "20170810" pcollections = read_files(p, intended_day) result = ((pcollections | "Flatten sensor" &gt;&gt; beam.Flatten()) | ..... )
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49154901

http://stackoverflow.com/comment/85453781
comment on: http://stackoverflow.com/q/49224992
type: Comment
type: QuestionComment
has text: Your description is a bit lacking: If you don't have at least three elements, you can not extract three elements, so that part of your description is redundant. A precise description is necessary to define an algorithm that does the right thing though.
score: 0

http://stackoverflow.com/q/49213200
has body: I am getting a response from the REST service. This response is an array of JSON objects. Using this array, I am trying to display the individual property of each JSON object on HTML page using Jinja2 template framework. But it is showing the empty string on the browser. The JSON response which I am getting from the service is { u'messages': [ {u'text': u'hello', u'author_id': 1, u'pub_date': 1518506778, u'message_id': 1}, {u'text': u'hell', u'author_id': 2, u'pub_date': 1518420378, u'message_id': 2}, ] } Not sure what is the u character before every string. The rest service is developed in Flask. Below is the python code: r = requests.get('http://127.0.0.1:3000/api/v1.0/messages') @app.route('/messages') def public_timeline(): """Displays the latest messages of all users.""" python_message = json.loads(r.text) print("******") print(python_message) return render_template('messages.html', messages = python_message) And the template code is : {% if messages %} {% for message in messages %} {{message['text']}} {% endfor %} {% else %} Messages not available :( {% endif %} I think the problem is due to the unnecessary u character before each string. How can I resolve problem of blank output on the browser screen? The output in the browser is: ....
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85431023
has comment: http://stackoverflow.com/comment/85431048
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85431013
has comment: http://stackoverflow.com/comment/85431227
answer count: 1
tagged with: jinja2
has answer: http://stackoverflow.com/a/49213416
linked to: http://stackoverflow.com/q/13940272
has comment: http://stackoverflow.com/comment/85431151
has title: Jinja2 template rendering getting empty string
has comment: http://stackoverflow.com/comment/85431060
type: Question
accepted answer: http://stackoverflow.com/a/49213416
tagged with: python
tagged with: flask

http://stackoverflow.com/a/49236443
answers question: http://stackoverflow.com/q/49181526
has body: I'm not a Linux expert, but this looks like Red Hat 6 (which had python 2.6 as default) [1]. The 4.4 is the version of GCC. When you've got python 2.6 back in place and still need Python 2.7, then install the latter via the Software Collections channel - this will install 2.7 alongside the 2.6 version and not replace it to mess up the OS. [1] How to confirm RedHat Enterprise Linux version? [2]https://developers.redhat.com/products/softwarecollections/hello-world/#fndtn-python
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85478447
has comment: http://stackoverflow.com/comment/85659355
has comment: http://stackoverflow.com/comment/85731324

http://stackoverflow.com/a/49219568
score: 0
has body: The solution to splitting the line is split - however you can change the code to do this a different way - though this might be more confusing if you're not used to comprehensions: a = 'aa ao oa aaaooo aooqq aoooq' # Create a dictionary where the key is the string, value is the number of 'o's counts = {k: k.count('o')for k in a.split()} # Calculate the highest count, and return a list of all items whose value equals the count: [k for m in [max(counts.values())] for k, v in counts.items() if v == m] # ['aaaooo', 'aoooq']
answers question: http://stackoverflow.com/q/49219328
type: Answer

http://stackoverflow.com/q/49168556
has title: Extract CSS Selector for an element with Selenium
has answer: http://stackoverflow.com/a/49168744
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/49169723
answer count: 2
has comment: http://stackoverflow.com/comment/85358439
upvote count: 2
has comment: http://stackoverflow.com/comment/85358647
has comment: http://stackoverflow.com/comment/85356944
downvote count: 0
tagged with: selenium
tagged with: web-scraping
favorite count: 0
has body: For my project I need to extract the CSS Selectors for a given element that I will find through parsing. What I do is navigate to a page with selenium and then with python-beautiful soup I parse the page and find if there are any elements that I need the CSS Selector of. For example I may try to find any input tags with id "print". soup.find_all('input', {'id': 'print')}) If I manage to find such an element I want to fetch its extract it's CSS Selector, something like "input#print". I don't just find using id's but also a combination of classes and regular expressions. Is there any way to achieve this?
type: Question
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/85358633
has answer: http://stackoverflow.com/a/49169723
has comment: http://stackoverflow.com/comment/85357931
has comment: http://stackoverflow.com/comment/85359728
tagged with: python
has comment: http://stackoverflow.com/comment/85357234
accepted answer: http://stackoverflow.com/a/49168744
tagged with: css

http://stackoverflow.com/comment/85396088
has text: @Giladbi I think it should be possible to generalise with a list comprehension... slice over [i::5] for i in range(1,5), if that makes sense.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49190302

http://stackoverflow.com/comment/85314491
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49154375
has text: @jpp, I have modified my question that includes a transposed dataframe. Thanks.

http://stackoverflow.com/a/49200302
has body: Maybe just: l = [2**i for i in range(n)]
score: 8
downvote count: 0
upvote count: 8
type: Answer
answers question: http://stackoverflow.com/q/49200272

http://stackoverflow.com/q/49229570
tagged with: mysql
type: Question
tagged with: phpmyadmin
tagged with: database
tagged with: python
has body: I have created a touch screen buttons consist of "start" "Request material" "Receive material" "Lap" "Emergency" "Finish" Now i am trying to store integers as numbers of finished products (1,2,3,etc) and lap times when an operator presses the lap button (similar to stopwatch). Basically, there are only two columns. The result shows in the terminal after i ran the program and there was no error, but it didn't show in the mysql database and i am using phpmyadmin. Here is my code can be seen below: from Tkinter import * from pymodbus.client.sync import ModbusTcpClient as ModbusClient import time import datetime import RPi.GPIO as GPIO import MySQLdb GPIO.setmode(GPIO.BCM) GPIO.setwarnings(0) #-------------------------------------------------------GPIO GPIO.setup(21, GPIO.OUT)#red led GPIO.setup(20, GPIO.OUT)#yellow led GPIO.setup(16, GPIO.OUT)#green led GPIO.output(21, GPIO.HIGH) GPIO.output(20, GPIO.HIGH) GPIO.output(16, GPIO.HIGH) #-------------------------------------------------------GPIO class Screen(Frame): def __init__(self, master): Frame.__init__(self, master) #-------------------------------------------------------Main self.lbttn_clicks = 0 self.start_button() self.material_button() self.receive_button() self.emergency_button() self.lap_button() self.finish_button() self.minutes = 0 self.seconds = 0 #-------------------------------------------------------Modbus Var self.LedRed_State = False self.LedYellow_State = False self.LedGreen_State = False self.db = MySQLdb.connect("localhost","root","raspberry","DB_ASSY") self.sql = "INSERT INTO Table_Assembly (Finished Product, Lap Time) VALUES (%s, %s)" self.c= self.db.cursor() self.client = ModbusClient('192.168.4.166') self.client.connect() print "ModbusClient connected..." #-------------------------------------------------------Modbus Var self.time_start = time.time() self.pack(fill=BOTH, expand=1) #-------------------------------------------------------Main #------------------------------------------------------…
score: 0
tagged with: raspberry-pi
has title: python code does not show data in mysql database
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49229832
answer count: 1

http://stackoverflow.com/a/49173785
accepted answer of: http://stackoverflow.com/q/49156749
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49156749
has body: So (for the time being) I went about manually reconciling them through a few steps. First I use my location data and get a list of all the ID's like this: location_ids = [s['location_id'] for s in location_data] Then I get the Location objects for those ID's: location_items = Location.objects.filter( id__in=location_ids ) Then I make a small dictionary with the ID and the name: location_names = [ {'location_id':s.id, 'location_name': s.name} for s in location_items ] Then I chain the two lists of dictionaries together and and create a new one from them based on the 'location_id' tying each dictionary together. additional_location_data = defaultdict(dict) for d in chain(past_enrollments, location_names): additional_location_data[d['location_id']].update(d) This worked to reconcile the location_id with the name of the Location object and put the name in a dictionary (inside of a list) in the appropriate spots. It's probably fairly 'ugly' for now - but I'll worry about cleaning it up later.
type: Answer
score: 0

http://stackoverflow.com/comment/85440240
comment on: http://stackoverflow.com/q/49218215
type: QuestionComment
type: Comment
has text: Do not assign to default value mutable objects.
score: 1

http://stackoverflow.com/comment/85504529
comment on: http://stackoverflow.com/q/49250239
score: 1
has text: @MadPhysicist If you are ok with a non-contiguous result you could actually do `X.view('S1').reshape(X.size, -1, 4)[..., 0]`
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49241225
score: 4
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49240133
answers question: http://stackoverflow.com/q/49240133
type: Answer
has body: You should be able to use the formula: (1 + r).cumprod() to get a cumulative growth factor. Example: &gt;&gt;&gt; data 0 1 0 548625 525980 1 546144 525553 2 541219 526281 3 536190 524998 &gt;&gt;&gt; pctchg = data.pct_change() &gt;&gt;&gt; init = data.iloc[0] # may want to use `data.iloc[0].copy()` &gt;&gt;&gt; res = (1 + pctchg).cumprod() * init &gt;&gt;&gt; res.iloc[0] = init &gt;&gt;&gt; res 0 1 0 548625.0 525980.0 1 546144.0 525553.0 2 541219.0 526281.0 3 536190.0 524998.0 To confirm you worked backwards into the correct absolute figures: &gt;&gt;&gt; np.allclose(data, res) True
upvote count: 4

http://stackoverflow.com/a/49275665
upvote count: 2
has body: As already answered in a similar question, the implementation of the intersection of two sets is analogous to: def intersect(a, b): if len(a) &gt; len(b): a, b = b, a c = set() for x in a: if x in b: c.add(x) return c For multiple sets it is implemented as a chain of pairwise intersections roughly equivalent to: def intersect_multi(a, *others): result = a.copy() for other in others: newresult = result.intersect(other) if not newresult: return set() result = newresult The average complexity is probably not given for this because it depends on whether or not this returns before going through all others, due to the intersection being empty. It can therefore be anywhere between O(k), with k being the length of the first set in others and the worst case. The worst case complexity for this is then (N-1) * max(O(set_intersection)). O(set_intersection) is usually O(min(k, l)) as you noted, but O(max(k, l)) if the second is not a set. I guess this is included here, so it is basically determined by the longest set. The worst case for O(set_intersection) stated in the wiki is very unlikely to occur, as noted on this post by Raymond Hettinger. Apparently it only occurs in case where you have a hash collisions every time, so if x in b becomes O(n) (its worst-case complexity). It seems like this worst-case is not included in the worst-case complexity of multiple set intersections (maybe not because of how highly unlikely it is to have a hash collision for all members of all sets?).
accepted answer of: http://stackoverflow.com/q/49275383
has comment: http://stackoverflow.com/comment/85556113
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49275383
has comment: http://stackoverflow.com/comment/85554891
has comment: http://stackoverflow.com/comment/85553914
has comment: http://stackoverflow.com/comment/85553966
type: Answer
has comment: http://stackoverflow.com/comment/85553930
score: 2
has comment: http://stackoverflow.com/comment/85555552

http://stackoverflow.com/comment/85390313
has text: can you please tell me the error here?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49192418

http://stackoverflow.com/a/49263358
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49263249
downvote count: 0
has comment: http://stackoverflow.com/comment/85531444
has comment: http://stackoverflow.com/comment/85530395
has comment: http://stackoverflow.com/comment/85534791
has comment: http://stackoverflow.com/comment/85531525
has body: Personally I would require one input format for good measure. As it stands, you have no choice but to handle each case differently, or at least each group of cases. With what you've done so far, you seem to be up to the task. To handle both of the cases with more than one argument, the easy way is to strip away any commas that might or might not be there: args = [arg.strip(',') for arg in sys.argv[1:]]
type: Answer

sockets
tags question: http://stackoverflow.com/q/49264265
tags question: http://stackoverflow.com/q/49222155
tags question: http://stackoverflow.com/q/49261856
tags question: http://stackoverflow.com/q/49218936
tags question: http://stackoverflow.com/q/49170605
tags question: http://stackoverflow.com/q/49178921
tags question: http://stackoverflow.com/q/49265329
tags question: http://stackoverflow.com/q/49252946
tags question: http://stackoverflow.com/q/49268568
tags question: http://stackoverflow.com/q/49227324
tag name: sockets
tags question: http://stackoverflow.com/q/49208060
tags question: http://stackoverflow.com/q/49221986
tags question: http://stackoverflow.com/q/49162784
tags question: http://stackoverflow.com/q/49185552
tags question: http://stackoverflow.com/q/49248067
tags question: http://stackoverflow.com/q/49205051
tags question: http://stackoverflow.com/q/49187150
tags question: http://stackoverflow.com/q/49268934
type: Tag
tags question: http://stackoverflow.com/q/49216875

http://stackoverflow.com/comment/85324774
has text: @Amir You want a shared counter among all the processes (so shared memory but not threading)? This is important. Check [https://docs.python.org/2/library/multiprocessing.html] and search for shared memory - looks like you want to use [`multiprocessing.Value`](https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Value) as your global counter.
type: AnswerComment
comment on: http://stackoverflow.com/a/49150181
score: 0
type: Comment

http://stackoverflow.com/comment/85375934
has text: It only has 3, 'year', 'title_field', and 'value'
type: AnswerComment
comment on: http://stackoverflow.com/a/49184946
score: 0
type: Comment

http://stackoverflow.com/comment/85272245
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49133702
has text: Is there any other way to load 1 million data other than using numpy?
type: Comment

http://stackoverflow.com/q/49186303
tagged with: tensorflow
tagged with: tensorflow-datasets
possible better answer: http://stackoverflow.com/a/49188235
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/49053569
linked to: http://stackoverflow.com/q/46444018
score: 0
accepted answer: http://stackoverflow.com/a/49263933
has title: Tensorflow: Batching whole dataset (MNIST Tutorial)
has answer: http://stackoverflow.com/a/49263933
has body: Following this tutorial: https://www.tensorflow.org/versions/r1.3/get_started/mnist/pros I wanted to solve a classification problem with labeled images by myself. Since I'm not using the MNIST database, I spent days creating my own dataset inside tensorflow. It looks like this: #variables batch_size = 50 dimension = 784 stages = 10 #step 1 read Dataset filenames = tf.constant(filenamesList) labels = tf.constant(labelsList) #step 2 create Dataset dataset = tf.data.Dataset.from_tensor_slices((filenames, labels)) #step 3: parse every image in the dataset using `map` def _parse_function(filename, label): #convert label to one-hot encoding one_hot = tf.one_hot(label, stages) #read image file image_string = tf.read_file(filename) image_decoded = tf.image.decode_image(image_string, channels=3) image = tf.cast(image_decoded, tf.float32) return image, one_hot #step 4 final input tensor dataset = dataset.map(_parse_function) dataset = dataset.batch(batch_size) #batch_size = 100 iterator = dataset.make_one_shot_iterator() images, labels = iterator.get_next() images = tf.reshape(images, [batch_size,dimension]).eval() labels = tf.reshape(labels, [batch_size,stages]).eval() for _ in range(10): dataset = dataset.shuffle(buffer_size = 100) dataset = dataset.batch(batch_size) iterator = dataset.make_one_shot_iterator() images, labels = iterator.get_next() images = tf.reshape(images, [batch_size,dimension]).eval() labels = tf.reshape(labels, [batch_size,stages]).eval() train_step.run(feed_dict={x: images, y_:labels}) Somehow using a higher batch_sizes will break python. What I'm trying to do is to train my neural network with new batches on each iteration. That's why Im also using dataset.shuffle(...). Using dataset.shuffle also breaks my Python. What I wanted to do (because shuffle breaks) is to batch the whole dataset. By evaluating ('.eval()') I will get a numpy array. I will then shuffle the array with numpy.random.shuffle(images) and then pick up some the first elements to train…
tagged with: mnist
tagged with: python
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49188235
tagged with: dataset

http://stackoverflow.com/q/49205815
tagged with: python
has title: How to make a better strategy for read database many time?
has answer: http://stackoverflow.com/a/49206348
score: 1
downvote count: 0
answer count: 1
tagged with: machine-learning
upvote count: 1
tagged with: keras
favorite count: 0
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: I am working on training a network that requires loading the image and its ground-truth data from dataset every iteration. Currently, I used the below strategy that read the image and its ground-truth every time from my SSD. The problem is that my images are *png with large size (512x512x3), hence, it takes time to read these images. Also, the strategy repeated read the images in the dataset. Do we have a better strategy to do it faster, ie. load all images to RAM and access it from RAM is faster? I am using python3 and keras class myDataset(Dataset): def load_dataset(self, root_path): #Return a list of image and ground-truth def load_image(self, image_id): info = self.image_info[image_id] image = skimage.io.imread(info["path"]) return image def load_gt(self, image_id): #Load ground-truth data info = self.image_info[image_id] gt_data = skimage.io.imread(info["path"]) return gt_data #==========Preparing dataset, return a dict of image, mask path===== dataset_train = myDataset() dataset_train.load_dataset('./dataset') dataset_train.prepare() #==========Load image and its mask during training================= for i in range (10000): #Let image_id be a random id from the dict image=dataset_train.load_image(image_id) gt_data=dataset_train.load_gt(image_id)

http://stackoverflow.com/comment/85548427
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49194458
type: AnswerComment
has text: I like the callback solution a lot, give quite some matplotlib insight. Nice!

http://stackoverflow.com/q/49266786
tagged with: flask
answer count: 1
tagged with: ajax
score: 2
type: AnsweredQuestion
upvote count: 3
tagged with: http://stackoverflow.com/tag/json
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49267208
type: Question
has body: I am using ajax to POST a JSON string to Python Flask but get the following error: Error This is my JavaScript: $.ajax({ type: 'POST', url: window.location.href, data: JSON.stringify(questionObj0), dataType: 'json', contentType: 'application/json; charset=utf-8' }).done(function(msg) { console.log(msg); }); And this is my Python: @app.route('/test', methods=['GET', 'POST']) def test(): question = request.get_json() question1 = json.loads(question) print (question) return render_template('test.html') Using print(question) yields the following output (same output when tested in JavaScript using browsers console): {'questionNumber': 1, 'question': 'Convert 10110001 to decimal', 'answer': 177, 'userAnswer': 'blank'} From what I understand, the output should be a string and therefore padded with quotation marks. Has anyone come across anything similar/know how to fix the issue?
has title: Error when using JSON to send Javascript object to Python Flask
tagged with: javascript
tagged with: python
accepted answer: http://stackoverflow.com/a/49267208

http://stackoverflow.com/comment/85282046
type: AnswerComment
has text: now im getting this error message: File "sketch.py", line 43, in constructTrades self.trades.append(Candle(trade['open'], trade['high'], trade['low'], trade['close'], trade['timestamp'])) TypeError: list indices must be integers or slices, not str
comment on: http://stackoverflow.com/a/49134708
type: Comment
score: 0

http://stackoverflow.com/comment/85356353
comment on: http://stackoverflow.com/q/49159643
score: 0
has text: @danihp - neither. What I posted is what I have so far, regarding the view.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85360837
score: 0
type: Comment
type: QuestionComment
has text: Django 2.1 [will have a hook](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-the-default-admin-site) to override the default admin site easily. Until then, it's trickier. [This answer](https://stackoverflow.com/questions/40090090/django-1-10-override-adminsite) might help you.
comment on: http://stackoverflow.com/q/49176113

http://stackoverflow.com/comment/85289114
comment on: http://stackoverflow.com/a/49141765
has text: I’m sorry I did this from my phone. Thank you Mrlenny
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85402056
has text: https://stackoverflow.com/questions/16628819/convert-pandas-timezone-aware-datetimeindex-to-naive-timestamp-but-in-certain-t -- seems to work on some sort of an object, but not a column of a dataframe.
type: Comment
comment on: http://stackoverflow.com/q/49198068
score: 0
type: QuestionComment

http://stackoverflow.com/a/49280195
downvote count: 3
upvote count: 18
type: Answer
has comment: http://stackoverflow.com/comment/98223491
answers question: http://stackoverflow.com/q/49270109
has comment: http://stackoverflow.com/comment/88324889
has comment: http://stackoverflow.com/comment/85628358
score: 15
has body: To create and open a new Chrome Profile you need to follow the following steps : Open Chrome browser, click on the Side Menu and click on Settings on which the url chrome://settings/ opens up. In People section, click on Manage other people on which a popup comes up. Click on ADD PERSON, provide the person name, select an icon, keep the item Create a desktop shortcut for this user checked and click on ADD button. Your new profile gets created. Snapshot of a new profile SeLeNiUm Now a desktop icon will be created as SeLeNiUm - Chrome From the properties of the desktop icon SeLeNiUm - Chrome get the name of the profile directory. e.g. --profile-directory="Profile 2" Get the absolute path of the profile-directory in your system as follows : C:\\Users\\Otaku_Wiz\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 2 Now pass the value of profile-directory through an instance of Options with add_argument() method along with key user-data-dir as follows : from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("user-data-dir=C:\\Users\\AtechM_03\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 2") driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe', chrome_options=options) driver.get("https://www.google.co.in") Execute your Test Observe Chrome gets initialized with the Chrome Profile as SeLeNiUm
has comment: http://stackoverflow.com/comment/85628361

http://stackoverflow.com/a/49188931
has comment: http://stackoverflow.com/comment/85383242
has body: It's a simple math expression: def AVGofGrades(self, *student): return sum(student) / len(student) You should call it as self.AVGofGrades() though, not just AVGofGrades().
has comment: http://stackoverflow.com/comment/85384108
score: 0
answers question: http://stackoverflow.com/q/49188794
type: Answer

http://stackoverflow.com/a/49250783
type: Answer
has body: You can do that by extending/overriding the name_get() method on the product model.
score: 0
answers question: http://stackoverflow.com/q/49247321
has comment: http://stackoverflow.com/comment/85583823
has comment: http://stackoverflow.com/comment/85548489

http://stackoverflow.com/comment/85503520
score: 0
comment on: http://stackoverflow.com/q/49249731
type: QuestionComment
has text: I _may_ have guessed wrong about what you're trying to do, but please read it and tell me.
type: Comment

http://stackoverflow.com/q/49277341
has body: When I am using this: results_all.ix['Total', 'n_Close'] = results_all['n_Close'].sum() the results is this (the results is not summed but rather added): date n_Close g_Close potential 0 2017-05-02.csv 234 10.5 20.5 1 2017-05-03.csv -8 0 1 Total 234.0-8.0 When I use this: results_all.loc['Total']= results_all.sum() the result is: date n_Close g_Close potential 0 2017-05-02.csv 234 10.5 20.5 1 2017-05-03.csv -8 0 1 Total 2017-05-02.csv2017-05-03.csv 234.0-8.0 10.50.0 20.51.0 The required result will be sum for specific columns: date n_Close g_Close potential XXX 0 2017-05-02.csv 234 10.5 20.5 10 1 2017-05-03.csv -8 0 1 7 Total nothing here 226 10.50 21.5 nothing here
has title: using loc to sum part columns and not all of them in pandas
tagged with: python
has answer: http://stackoverflow.com/a/49277429
accepted answer: http://stackoverflow.com/a/49277429
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
type: Question

http://stackoverflow.com/comment/85456125
score: 0
comment on: http://stackoverflow.com/q/49226167
has text: @triandicAnt: No, it's perfectly legal—although it probably doesn't mean what he intended. [`while` statements have `else` clauses](https://docs.python.org/3/reference/compound_stmts.html#the-while-statement).
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49223147
has answer: http://stackoverflow.com/a/49223707
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85450755
type: Question
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85449895
has comment: http://stackoverflow.com/comment/85450952
has comment: http://stackoverflow.com/comment/85450918
has body: I have a dictionary with elements as lists of certain sequence: a = {'seq1':['5', '4', '3', '2', '1', '6', '7', '8', '9'], 'seq2':['9', '8', '7', '6', '5', '4', '3', '2', '1'], 'seq3':['5', '4', '3', '2', '1', '11', '12', '13', '14'], 'seq4':['15', '16', '17'], 'seq5':['18', '19', '20', '21', '22', '23'], 'seq6':['18', '19', '20', '24', '25', '26']} So there are 6 sequences What I need to do is: To find only unique lists (if two lists contains the same elements (regardless of their order), they are not unique) - say I need to get rid of the second list (the first founded unique list will stay) In unique lists I need to find unique subsequences of elements and print it Bounds of unique sequences are found by resemblance of elements order - in the 1st and the 3rd lists the bound ends exactly after element '1', so we get the subsequence ['5','4','3','2','1'] As the result I would like to see elements exactly in the same order as it was in the beginning (if it`s possible at all somehow). So I expect this: [['5', '4', '3', '2', '1']['6', '7', '8', '9']['11', '12', '13', '14']['15', '16', '17']['18', '19', '20']['21', '22', '23']['24', '25', '26']] Tried to do it this way: import itertools unique_sets = [] a = {'seq1':["5","4","3","2","1","6","7","8","9"], 'seq2':["9","8","7","6","5","4","3","2","1"], 'seq3':["5","4","3","2","1","11","12","13","14"], 'seq4':["15","16","17"], 'seq5':["18","19","20","21","22","23"], 'seq6':["18","19","20","24","25","26"]} b = [] for seq in a.values(): b.append(seq) for seq1, seq2 in itertools.combinations(b,2): #searching for intersections if set(seq1).intersection(set(seq2)) not in unique_sets: #if set(seq1).intersection(set(seq2)) == set(seq1): #continue unique_sets.append(set(seq1).intersection(set(seq2))) if set(seq1).difference(set(seq2)) not in unique_sets: unique_sets.append(set(seq1).difference(set(seq2))) for it in unique_sets: print(it) I got this which is a little bit different from my expectations: {'9', '5', '2', '3', '7', '1',…
has comment: http://stackoverflow.com/comment/85450216
has title: Python - List of unique sequences
has comment: http://stackoverflow.com/comment/85450572
tagged with: set
downvote count: 0
has comment: http://stackoverflow.com/comment/85450119
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85449932

http://stackoverflow.com/comment/85376637
comment on: http://stackoverflow.com/a/49161105
has text: Also chris when i use the database resident connection pooling instead of session pool my workload completes in half the time so not sure why the tutorial recommends the approach of using the sessionPool i find connection pool far superior
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85317745
type: QuestionComment
type: Comment
score: 0
has text: We can hardly know what you are talking about. i assume a pandas dataframe. I do no know pandas but this kind of issue is not pandas specific.
comment on: http://stackoverflow.com/q/49156393

http://stackoverflow.com/a/49153300
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49151683
has comment: http://stackoverflow.com/comment/92951105
has comment: http://stackoverflow.com/comment/92949906
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/92950097
has body: What I understood from your question is you need to find the length of longest occurance of consecutive elements in numpy array (row by row). So for this below one, the output should be 5: [[1 2 3 4 0] [0 0 0 0 0] [10 11 12 13 14] [0 1 2 3 0] [1 0 0 0 0]] Because [10 11 12 13 14] are consecutive elements and they have the longest length comparing to any consecutive elements in any other row. If this is what you are expecting, consider this: import numpy as np from itertools import groupby a = np.array([[1, 2, 3, 4, 0], [0, 0, 0, 0, 0], [10, 11, 12, 13, 14], [0, 1, 2, 3, 0], [1, 0, 0, 0, 0]]) a = a.astype(float) a[a == 0] = np.nan b = np.diff(a) # Calculate the n-th discrete difference. Consecutive numbers will have a difference of 1. counter = [] for line in b: # for each row. if 1 in line: # consecutive elements differ by 1. counter.append(max(sum(1 for _ in g) for k, g in groupby(line) if k == 1) + 1) # find the longest length of consecutive 1's for each row. print(max(counter)) # find the max of list holding the longest length of consecutive 1's for each row. # 5 For your particular example: [[0 0 0 0 0] [0 0 0 0 0] [1 2 3 4 5] [0 0 0 0 0] [0 0 0 0 0]] # 5
accepted answer of: http://stackoverflow.com/q/49151683
has comment: http://stackoverflow.com/comment/92950951

http://stackoverflow.com/q/49184163
has answer: http://stackoverflow.com/a/49184317
favorite count: 0
type: Question
has body: I should mention that I've read these but I'm still unable to achieve my goal: [Using a dictionary in a for loop to create buttons doesn&#39;t work [QtCore.QObject.connect in a loop only affects the last instance My goal is to make a linux 'launcher' application. Button creation, placement, etc. is working like a charm but there's one problem - all buttons trigger the same callback - the last one to be connected in the button creation loop. Here's a basic version of the script to illustrate what I'm trying to do: class App(QMainWindow): def launch(self, filepath): subprocess.run(filepath) def __init__(self): super(App, self).__init__() for btn in matrix: filepath = matrix[btn]['path'] icon = matrix[btn]['setIcon'] posx = matrix[btn]['posx'] posy = matrix[btn]['posy'] matrix[btn] = QToolButton(self) matrix[btn].setIcon(QIcon(icon)) matrix[btn].setIconSize(QSize(64, 64)) matrix[btn].resize(100, 100) matrix[btn].move(posx, posy) matrix[btn].clicked.connect(lambda launch: self.launch(filepath)) self.initUI() def initUI(self): self.setGeometry(150, 150, 1250, 650) self.setWindowTitle('LinuxLauncher') self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_()) I know there's an answer but I've been at it for hours - I'd appreciate it someone could help me out of this jam - Thanks!
tagged with: python
has comment: http://stackoverflow.com/comment/85374794
linked to: http://stackoverflow.com/q/34189017
tagged with: qpushbutton
has title: Creating PyQt5 buttons in a loop: all buttons trigger the same callback
type: AnsweredQuestion
score: 3
tagged with: linux
upvote count: 3
tagged with: pyqt
linked to: http://stackoverflow.com/q/19510860
answer count: 1
downvote count: 0
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/49184317

http://stackoverflow.com/a/49184817
type: AcceptedAnswer
score: 3
has comment: http://stackoverflow.com/comment/85375710
type: Answer
accepted answer of: http://stackoverflow.com/q/49184761
has body: If you are allowed to store values you could do something like: smallest = numbers[0] biggest = numbers[0] total = 0 for num in numbers: if num &lt; smallest: smallest = num elif num &gt; biggest: biggest = num total += num average = total / len(numbers)
upvote count: 3
answers question: http://stackoverflow.com/q/49184761
has comment: http://stackoverflow.com/comment/85375527
downvote count: 0
has comment: http://stackoverflow.com/comment/85375842

http://stackoverflow.com/comment/85536938
comment on: http://stackoverflow.com/q/49225456
score: 0
has text: Why do you have the `SteamName OR` part there at all? I would just do `WHERE SteamName = %s`. Also, see http://bobby-tables.com/python.html
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/126509645
comment on: http://stackoverflow.com/a/49246761
score: 0
type: Comment
has text: After making this fix, if your code continues to show the same error, try adding `squeeze=False` as an argument to `plt.subplots()`
type: AnswerComment

http://stackoverflow.com/comment/85502859
comment on: http://stackoverflow.com/q/49245642
has text: @gm9089zo: because that is what it was compiled against and has binary dependencies on
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49224350
type: Answer
answers question: http://stackoverflow.com/q/49224224
has body: to answer this question, we have to understand what is the datatype of data.iloc and how are you accessing data.iloc[45,25]? - if iloc is a dictionary with the tuple (45,25) as key then access data.iloc[(x,25)].
score: 0

http://stackoverflow.com/q/49205654
tagged with: python-3.x
has title: How to determine the first and last item in a list of objects in Python?
tagged with: python
score: -1
has body: I need to create a class Person (in Python) that implements the comparison operator such as &lt; to compare their names. I need to ask the user for input of 10 names and generate 10 Person objects. I need to determine the first and last person among them and print them. I got the class, operator and ask for user input. All is working but I am not sure how to determine the first and last person? Any help would be appreciated, below is my code: class Person(): def __init__(self, name): self.name = name def __str__(self): return '{}'.format(self.name) def __eq__(self, other): return self.name == other.name def __lt__(self, other): return self.name &lt; other.name #create empty list to hold person object persons =[] for p in range(0,10): if p==0: name = input("please enter name: ") else: name = input("please enter another name: ") #take user input and create 10 person object persons.append(Person(name)) for person in persons: print(person)
has comment: http://stackoverflow.com/comment/85416474
has comment: http://stackoverflow.com/comment/85416652
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49205701
upvote count: 0
has answer: http://stackoverflow.com/a/49205701
answer count: 1
has comment: http://stackoverflow.com/comment/85416639
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49176871
tagged with: python
has body: driver.find_element_by_class_name("lnkClassInfo").click() time.sleep(2) element = driver.find_element_by_css_selector("#popup input[value='BOOK THIS CLASS NOW']") driver.execute_script("arguments[0].click();", element) ERROR: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"#popup input[value='BOOK THIS CLASS NOW']"} Line 1 of my code allows me to click into the above time-slot on the Main Page, which triggers an Overlay to pop up. My goal is to click the class-booking button on the overlay. Based on my understanding, Python needs to switch to the overlay/iframe. Please advise on how to code this for my attempts have been unsuccessful so far. Relevant Main Page HTML: &lt;script type="text/javascript"&gt; $(document).ready(function () { setPageScroll('dashboard'); $(".club-selections a").click(function () { $("#ctl00_cphContents_ddlClub").val($(this).attr('rel')); $("form:first").submit(); }); $(".schedule-selection a").click(function () { $("#ctl00_cphContents_ddlSchedule").val($(this).attr('rel')); $("form:first").submit(); }); $(".club-selections a[rel=" + $("#ctl00_cphContents_ddlClub").val() + "]").addClass('selected'); $(".schedule-selection a[rel=" + $("#ctl00_cphContents_ddlSchedule").val() + "]").addClass('selected'); $(".lnkClassInfo").click(function () { $.colorbox({ href: $(this).attr("href"), title: $(this).attr("title"), transition: 'fade', iframe: true, width: 566, height: 600, fixed: true }); return false; }); var FIREFOX = /Firefox/i.test(navigator.userAgent); if (FIREFOX) { $('.tbl-wrapper .tbl-container').scroll(function () { $('title').html($(this).scrollLeft()); $(this).find('a.lnkClassInfo').css('margin-right', $(this).scrollLeft() + "px"); }); } }); &lt;/script&gt; &lt;a href='popup/class-info.aspx?tcl_id=307632' title='Class Info.' style='line-height:74px; height:74px; top:413px;' class='lnkClassInfo'&gt;&lt;span class='class-name'&gt;ICE II&lt;/span&gt;…
score: 2
tagged with: iframe
downvote count: 0
answer count: 1
tagged with: selenium
tagged with: overlay
has title: Python + Selenium: How to switch to overlay
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/49177115

http://stackoverflow.com/comment/85596477
score: 0
type: AnswerComment
has text: I know where the POST request is received and I have successfully authenticated using python-requests before my question. But I have a Linux server running `nginx` and I want to be able to go to http://myserver.com/enter and it redirects me to the site in question already authenticated @sykez
comment on: http://stackoverflow.com/a/49274397
type: Comment

http://stackoverflow.com/q/49193286
accepted answer: http://stackoverflow.com/a/49193346
score: 1
downvote count: 0
answer count: 1
upvote count: 1
tagged with: scikit-learn
has title: python scikit learn logistic regression error
favorite count: 0
tagged with: logistic-regression
type: Question
has answer: http://stackoverflow.com/a/49193346
has body: I am trying to plot a logistic regression graph from the following data X = np.array([0,1,2,3,4,5,6,7,8,9,10,11]) y = np.array([0,0,0,0,1,0,1,0,1,1,1,1]) However when I try: import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model X = np.array([0,1,2,3,4,5,6,7,8,9,10,11]) y = np.array([0,0,0,0,1,0,1,0,1,1,1,1]) clf = linear_model.LogisticRegression(C=1e5) clf.fit(X, y) I get the following error: ValueError: Found input variables with inconsistent numbers of samples: [1, 12] I am a bit confused why it thinks that either X or y has only one sample.
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/85429909
type: QuestionComment
has text: https://stackoverflow.com/questions/48510555/pandas-flag-column-if-value-in-list-exists-anywhere-in-row/48510634#48510634
type: Comment
comment on: http://stackoverflow.com/q/49212682
score: 0

http://stackoverflow.com/q/49141025
tagged with: bash
has comment: http://stackoverflow.com/comment/85603024
score: 1
favorite count: 0
type: Question
has body: I am trying to run a gunicorn enclosing a python app but it keeps giving me failed to find application error. Here is the whole trace: [2018-03-06 22:17:39 +0000] [13278] [INFO] Starting gunicorn 19.7.1 [2018-03-06 22:17:39 +0000] [13278] [INFO] Listening at: http://0.0.0.0:7007 (13278) [2018-03-06 22:17:39 +0000] [13278] [INFO] Using worker: gthread [2018-03-06 22:17:39 +0000] [13281] [INFO] Booting worker with pid: 13281 [2018-03-06 22:17:39 +0000] [13285] [INFO] Booting worker with pid: 13285 [2018-03-06 22:17:39 +0000] [13286] [INFO] Booting worker with pid: 13286 [2018-03-06 22:17:39 +0000] [13290] [INFO] Booting worker with pid: 13290 Failed to find application: 'production.server' [2018-03-06 22:17:42 +0000] [13281] [INFO] Worker exiting (pid: 13281) Failed to find application: 'production.server' Failed to find application: 'production.server' [2018-03-06 22:17:42 +0000] [13285] [INFO] Worker exiting (pid: 13285) [2018-03-06 22:17:42 +0000] [13290] [INFO] Worker exiting (pid: 13290) Failed to find application: 'production.server' [2018-03-06 22:17:42 +0000] [13286] [INFO] Worker exiting (pid: 13286) [2018-03-06 22:17:42 +0000] [13278] [INFO] Shutting down: Master [2018-03-06 22:17:42 +0000] [13278] [INFO] Reason: App failed to load. And my file tree shows that production/server.py does exist. I am running the bash command: gunicorn \ -b 0.0.0.0:${port} \ -k gthread \ -w ${proc_count} \ --threads ${thread_count} \ -t 300 \ 'production.server:create_app(ensemble)' when I am rooted at the directory containing production sub-directory. When I run the Gunicorn command from bash directly: gunicorn production.server:create_app -b 0.0.0.0:7007 it works just fine! How can I fix this?
tagged with: gunicorn
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has title: Gunicorn failed to find application when run from a shell file but succeeds when run from cli directly

http://stackoverflow.com/q/49168762
upvote count: 12
has body: I have a function that most of the time should return a single value, but sometimes I need a second value returned from the function. Here I found how to return multiple values, but as most of the time I need only one of them I would like to write something like this: def test_fun(): return 1,2 def test_call(): x = test_fun() print x but calling this results in &gt;&gt;&gt; test_call() (1,2) and when trying to return more than two, as in def test_fun2(): return 1,2,3 def test_call2(): x,y = test_fun2() print x,y I get an error Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "my_module.py", line 47, in test_call2 x,y = test_fun2() ValueError: too many values to unpack I am thinking about something like in matlab, where x = test_fun() would result in x == 1 (while [x y] = test_fun() would also work as expected). Is something like that possible in python?
tagged with: function
tagged with: python
score: 11
possible better answer: http://stackoverflow.com/a/49169107
type: AnsweredQuestion
tagged with: return-value
downvote count: 1
has answer: http://stackoverflow.com/a/49169107
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49168865
linked to: http://stackoverflow.com/q/9752958
answer count: 2
has title: optional multiple return values
has answer: http://stackoverflow.com/a/49168865

http://stackoverflow.com/comment/85334099
type: Comment
score: 0
has text: I can post it in a bit when I get somewhere I have access to it, but the pseudo code I can put above.
comment on: http://stackoverflow.com/q/49163994
type: QuestionComment

http://stackoverflow.com/comment/85338142
score: 0
has text: Maybe that feature is your class label that you accidentally put in X, or maybe something that corresponds to the classes, which in reality is computed after the class is known. You should not take such features.
comment on: http://stackoverflow.com/q/49149075
type: Comment
type: QuestionComment

tensor
tags question: http://stackoverflow.com/q/49234160
tags question: http://stackoverflow.com/q/49174596
tag name: tensor
type: Tag
tags question: http://stackoverflow.com/q/49268475
tags question: http://stackoverflow.com/q/49158935

http://stackoverflow.com/q/49203426
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85412415
tagged with: http://stackoverflow.com/tag/html
downvote count: 0
answer count: 1
has body: How would I go about writing a function (with BeautifulSoup or otherwise) that would replace all instances of one HTML tag with another. For example: text = " this is some text with some tags that I would like to replace " new_text = replace_tags(text, "bad", "p") print(new_text) # " this is some text with some tags that I would like to replace " I tried this, but preserving the attributes of each tag is a challenge: def replace_tags(string, old_tag, new_tag): soup = BeautifulSoup(string, "html.parser") nodes = soup.findAll(old_tag) for node in nodes: new_content = BeautifulSoup("<{0}>{1}</{0}".format( new_tag, node.contents[0], )) node.replaceWith(new_content) string = soup.body.contents[0] return string Any idea how I could just replace the tag element itself in the soup? Or, even better, does anyone know of a library/utility function that'll handle this more robustly than something I'd write? Thank you!
favorite count: 0
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/49205202
accepted answer: http://stackoverflow.com/a/49205202
has comment: http://stackoverflow.com/comment/85412780
tagged with: python
has title: Python function to replace all instances of a tag with another
type: AnsweredQuestion

http://stackoverflow.com/q/49266871
score: 0
tagged with: http://stackoverflow.com/tag/csv
has body: I am writing a vending machine simulation in Python as school work and I am required to edit a specific line to keep a stock list up to date. Here is the code: import csv with open('stock.csv','r') as STOCK_READ: #Counts the amount of items in the CSV file ITEM_COUNT = 0 reader = csv.reader(STOCK_READ) for line in reader: ITEM_COUNT = ITEM_COUNT + 1 def GET_STOCK_COUNT(): with open('stock.csv', 'r') as STOCK_READ: reader = csv.reader(STOCK_READ) for line in reader: print("{0} - {1} - {2} in stock".format(line[0],line[1],line[2])) while True: GET_STOCK_COUNT() CHOSEN_ITEM = int(input("Input number of desired item: ")) Here is the CSV (It goes: Item no., Name, Stock): 1,Coca Cola,10 2,Monster,10 3,Monster Ultra,10 By making the user select the number, I want to make the CSV writer go to the correct line and make the change to the number at the end.
type: Question
has answer: http://stackoverflow.com/a/49267035
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49267035
has title: Modify specific cell in Python CSV
answer count: 2
tagged with: python
has answer: http://stackoverflow.com/a/49267404
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49267404

http://stackoverflow.com/comment/85290386
comment on: http://stackoverflow.com/q/49128964
has text: First update your NLTK version, your version is outdated, `pip install -U nltk`. Next in the new version, you'll see something like `import nltk; nltk.download('popular')`.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85264729
comment on: http://stackoverflow.com/q/49130146
has text: Can you add sample of `dict`? I think `DataFrame` should be generated from `dict`, so not necessery define columns.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85537516
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49266989
has text: There are OS-dependent tools to resize files; I suspect that the best way for you is to convert the input directory using one of those; search using your OS name as one of the parameters.

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/49219586
tags question: http://stackoverflow.com/q/49137795
type: Tag

http://stackoverflow.com/a/49157800
upvote count: 1
has comment: http://stackoverflow.com/comment/85321233
has comment: http://stackoverflow.com/comment/85320895
accepted answer of: http://stackoverflow.com/q/49157349
has comment: http://stackoverflow.com/comment/85320744
downvote count: 0
score: 1
has body: I would recommend using the Pandas multiIndex. In your case you could do the following: tuples = list(data'Date', 'Symbol'.itertuples(index=False, name=None)) data.index = pd.MultiIndex.from_tuples(tuples, names=['Date', 'Symbol']) # And then to index data.loc['2018-01-11', 'AEDCAD']
answers question: http://stackoverflow.com/q/49157349
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/85452892
has text: @Alnitak Nope, no direct way there.
comment on: http://stackoverflow.com/a/49224278
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/49266901
type: Answer
score: 11
answers question: http://stackoverflow.com/q/49266014
upvote count: 11
has body: Seaborn has in general two ways to calculate the bivariate kde. If available, it uses statsmodels, if not, it falls back to scipy. The scipy code is similar to what is shown in the question. It uses scipy.stats.gaussian_kde. The statsmodels code uses statsmodels.nonparametric.api.KDEMultivariate. However, for a fair comparisson we would need to take the same grid size for both methods. The standard gridsize for seaborn is 100 points. import numpy as np; np.random.seed(42) import seaborn.distributions as sd N = 34900 x = np.random.randn(N) y = np.random.randn(N) bw="scott" gridsize=100 cut=3 clip = [(-np.inf, np.inf), (-np.inf, np.inf)] f = lambda x,y : sd._statsmodels_bivariate_kde(x, y, bw, gridsize, cut, clip) g = lambda x,y : sd._scipy_bivariate_kde(x, y, bw, gridsize, cut, clip) If we time those two functions, # statsmodels %timeit f(x,y) # 1 loop, best of 3: 16.4 s per loop # scipy %timeit g(x,y) # 1 loop, best of 3: 8.67 s per loop Scipy is hence twice as fast as statsmodels (the seaborn default). The reason why the code in the question takes so long is that instead of a grid of size 100, a grid of size 2000 is used. Seeing those results one would actually be tempted to use scipy instead of statsmodels. Unfortunately it does not allow to choose which one to use. One hence needs to manually set the respective flag. import seaborn.distributions as sd sd._has_statsmodels = False # plot kdeplot with scipy.stats.kde.gaussian_kde sns.kdeplot(x,y)
downvote count: 0

http://stackoverflow.com/q/49132008
has comment: http://stackoverflow.com/comment/85269751
has answer: http://stackoverflow.com/a/49134293
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85271397
upvote count: 1
has body: I have next method: public void callPython() throws IOException { Runtime rt = Runtime.getRuntime(); Process pr = rt.exec("python -c \"from test import read_and_show; read_and_show()\" src/main/python"); BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream())); BufferedReader bfre = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String outputStr = ""; while ((outputStr = bfr.readLine()) != null) { System.out.println(outputStr); } while ((outputStr = bfre.readLine()) != null) { System.out.println(outputStr); } } in python file next code: import os from stat import * def read_and_show(): print('worked!') when i call this in terminal all worked correctly (before i cd to this directory): MacBook-Pro-Nikita-2:python NG$ python -c "from test import read_and_show; read_and_show()" worked! when i run this code in my java code he return error: File "&lt;string&gt;", line 1 "from ^ SyntaxError: EOL while scanning string literal What i make wrong? P.S.: i need run python method/class/file for read, parse and show graphical data. but for this need when java run python single method (def)
has answer: http://stackoverflow.com/a/49134183
downvote count: 1
has answer: http://stackoverflow.com/a/49135038
favorite count: 0
has comment: http://stackoverflow.com/comment/85271420
linked to: http://stackoverflow.com/q/10308221
tagged with: terminal
has comment: http://stackoverflow.com/comment/85271957
answer count: 3
has comment: http://stackoverflow.com/comment/85274456
has comment: http://stackoverflow.com/comment/85269827
has comment: http://stackoverflow.com/comment/85271277
tagged with: java
has comment: http://stackoverflow.com/comment/85271446
tagged with: python
tagged with: macos
has comment: http://stackoverflow.com/comment/85271086
has title: How to run python from java correctly?
type: Question
has comment: http://stackoverflow.com/comment/85269911

http://stackoverflow.com/comment/85401216
type: AnswerComment
has text: Thanks for the reply. I tried this already thought: from xlrd import open_workbook book = open_workbook('test.xls') CompDocError: Expected "little-endian" marker, found b'\xff\xfe'
type: Comment
comment on: http://stackoverflow.com/a/49198147
score: 0

http://stackoverflow.com/comment/85323871
score: 1
type: Comment
type: QuestionComment
has text: @andi Yeah that was it. Small oversight on my part. thank you
comment on: http://stackoverflow.com/q/49159292

http://stackoverflow.com/comment/85417108
comment on: http://stackoverflow.com/a/49179219
score: 0
type: Comment
has text: @hemantcnaik Could you upload the text file to something like bpaste.net so I could see it? I’m just not sure what the format looks like. Chances are you are just going to want to use pythons built in ‘open’ function though.
type: AnswerComment

http://stackoverflow.com/comment/85327939
comment on: http://stackoverflow.com/a/49160744
score: 0
type: AnswerComment
has text: Yes! Very clever, and it really is an order of magnitude improvement in speed! (We can I/O DataFrame to fit OP via `df['F'] = tai(df['S'].values)`.)
type: Comment

http://stackoverflow.com/a/49166493
score: 0
answers question: http://stackoverflow.com/q/49166307
type: Answer
has body: Your code as under is valid: fighter_match_data = json.load(open(file="fighter_data.txt", mode="r")) Consider this part: open(file="fighter_data.txt", mode="r") . #1 v/s data_file = open(file="fighter_data.txt", mode="r") . #2 In case of #2, in case you do not explicitly close the file, the file will automatically be closed when the variable ceases to exist[In better words, no reference exists to that variable] (when you move out of the function). In case of #1, since you never create a variable, the lifespan of that implicit variable created for opening that file ceases to exist on that line itself. And python automatically closes the file after opening it.

http://stackoverflow.com/q/49190016
possible better answer: http://stackoverflow.com/a/49190132
tagged with: python
favorite count: 0
has title: Generate 2d points based on sample points with variance
upvote count: 2
accepted answer: http://stackoverflow.com/a/49190460
has comment: http://stackoverflow.com/comment/85385224
downvote count: 0
type: Question
score: 2
type: AnsweredQuestion
has body: I have a plot where I gather 10 points via mouseclick events on a 2d grid [-55 - 55, -35, 35]. After that I'm adding a label representing the 10 points and save it in a list. Here is a sample entry of the result list: &lt;class 'list'&gt;: [[-38.39, 20.3], [-38.25, 12.27], [-38.39, 5.0], [-38.96, -3.48], [-37.54, -15.61], [-26.33, -7.73], [-28.32, 3.03], [-26.47, 14.24], [-20.08, 15.15], [-18.38, -1.36], [1.0]] Now I want to generate similar list entries based on the 10 sample points. The data should later serve as training data for a model to determine different formations of the 10 points. I would appreciate tips for the generation of similar points within a certain degree of variance.
answer count: 3
has answer: http://stackoverflow.com/a/49190207
has answer: http://stackoverflow.com/a/49190460
has answer: http://stackoverflow.com/a/49190132

http://stackoverflow.com/a/49158890
type: Answer
answers question: http://stackoverflow.com/q/49157831
has comment: http://stackoverflow.com/comment/85326801
accepted answer of: http://stackoverflow.com/q/49157831
has comment: http://stackoverflow.com/comment/85324123
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85323111
has body: I don't work for Jet Brains, but I have used Resharper and PyCharm for many years. Here is my general experience/thoughts on the subject (specifically for Pycharm). Until recently, with the availability of type hints 3.5+, PyCharm has had to make some really clever inferences to provide things like type checking and auto complete. It does a pretty dang good job considering -- but often its best guess simply isn't correct. Ultimately sometimes only the developer can decide if it simply guessed wrong. If you are like me, you can't stand seeing those little curly lines telling you of a code smell. Fortunately, PyCharm gives you the ability to turn off a warning for a line, a function, or even a file (eg. # noinspection PyTypeChecker - in your case). When I know that PyCharm is giving me wrong warnings, I rely on those. Sometimes I disagree with PyCharm altogether and adjust checks for the entire project. Now, with type hinting this should get a lot better (provide developers use it). PyCharm will have more reliable information on which to make its decisions. The good news is that you can help. Ensure that you use type hinting for all your personal projects Encourage others that you work with to do the same Kindly and positively encourage package maintainers to do the same Offer to contribute to projects by adding type hints If every developer does the above, most of your false warnings go away. Until then, there is no magic answer for all. You simply have to deal with warnings on a case by case basis.

http://stackoverflow.com/comment/85274775
has text: Well that might be a problem, but as long as you don't try it, this problem does not become apparent.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49134634

http://stackoverflow.com/a/49225900
answers question: http://stackoverflow.com/q/49225866
score: 1
upvote count: 1
has body: Your problem is that you are replacing L every time, instead of appending to L. The following should work: numList = [2,3,4,5,6,7] def square (N): sq = N * N return (sq) def cmput_square(numList): i = 0 L = [] while i &lt; len (numList): L.append(square(numList[i])) i = i + 1 return (L) n = cmput_square (numList) print ("The squares of your numbers are:", n) prints: The squares of your numbers are: [4, 9, 16, 25, 36, 49] If you would like to reduce the number of lines of code required, you could change it to a single function with a list iteration: def cmput_square(numList): return([i*i for i in numList]) [EDIT] Seeing as you can't use .append or a list comprehension as per your comment, here is another way, again as a single function. I'd argue it's less elegant, but it gets you what you need: def cmput_square(numList): L = [0] * len(numList) for i in range(len(numList)): L[i] = numList[i]*numList[i] return(L) [EDIT #2] and without using for or range, you can do it this way: def cmput_square(numList): L = [0] * len(numList) i = 0 while i &lt; len(numList): L[i] = numList[i]*numList[i] i = i+1 return(L)
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49225866
downvote count: 0

http://stackoverflow.com/a/49226597
has body: You can create a dictionary of your desired arrays: x=[5,3,6,4] weights = {'W'+str(i+1): np.random.normal(loc=0.0, scale=1.0, size=(x[i],x[i+1])) for i in range(len(x)-1)} Then, to use them, just call them from that dictionary. For instance, if you want to use W1, use: weights['W1'] which returns your array: array([[-1.22374486, 0.74080707, 0.00914048], [ 0.08813797, 0.6807603 , 0.87249113], [ 0.29799539, -0.78276957, 0.11789963], [-0.25467395, -1.27457749, 0.96499082], [-2.92436286, -0.8131938 , -2.2352768 ]]) You can see a list of all the variables names created using weights.keys() See this answer
answers question: http://stackoverflow.com/q/49226529
has comment: http://stackoverflow.com/comment/85523003
has comment: http://stackoverflow.com/comment/85523332
score: 0
type: Answer

http://stackoverflow.com/a/49232907
has body: l = ['H1', 'H100', 'H10', 'H3', 'H2', 'H6', 'H11', 'H50', 'H5', 'H99', 'H8'] print sorted(l, key=lambda x: int("".join([i for i in x if i.isdigit()]))) Output: ['H1', 'H2', 'H3', 'H5', 'H6', 'H8', 'H10', 'H11', 'H50', 'H99', 'H100']
type: Answer
has comment: http://stackoverflow.com/comment/85470871
accepted answer of: http://stackoverflow.com/q/49232823
has comment: http://stackoverflow.com/comment/85469307
has comment: http://stackoverflow.com/comment/85471343
has comment: http://stackoverflow.com/comment/85470982
has comment: http://stackoverflow.com/comment/85472328
has comment: http://stackoverflow.com/comment/85473946
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85469444
answers question: http://stackoverflow.com/q/49232823
downvote count: 0
has comment: http://stackoverflow.com/comment/85470501
score: 9
upvote count: 9

http://stackoverflow.com/comment/85269630
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49131012
has text: Yes I have tested it.

http://stackoverflow.com/q/49274862
tagged with: python
has answer: http://stackoverflow.com/a/49274923
type: Question
score: 0
has title: Django Python Requests - Parse text/plain payload
answer count: 1
tagged with: django
tagged with: python-requests
type: AnsweredQuestion
has body: This seems like a stupid question, and probably is. Say that I'm making a request to an API as follows: r = requests.post("http://EXAMPLE.COM/api/randomstring") ## I've blocked out the real URL so false requests aren't made as it's publicly available The specification for this API is that on every request, it generates a random string of 10 letters. If the request is processed successfully, the server should respond with 201 CREATED and a text/plain payload giving the random string from the API database. I have previously tried the following to parse the request, and add it to a locally stored database model: new_word = r.text() Words.objects.create(word=new_word) But this gave the error: TypeError: 'str' object is not callable I then tried simply: Words.objects.create(word=r) When I run this from a client, and then check the local database, it only shows as: word: &lt;Response [201]&gt; This means that obviously the request was successful, and a word is in the text/plain payload. But how do I parse only the word from the payload, so that I am able to save it as (for example): word: hskcudyhft I know how to parse a JSON payload which is probably much trickier than this - which is probably why I'm overthinking it! Many thanks!
accepted answer: http://stackoverflow.com/a/49274923
tagged with: django-models

http://stackoverflow.com/comment/85482798
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49238821
has text: The result is not what you claim it is... Take a look at your second column vs jpp's answer.

http://stackoverflow.com/comment/85458528
has text: I think zip method is the best answer overall
comment on: http://stackoverflow.com/a/49227380
type: Comment
score: 2
type: AnswerComment

http://stackoverflow.com/comment/85537801
type: QuestionComment
comment on: http://stackoverflow.com/q/49267159
has text: Or can you explain why you need to know when the sound stops playing?
score: 0
type: Comment

http://stackoverflow.com/comment/125818178
type: Comment
has text: Note this ignore **all** errors on the **whole** file, not just errors on a single line like what OP was asking about.
comment on: http://stackoverflow.com/a/59549683
type: AnswerComment
score: 4

http://stackoverflow.com/a/49201197
type: Answer
accepted answer of: http://stackoverflow.com/q/49201028
has comment: http://stackoverflow.com/comment/85408104
upvote count: 4
has comment: http://stackoverflow.com/comment/85407794
answers question: http://stackoverflow.com/q/49201028
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/85407880
has comment: http://stackoverflow.com/comment/85407838
has body: you cannot propagate an environment variable to the parent process. But you can print the variable, and assign it back to the variable name from your shell: VarFromFirstScript=$(python myOtherScript.py $VarFromFirstScript) you must not print anything else in your code, or using stderr sys.stderr.write("Running some code...\n") VarFromFirstScript = someFunc() sys.stdout.write(VarFromFirstScript) an alternative would be to create a file with the variables to set, and make it parse by your shell (you could create a shell that the parent shell would source) import shlex with open("shell_to_source.sh","w") as f: f.write("VarFromFirstScript={}\n".format(shlex.quote(VarFromFirstScript)) (shlex.quote allows to avoid code injection from python, courtesy Charles Duffy) then after calling python: source ./shell_to_source.sh

http://stackoverflow.com/q/49260005
favorite count: 0
has answer: http://stackoverflow.com/a/49260063
type: Question
has body: I'm trying to test a string. I get the innerHTML, yet it has extra u'\n and \n' AssertionError: u'\n Codul de Utilizator/Parola introduse nu sunt corecte! \n' != ' Codul de Utilizator/Parola introduse nu sunt corecte! ' HTML from site Codul de Utilizator/Codul introduse nu sunt corecte! Code error = self.driver.find_element_by_id("errorDiv1").get_attribute('innerHTML') expected_error = ' Codul de Utilizator/Parola introduse nu sunt corecte! ' self.assertEqual(error, expected_error) What is happening here? Where they come from?
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85523418
has answer: http://stackoverflow.com/a/49260415
score: 0
answer count: 2
has title: Where does the \n come from?
tagged with: selenium
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/85534932
type: Comment
has text: I am actually feeding in the URL via urllib, and when I get the HTML data from the website, this does not work.
type: AnswerComment
comment on: http://stackoverflow.com/a/49264049
score: 0

http://stackoverflow.com/q/49133657
tagged with: dictionary
tagged with: append
has answer: http://stackoverflow.com/a/49137623
score: 0
has title: Adding to defaultdict keys using for loop
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/85272747
has comment: http://stackoverflow.com/comment/85273448
tagged with: key
has comment: http://stackoverflow.com/comment/85272188
has comment: http://stackoverflow.com/comment/85272276
type: Question
has comment: http://stackoverflow.com/comment/85272533
has comment: http://stackoverflow.com/comment/85272885
type: UnansweredQuestion
has body: I have tried multiple different suggestions I found on other threads, but nothing seems to be working (yes I am new to programming lol). I have the following code: SysLength = defaultdict(list) #empty dictionary for x in SystemDict: length = len(SystemDict[x]) #obtains length of each system SysLength[x].append(length) #adds system and length to the dictionary SysMin = sorted(SysLength, key=SysLength.get) #sorts systems from smallest to largest emailDict = defaultdict(list) #empty dictionary for x in SysMin: #cycles through lowest system first for email in SystemDicto3[x]: #cycles through email in the lowest system emailDict[email] = 0 #adds email to dictionary and sets it equal to 0 for x in SysMin: for email in SystemDicto3[x]: if emailDict[email] &lt; 3: #if count is below 3, pass email through emailDict[email] += 1 #adds 1 to each email passed through SystemDictu4[x].append(email) I am having an issue with this line: SystemDictu4[x].append(email) What I am looking to do is append 'email' to the key value 'x'. SystemDictu4 is a defaultdict with 1000's of entries under each key, and I need to add the email variable to those keys. I am getting the following error: TypeError: cannot concatenate a non-NDFrame object
tagged with: python

http://stackoverflow.com/q/49204295
score: 1
has answer: http://stackoverflow.com/a/49204775
answer count: 1
favorite count: 0
tagged with: python-3.x
type: Question
has body: I tried to show the images when the mouse hover the graph, but it never shows the images. Here is a part of my code. source = ColumnDataSource(data=dict( x=, y=, imgs=icon_data)) The url of each icon is contained in the icon_data. tooltips = """ @x{%m/%d %p%I} """ hover_format = {'x' : 'datetime'} return HoverTool(tooltips=tooltips, formatters=hover_format, mode='vline') Here is the function to return hovertool. And the graph shows like this The hover window Anyone who knows the reason?
tagged with: python
has title: Bokeh: Images for hovertool doen't show
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49204775
downvote count: 0
upvote count: 1
tagged with: bokeh

http://stackoverflow.com/comment/85422472
has text: Yup, I understand just until the point where you do the for cycle. How do you know if it is going along the arrows?
comment on: http://stackoverflow.com/a/49208763
score: 0
type: AnswerComment
type: Comment

avro
type: Tag
tags question: http://stackoverflow.com/q/49278649
tag name: avro

http://stackoverflow.com/comment/85263603
has text: Geez, dude, chillax. Sorry then..
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49125636
type: Comment

http://stackoverflow.com/q/49164985
score: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49165069
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has title: How to load module into python with argv
possible better answer: http://stackoverflow.com/a/49166995
has answer: http://stackoverflow.com/a/49166995
tagged with: python
has body: I want to load oneRunParams.py into my current program but won't know where it is till I run it. I want to have it as an input argument, accessed through argv. I was using: from oneRunParams import * I now want to replace this with something that will do the same only with the path to oneRunParams specified.
has answer: http://stackoverflow.com/a/49165069
type: AnsweredQuestion
tagged with: python-import
answer count: 2

http://stackoverflow.com/comment/85333739
score: 0
has text: @AkshayJ, no need - this is a duplicate.
type: QuestionComment
comment on: http://stackoverflow.com/q/49163884
type: Comment

http://stackoverflow.com/comment/85425006
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49210113
has text: 'cos you might be after: `df.time.sub(df.time.shift(-1) == df.time)`...

http://stackoverflow.com/comment/85584410
comment on: http://stackoverflow.com/q/49278425
type: Comment
type: QuestionComment
score: 1
has text: Do you really **have** to use bjam to build your projects? As in, is that what you would normally use? It's just that it's by no means a necessity to use boost.python, and this often tends to confuse people unnecessarily.

http://stackoverflow.com/q/49179377
downvote count: 1
possible better answer: http://stackoverflow.com/a/49179510
has title: How do I use one object from one function in another function in the same class
favorite count: 0
type: Question
tagged with: object
has answer: http://stackoverflow.com/a/49179510
has answer: http://stackoverflow.com/a/49179527
upvote count: 2
has body: I want to use "img" of browse_file() in grey_scale(). I am able to use band_count(type Int) but when I am trying to use "img" in grey_scale(), I'm getting the following error: the type of "img" is class 'spectral.io.bilfile.BilFile' Traceback (most recent call last): File "main.py", line 50, in grey_scale view = imshow(img,(bandGrey,))` NameError: global name 'img' is not defined` My code: def browse_file(self,MainWindow): file = str(QtGui.QFileDialog.getOpenFileName(self,"Select Directory")) img = envi.open(file) #load image to img object. band_info = str(img.read_band) band_count = int((band_info.split(start))[1].split(end)[0]) view = imshow(img,(1,0,0)) def grey_scale(self): bandGrey = self.spinBox_grey_band.value() print bandGrey #working view = imshow(img,(bandGrey,)) #error
tagged with: python
tagged with: class
type: AnsweredQuestion
answer count: 3
accepted answer: http://stackoverflow.com/a/49179514
score: 1
has answer: http://stackoverflow.com/a/49179514
tagged with: loops

http://stackoverflow.com/q/49208047
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85420986
tagged with: django-views
has comment: http://stackoverflow.com/comment/85421116
has comment: http://stackoverflow.com/comment/85420929
tagged with: python
has comment: http://stackoverflow.com/comment/85420964
type: AnsweredQuestion
has title: DJango form.is_valid() function only clean the first form in an if statement
has comment: http://stackoverflow.com/comment/85421044
accepted answer: http://stackoverflow.com/a/49208143
score: 1
has comment: http://stackoverflow.com/comment/85420940
has comment: http://stackoverflow.com/comment/85421020
answer count: 1
downvote count: 0
has body: I notice that forms.is_valid only clean form for the first form in an if statement. Example code : if not user_detail_form.is_valid() and not user_location_form.is_valid(): return redirect('account:profile') Accessing cleaned data of user_detail_form works but when accessing cleaned data of user_location_form, it throws an error stating that cleaned_data does not exists. My question is What causes this? and is there a workaround for this?
tagged with: django
has answer: http://stackoverflow.com/a/49208143
upvote count: 1
linked to: http://stackoverflow.com/q/2580136

http://stackoverflow.com/comment/85560032
has text: I would avoid making `__repr__` the easy-to-read option. There's an in depth discussion [here](https://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python), but the main point is that `__repr__` should be unambiguous, and `__str__` should be human readable.
score: 3
type: Comment
comment on: http://stackoverflow.com/a/49278639
type: AnswerComment

http://stackoverflow.com/q/49140389
type: AnsweredQuestion
has title: Problems accessing page with python requests
score: 0
answer count: 1
tagged with: python-requests
type: Question
has body: I'm trying to extract the sector of a stock for a ML classification project. If I go to the following page: https://www.six-swiss-exchange.com/shares/security_info_en.html?id=CH0012221716CHF4 I get (on the screen) some information about this stock (it changes, with the id code - I just pick the first one of the list). However, none of the information is available on a regular request. (The html page contains mostly javascript functions) What I need is on the "Shares Details" tab (ICB Supersector at the bottom of the page). Once again nothing is available with a regular requests. I looked into what happens when I click this tab and the desired request is inside the url: http://www.six-swiss-exchange.com/shares/info_details_en.html?id=CH0210483332CHF4&amp;portalSegment=EQ&amp;dojo.preventCache=1520360103852 HTTP/1.1 However, if I use this url directly, I get an 403 error from requests but work from a browser. I usually don't have any problems with this sort of things but in this case, do I have to submit cookies or any other information to access that page - no login is required and it can be easily accessed from any browser. I am thinking 1) make a first request to the url that works, 2) store the cookie they send you (I don't know how to do that really) and 3) make a second request to the desired url. Would this work? I tried using request.session() but I'm not sure if this is the solution or if I implemented it properly. If anyone has dealt with that sort of problem, I would love any pointers in solving this. Thanks.
accepted answer: http://stackoverflow.com/a/49141105
tagged with: python
has answer: http://stackoverflow.com/a/49141105

http://stackoverflow.com/q/49175575
tagged with: recursion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85356128
answer count: 0
score: 1
has title: recursive binary search with python
has comment: http://stackoverflow.com/comment/85356238
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
has body: Wrote this code in comp sci class and I cant get it to work. Its supposed to be a recursive binary search method... Any idea why I can't get it to work? arr = [1,10,12,15,16,122,132,143,155] def binarysearch(arr,num): arr2 = [] for i in range (len(arr)/2): arr2.append(0) if (arr[len(arr)/2]&gt;num): for x in range (len(arr)/2,len(arr)): arr2[x-(len(arr)/2)]=arr[x] binarysearch(arr2,num) if(arr[len(arr)/2]&lt;num): for x in range(0, len(arr) / 2 ): arr2[x] = arr[x] binarysearch(arr2, num) if(len(arr)==1): if(arr[0]==num): return 1 else: return 0 num = raw_input("put number to check here please: ") if(binarysearch(arr,num)==1): print "true" else: print "false"
linked to: http://stackoverflow.com/q/17778372
downvote count: 0
has comment: http://stackoverflow.com/comment/85356200
tagged with: python
linked to: http://stackoverflow.com/q/19989910
has comment: http://stackoverflow.com/comment/85357863

http://stackoverflow.com/q/49157421
has body: I have 2 data frames df1 = pd.DataFrame({'id':[1,2,3],'date':['2015-12-01','2016-02-02','2017-05-01']}) df1 date id 0 2015-12-01 1 1 2016-02-02 2 2 2017-05-01 3 df2 = pd.DataFrame({'id':[1,2,3,1,2,3],'book_date':['2014-08-03','2016-01-12','2017-08-01','2015-02-01','2015-05-01','2016-09-01']}) df2 book_date id 0 2014-08-03 1 1 2016-01-12 2 2 2017-08-01 3 3 2015-02-01 1 4 2015-05-01 2 5 2016-09-01 3 I want to join both data frames and for each ID in df1 i would like to get all book_date from df2 where book_date in df2 is in the range of past one year to date in df1. so for id 1 i want only 2015-02-01 but not 2014-08-03
has title: Pandas Data frame Finding data related to rolling one year
tagged with: dataframe
tagged with: python
tagged with: date
type: AnsweredQuestion
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49157806
upvote count: 1
has answer: http://stackoverflow.com/a/49157806
favorite count: 0
type: Question

http://stackoverflow.com/comment/117168270
has text: I successfully bypassed the onboard MCU improving accuracy (the majority of error was due poor coding of MCU probably some interrupt messing with timing). The resulting error is ~0.1mm and ~4 mm. The ~4 mm is wavelength of received signal after processing and depends on reflective surface quality and distance (its getting worse the more far it is) because the analog processing part of the sensor is really weird and first and last period get screwed in amplitude so it is sometimes not accepted as signal causing measuring the next period (so the distance jumps by ~4 mm)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49185964
score: 0

http://stackoverflow.com/a/49218410
answers question: http://stackoverflow.com/q/49218302
downvote count: 0
score: 62
type: Answer
upvote count: 62
has body: get(key[, default]): return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError. d = {'a' :1, 'c' :2} print(d.get('b', 0)) # return 0 print(d.get('c', 0)) # return 2 pop(key[, default]) if key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised. d = {'a' :1, 'c' :2} print(d.pop('c', 0)) # return 2 print(d) # returns {'a': 1} print(d.get('c', 0)) # return 0 NB: Regarding best practice question, I would say it depends on your use case but I would go by default for .get unless I have a real need to .pop

http://stackoverflow.com/q/49229774
linked to: http://stackoverflow.com/q/49132301
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/49230018
accepted answer: http://stackoverflow.com/a/49230018
downvote count: 1
has comment: http://stackoverflow.com/comment/85463056
has answer: http://stackoverflow.com/a/49230098
favorite count: 0
possible better answer: http://stackoverflow.com/a/49230098
has answer: http://stackoverflow.com/a/49229894
type: Question
has title: Calculating sum and export to a file , based on the random number of inputs of a column
has answer: http://stackoverflow.com/a/49230219
answer count: 5
has answer: http://stackoverflow.com/a/49229943
has body: This is a repost of my previous request (Summing up the total based on the random number of inputs of a column). But in this question, I had requested to provide the solution without using pandas library. The problem is same as before. I need to sum up the "value" column amount for each value of col1 of the File1 and export it to an output file. I'm new in python and need to do it for thousands of records. File1 col1 col2 value 559 1 91987224 2400000000 559 0 91987224 100000000 558 0 91987224 100000000 557 2 87978332 500000000 557 1 59966218 2400000000 557 0 64064811 100000000 Desired Output: col1 Sum 559 2500000000 558 1000000000 557 3000000000 Thanks in advance. P.S : I can't use the pandas library due to permission issues.I tried the following code. Sharing my effort till now: import csv fin = open("File1.txt","r") list_txid = {} amount_tx = {} for line in fin: line = line.rstrip() f = line.split("\t") txid = f[0] amount = int(f[3]) fin.close() for txid in list_txid: amount_tx[txid] += amount print("{0}\t{1:d}\n".format(txid, amount_tx[txid]))
tagged with: python
score: -1

http://stackoverflow.com/q/49232773
upvote count: 2
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 1
tagged with: schedule
has comment: http://stackoverflow.com/comment/85469563
favorite count: 0
has comment: http://stackoverflow.com/comment/85469092
type: Question
has comment: http://stackoverflow.com/comment/85469446
has answer: http://stackoverflow.com/a/49233080
has body: I am currently working on a program that needs to run every 14 days. I have looked into Schedule which works fine, but I have a few doubts about how to go about this. I will create a service which will handle the execution of the python program itself on a CentOS 7 system. The issue here is that every 14 days I will run a function that generates a lot of email addresses and send them to a support entity. I am afraid that if something unintended happens, and the program restart - the support entity will get spammed with emails outside the time frame in which they should receive emails. As far as I can tell, Schedule does not have any way of determining if the program has restarted, and therefore a reboot of either the system or the service will cause this behaviour. Would it be a correct solution to write a date to a text file after each completed function run, and then check that text file once a day to determine whether the function should run or not? This method would survive a service and/or system reboot, but is it a "correct" way of doing it? ****UPDATE**** Having the cronjob run on specific days of the month (for example 1st and 15th.) is not sufficient. This could cause gaps in the data which the program processes. The script makes a call which pulls data from 14 days back, and this is the maximum number of days supported by the script (licensing and stuff, can't be changed so not that important except that it is a limitation). So it need to run on lets say odd or even week numbers (to get 14 days). Any ideas on how to accomplish this given this new information?.
has title: Python scheduled task to run every 14 days
tagged with: python

http://stackoverflow.com/q/49274833
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
tagged with: geopandas
has answer: http://stackoverflow.com/a/49274930
accepted answer: http://stackoverflow.com/a/49274930
has body: I have problem to analyse vincenty distance because the format is object and have km metrics in there, I want to analyse further. I want to convert vincenty distance to float format Here's the data customer_id lat_free long_free lat_device long_device radius timestamp 7509 -6.283468 106.857636 -7.802388 110.368660 1264.000000 2017-12-14 21:18:40.327 7509 -6.283468 106.857636 -7.804296 110.367192 14.000000 2017-12-15 20:02:21.923 Here's my code from geopy.distance import vincenty df['Vincenty_distance'] = df.apply(lambda x: vincenty((x['lat_free'], x['long_free']), (x['lat_device'], x['long_device'])), axis = 1) This is the result customer_id lat_free long_free lat_device long_device radius timestamp Vincenty_distance 7509 -6.283468 106.857636 -7.802388 110.368660 1264.000000 2017-12-14 21:18:40.327 422.7123873310482 km 7509 -6.283468 106.857636 -7.804296 110.367192 14.000000 2017-12-15 20:02:21.923 422.64674499172787 km I need to convert Vincenty_distance to float
tagged with: python
has title: How do I convert vincenty distance to float in pandas dataframe
type: Question
answer count: 2
upvote count: 5
tagged with: geopy
score: 5
downvote count: 0
has answer: http://stackoverflow.com/a/49274946
possible better answer: http://stackoverflow.com/a/49274946

http://stackoverflow.com/q/49136427
type: Question
has answer: http://stackoverflow.com/a/49138810
has title: Python networkx weighted graph not taking into account weight of node in shortest path calculation?
tagged with: python-3.x
tagged with: shortest-path
has comment: http://stackoverflow.com/comment/85278033
has comment: http://stackoverflow.com/comment/85278284
downvote count: 0
has comment: http://stackoverflow.com/comment/85278360
tagged with: python
has body: I'm using Python 3 and Networkx 1.11. I make a weighted graph, with weights on the edges and some nodes, but when I calculate the weight of a shortest path, the weight of the node is not taken into account (code below). Anyone know how to ensure the node weight is considered? Thanks! Sam import networkx as nx from matplotlib import pyplot as plt # Set up a station map all_stations = ['a','b','c','d','e'] interchange_stations = ['b'] routes = {'a':{'b':2}, 'c':{'b':2}, 'b':{'d':2}, 'd':{'e':2}} print(routes) # Make a network graph G = nx.Graph() # Add all the nodes (stations) for station in all_stations: weight = 0 if station in interchange_stations: weight = 5 G.add_node(station, weight=weight) print(G.nodes(data=True)) # Iterate through each line and add the time between stations for name1, value in routes.items(): for name2, time in value.items(): if name1 == name2: continue G.add_edge(name1, name2, weight=time) print(G.edges(data=True)) # Work out the minimium distance between all stops route_times = nx.all_pairs_dijkstra_path_length(G) # Work out the minimum path between all stops route = nx.all_pairs_dijkstra_path(G) print(route['a']['e']) # Returns: ['a', 'b', 'd', 'e'] print(route_times['a']['e']) # Returns: 6 (should be 2+2+2+5)
tagged with: networkx
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85278328
tagged with: weighted-graph
has comment: http://stackoverflow.com/comment/85278463
answer count: 1
has comment: http://stackoverflow.com/comment/85278309
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/49138810
favorite count: 0
has comment: http://stackoverflow.com/comment/85277988

http://stackoverflow.com/q/49151031
has comment: http://stackoverflow.com/comment/85314414
has comment: http://stackoverflow.com/comment/88230110
has comment: http://stackoverflow.com/comment/85310113
has body: I loaded a 3d File with PyAssimp then I changed some vertices position and when I exported it all modification were ignored This is an example of what I wrote: &gt;&gt;&gt; import pyassimp &gt;&gt;&gt; scene = pyassimp.load('D:/test.3ds') &gt;&gt;&gt; v = scene.meshes[2].vertices &gt;&gt;&gt; v = [ [p[0], p[1], p[2]+200] for p in v ] &gt;&gt;&gt; scene.meshes[2].vertices = v &gt;&gt;&gt; print scene.meshes[2].vertices [[-13.360946655273438, -19.980607986450195, 200.0], [-13.360946655273438, 19.980606079101562, 200.0], ……… &gt;&gt;&gt; pyassimp.export(scene,'D:/ExportedFile.gltf','gltf2') but when I load the file there are no changes! Thanks.
tagged with: assimp
type: Question
upvote count: 2
has title: PyAssimp ignores all modification before the export
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/56140479
has comment: http://stackoverflow.com/comment/85340512
has comment: http://stackoverflow.com/comment/85306287
favorite count: 0
score: 2

http://stackoverflow.com/q/49183526
has comment: http://stackoverflow.com/comment/85372883
score: 0
upvote count: 1
has title: Python regex search between > and <
downvote count: 1
linked to: http://stackoverflow.com/q/12736074
favorite count: 0
has comment: http://stackoverflow.com/comment/85372969
type: Question
has comment: http://stackoverflow.com/comment/85372960
answer count: 0
duplicate of: http://stackoverflow.com/q/12736074
type: UnansweredQuestion
tagged with: python
tagged with: regex
has body: I have this: string = 'white-space:pre;"&gt;porttitor,&lt;span class="goog-inline-block" style="width:5.875px;height:16.8px"&gt;&amp;nbsp;&lt;/span&gt;massa&lt;span class="goog-inline-block" style="width:5.875px;height:16.8px"&gt;&amp;nbsp;&lt;/span&gt;dui&lt;span class="goog-inline-block" style="width:5.875px;height:16.8px"&gt;&amp;nbsp;' and I want this: ['porttitor,', '&amp;nbsp;', 'massa', '&amp;nbsp;', 'dui'] I have tried re.findall('^&gt;.*&lt;$', string) and re.findall('^\&gt;.*\&lt;$', string) but no luck. I have a non-regex workaround already, so I'm only looking for regex answers. Thanks!

http://stackoverflow.com/a/49366510
has body: d = testdata file = 'data/app_name/{}app_name.txt' n = 0 # to number the files for row in d.iteritems(): with open(file.format(row[0]), 'w') as f: f.write(str(row)) n += 1 Wouldn't you just grab the first column then? So row[0] would be your numerical value?
has comment: http://stackoverflow.com/comment/85735842
has comment: http://stackoverflow.com/comment/85906717
answers question: http://stackoverflow.com/q/49155609
has comment: http://stackoverflow.com/comment/85735929
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85934921
accepted answer of: http://stackoverflow.com/q/49155609
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85737076

http://stackoverflow.com/q/49233855
has comment: http://stackoverflow.com/comment/85471259
tagged with: python
has answer: http://stackoverflow.com/a/49234386
score: 2
type: AnsweredQuestion
tagged with: python-2.7
upvote count: 3
answer count: 1
has body: I just increase my sample to 12 and found axes.prop_cycle() has only 10 colors by default (I think it is tab10.). So I got IndexError: list index out of range. My simplified code. Each sample value is represented in each row of matrix matrix = np.random.randint(25, size=(12, 4)) for p in xrange(12): ax_eachp = plt.subplot2grid((protcount, 1), (p, 0), rowspan=1, colspan=1) ax_eachp.plot(matrix[p], color=colors[p]) Can I just add 2 more colors manually if I want to remain first 10 colors in tab10? or how to change to other qualitative color maps?
downvote count: 1
has comment: http://stackoverflow.com/comment/85471345
favorite count: 0
type: Question
tagged with: colors
has title: Matplotlib: add more colors to the default colors in axes.prop_cycle() manually?
linked to: http://stackoverflow.com/q/22676657
accepted answer: http://stackoverflow.com/a/49234386
tagged with: matplotlib

http://stackoverflow.com/q/49183196
type: UnansweredQuestion
has body: I wish to search a directory, and all contained subdirectories, for files with a substring contained within their name and one of three possible extensions Please can you help me edit the following code os.chdir(directory) files = glob.glob("**/*{}*.pro".format(myStr), recursive = True) I wish to find files with the extension .pro, .bd3 and .mysql I'm running Python 3.5
has answer: http://stackoverflow.com/a/49183573
favorite count: 0
downvote count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/85372289
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49183323
has comment: http://stackoverflow.com/comment/85372470
type: Question
has answer: http://stackoverflow.com/a/49183566
upvote count: 1
has comment: http://stackoverflow.com/comment/85372419
has title: Python search files with multiple extensions

http://stackoverflow.com/q/49262646
type: AnsweredQuestion
score: 0
has title: Do mysql querys in python with zip file
answer count: 1
tagged with: mysql
tagged with: mysql-connector
type: Question
accepted answer: http://stackoverflow.com/a/49262686
has body: Im trying to do some querys on my data base, but the file is to large and is spending to much time, exists some way to upload one zip file with those querys to my table? ps: the file have between 350Mb to 500Mb
has answer: http://stackoverflow.com/a/49262686
tagged with: python

http://stackoverflow.com/q/49273694
score: -2
downvote count: 2
has title: converting GMT to stftime using python
answer count: 1
has comment: http://stackoverflow.com/comment/85550402
has answer: http://stackoverflow.com/a/49274065
duplicate of: http://stackoverflow.com/q/466345
linked to: http://stackoverflow.com/q/466345
has body: I want to convert Wed, 14 Mar 2018 07:30:00 GMT to 2018/03/14 in python. I am getting unicode object has no attribute strftime error. Someone help me.
has comment: http://stackoverflow.com/comment/85550347
tagged with: python
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85550247
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49153714
linked to: http://stackoverflow.com/q/46701364
has comment: http://stackoverflow.com/comment/85312185
has comment: http://stackoverflow.com/comment/85360915
possible better answer: http://stackoverflow.com/a/49153997
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85324473
answer count: 2
has answer: http://stackoverflow.com/a/49153997
upvote count: 53
linked to: http://stackoverflow.com/q/23016610
tagged with: cpython
accepted answer: http://stackoverflow.com/a/49154022
downvote count: 2
has answer: http://stackoverflow.com/a/49154022
has comment: http://stackoverflow.com/comment/85337641
favorite count: 0
has comment: http://stackoverflow.com/comment/85327761
type: Question
has title: Why is the size of 2⁶³ 36 bytes, but 2⁶³-1 is only 24 bytes?
linked to: http://stackoverflow.com/q/40344159
score: 51
tagged with: python-internals
has comment: http://stackoverflow.com/comment/85360962
has body: Everything in Python is an object. So the size of an int in Python will be larger than usual. &gt;&gt;&gt; sys.getsizeof(int()) 24 OK, but why does it take 12 more bytes for 2⁶³ compared too 2⁶³ - 1 and not just one? &gt;&gt;&gt; sys.getsizeof(2**63) 36 &gt;&gt;&gt; sys.getsizeof(2**62) 24 I get that 2⁶³ is a long and 2⁶³-1 an int, but why 12 bytes of difference? No more intuitive, I tried some other things: &gt;&gt;&gt; a = 2**63 &gt;&gt;&gt; a -= 2**62 &gt;&gt;&gt; sys.getsizeof(a) 36 a is still stored as a long even if it could be in an int now. So that's not surprising. But: &gt;&gt;&gt; a -= (2**63 - 1) &gt;&gt;&gt; a = 2**63 &gt;&gt;&gt; a -= (2**63 - 1) &gt;&gt;&gt; a 1L &gt;&gt;&gt; sys.getsizeof(a) 28 A new size. &gt;&gt;&gt; a = 2**63 &gt;&gt;&gt; a -= 2**63 &gt;&gt;&gt; a 0L &gt;&gt;&gt; sys.getsizeof(a) 24 Back to 24 bytes, but still with a long. Last thing I got: &gt;&gt;&gt; sys.getsizeof(long()) 24 Question: How does the memory storage work in those scenarios? Sub-questions: Why is there a gap of 12 bytes to add what our intuition tells us is just 1 bit? Why are int() and long() 24 bytes, but long(1) is already 28 bytes and int(2⁶²)? NB: Python 3.X is working a bit differently, but not more intuitively. Here I focused on Python 2.7; I did not test on prior versions.
linked to: http://stackoverflow.com/q/4153852
tagged with: python

http://stackoverflow.com/a/49231798
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49230486
score: 2
has comment: http://stackoverflow.com/comment/85471514
type: Answer
has body: manage.py test doesn't run a "test server" at all, and nothing is listening on any port. Testing emails is fully covered in the docs - as that page shows, you can do from django.core import mail and then check mail.outbox.
answers question: http://stackoverflow.com/q/49230486
upvote count: 2

http://stackoverflow.com/q/49182233
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49184176
tagged with: pyqt
score: 0
answer count: 1
has body: Hello Guys I have a question i have to write python script that will first display a qt4 window with push buttons text edit and some labels. Push buttons i have linked but when i click on my left button which is end of script it displays this: Traceback (most recent call last): File "Skrypt.py", line 18, in Koniec QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) TypeError: arguments did not match any overloaded call: question(QWidget, str, str, buttons: Union[QMessageBox.StandardButtons, QMessageBox.StandardButton] = QMessageBox.Ok, defaultButton: QMessageBox.StandardButton = QMessageBox.NoButton): argument 1 has unexpected type 'bool' question(QWidget, str, str, int, button1: int = 0, button2: int = 0): argument 1 has unexpected type 'bool' question(QWidget, str, str, str, button1Text: str = '', button2Text: str = '', defaultButtonNumber: int = 0, escapeButtonNumber: int = -1): argument 1 has unexpected type 'bool' when i click on right which will be a pylab script which will get value from text edit it displays this : File "Skrypt.py", line 26, in Zatwierdz a = int(uiplot.textEdit()) TypeError: 'QTextEdit' object is not callable i don't know how to fix that because this is my first time in qt4 so if anyone could help me i will appreciate that Here is the code from script which will display the function using matplotlib import skrypt1 import pylab import skrypt1 from pylab import * import sys from PyQt4 import QtGui, QtCore if __name__ == "__main__": app = QtGui.QApplication(sys.argv) def Koniec(self): global wybor wybor = QtGui.QMessageBox.question(self, 'Koniec', "Na Pewno chcesz wyjsc ?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) if wybor == QtGui.QMessageBox.Yes: sys.exit() else: pass def Zatwierdz(self): x = pylab.arange(-10, 10.5, 0.5) a = int(uiplot.textEdit()) y1 = [i / -3 + a for i in x if i &lt;= 0] y2 = [i**2 / 3 for i in x if i &gt;= 0] x1 = [i for i in x if i &lt;= 0] x2 = [i for i in x if i &gt;= 0] pylab.plot(x1, y1, x2, y2) pylab.title('Wykres f(x)…
type: Question
has comment: http://stackoverflow.com/comment/85371190
has title: Python-PyQt4 QTextEdit
tagged with: pyqt4
has answer: http://stackoverflow.com/a/49184176
tagged with: python

http://stackoverflow.com/q/49182766
has title: Rotate cell's text when using pd.DataFrame.to_excel?
has comment: http://stackoverflow.com/comment/85386773
tagged with: python
has body: I'm working on a program and one of the needed features is to take a pandas dataframe and exports it to excel. This part works fine. When exporting, though, I need some of the cells to have their text rotated to be vertical rather than the default horizontal arrangement. Here's what I have so far: output = BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') filename = "Data for {} at {} on {}".format(item_no, loc, date) columns = [('A:A', 18), ('B:B', 4), ('C:C', 18), ('D:Y', 20), ('Z:Z', 18), ('AA:AA', 12), ('AB:AB', 18), ('AC:AC', 12), ('AD:AD', 4), ('AE:AF', 18), ('AG:AG', 11), ('AH:AK', 16), ('AL:AL', 10), ('AM:AN', 14.5)] df = fetch_data(item_no, loc, date) df.to_excel(writer, index=False, sheet_name='Sheet1') for col, width in columns: writer.sheets['Sheet1'].set_column(col, width) writer.save() writer.close() output.seek(0) I know that the xlsxwriter library has format.set_rotation() but from what I can tell, this is only used when you use worksheet.write(..., format) rather than after pandas has written each cell to the sheet. How would I go about getting certain of the cells to orient text vertically (90 degree rotation) rather than horizontally? In particular, I'm interested in rotating the text in cells D1:Y1.
has comment: http://stackoverflow.com/comment/85371677
type: AnsweredQuestion
score: 4
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49186002
tagged with: xlsxwriter
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49186002
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
linked to: http://stackoverflow.com/q/22352907

http://stackoverflow.com/comment/85257505
score: 0
type: AnswerComment
has text: Hi,It works but it unable to remove the 'u ` in the list [u' ', u' ', u' Bard1 Life Sciences Limited ', u' Gold' , u' Basic Materials', u' ASX', u' 7'..]`
comment on: http://stackoverflow.com/a/49126398
type: Comment

http://stackoverflow.com/q/49235259
type: UnansweredQuestion
has title: What is a good hashable python dict-like object for managing configuration parameters?
score: 0
tagged with: hashable
has comment: http://stackoverflow.com/comment/85478240
has body: In order to cache functions (right now I'm using klepto for that), I'm passing a confguration object cfg to the functions, s.t. the return value is only calculated, when cfg changes. Therefore, cfg has to be hashable and hash(cfg1) == hash(cfg2) if cfg1 == cfg2. I also would love to access the config parameters via dot-notation, e.g. cfg.para1. Nested entries would be nice, but one level is enough and I'm fine with dict and list being the only unhashable objects in cfg. I want to do something like this: from klepto import lru_cache from klept.keymaps import hasher class MyClass: def __init__(self, cfg) self.cfg = cfg def my_func(self): return self._my_func(self.cfg) @lru_cache(keymap=hasher, ignore=(self,)) def _my_func(self, cfg): a = cfg.a b = cfg.b.c[0] return expensive_func(a, b) cfg_dic = { 'a': 1, 'b': {'c': [1,2,3]} } cfg = give_me_the_hashable_object_i_need(cfg_dic) my_obj = MyClass(cfg) my_obj.my_func() #evaluate only if cfg was not (recently) used before First try Use a Box() object from the package python-box, initialized by a regular (nested) python dict cfg_dic: from box import Box cfg = Box(cfg_dic, frozen_box=True, box_it_up=True) Second try Make OrderedDicts from dic and its entries (after turning it into tuples of tuples, ..) before initializing the Box like this: from collections import OrderedDict from box import Box def to_tuple(dic_or_list): l = [] if isinstance(dic_or_list, list): for v in sorted(dic_or_list): try: hash(v) l.append(v) except TypeError: l.append(to_tuple(v)) elif isinstance(dic_or_list, dict): for k, v in sorted(dic_or_list.items()): try: hash(v) l.append((k, v)) except TypeError: l.append((k, to_tuple(v))) else: raise ValueError('argument must be one of "dict", "list"') return tuple(l) def second_level_odict(tup): if len(tup) == 2: k_1, v_1 = tup if isinstance(v_1, tuple): for v_2 in v_1: if len(v_2) != 2: return (k_1, v_1) return (k_1, (OrderedDict(v_1))) else: return (k_1, v_1) else: return tup def first_level_odict(tup): l =…
tagged with: python
tagged with: dictionary
tagged with: caching
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/85473824

http://stackoverflow.com/comment/85515117
comment on: http://stackoverflow.com/a/49253627
score: 0
type: Comment
type: AnswerComment
has text: When you create a fresh `PoolManager`, it just hold an empty `pools`. Or when you `clear` a `PoolManager`, it will clear `pools`.

http://stackoverflow.com/comment/103888495
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49194902
has text: This is wrong. `lp__` is the log-*posterior* not the log-*likelihood*. Therefore `lp__` also includes contributions from your prior densities and any Jacobian adjustments necessary to allow sampling to happen on the unconstrained scale.

http://stackoverflow.com/comment/85497330
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49167525
type: Comment
has text: Sorry there is yet another glitch... the scale on the x-axis seems to be alright but the labels won't show..

http://stackoverflow.com/a/49211238
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49210078
has comment: http://stackoverflow.com/comment/85429182
type: Answer
has body: Have you tried a threshold on the image? This is a common way to binarize images, rather than trying to apply a random binomial distribution. You could try something like: binarized_brains = (brains &gt; threshold_value).astype(int) which returns an array of 0s and 1s according to whether the image value was less than or greater than your chosen threshold value. You will have to experiment with the threshold value to find the best one for your images, but it does not need to be normalized first. If this doesn't work well, you can also experiment with the thresholding options available in the skimage filters package.
score: 1
has comment: http://stackoverflow.com/comment/85432318

http://stackoverflow.com/comment/85469532
has text: Do you want to capture the 'Harry Potter' part here?
type: Comment
comment on: http://stackoverflow.com/q/49233067
score: 0
type: QuestionComment

http://stackoverflow.com/q/49214989
score: 6
tagged with: macos
favorite count: 0
type: Question
has title: Access file in external hard drive using python on mac
has answer: http://stackoverflow.com/a/49215074
has body: I have a Python file in /Users/homedir/... and I want it to access a csv file on an external hard drive. Does anyone know how to do this? I only need reading permission.
type: UnansweredQuestion
tagged with: io
has answer: http://stackoverflow.com/a/59804114
tagged with: python
answer count: 2
upvote count: 7
downvote count: 1

http://stackoverflow.com/q/49212869
linked to: http://stackoverflow.com/q/2659900
has answer: http://stackoverflow.com/a/49212898
has comment: http://stackoverflow.com/comment/85430682
answer count: 2
score: 2
upvote count: 2
tagged with: divide
has comment: http://stackoverflow.com/comment/85430348
downvote count: 0
has body: I want to divide a file in a two random halfs with python. I have a small script, but it did not divide exactly into 2. Any suggestions? import random fin = open("test.txt", 'rb') f1out = open("test1.txt", 'wb') f2out = open("test2.txt", 'wb') for line in fin: r = random.random() if r &lt; 0.5: f1out.write(line) else: f2out.write(line) fin.close() f1out.close() f2out.close()
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: File division into 2 random files
has answer: http://stackoverflow.com/a/49212909

http://stackoverflow.com/q/49199585
possible better answer: http://stackoverflow.com/a/49199711
has answer: http://stackoverflow.com/a/49199711
type: Question
tagged with: object
has body: I have a problem in understanding of the notion of static variables in Python classes. According to Static class variables in Python, whenever we define a variable outside a method and inside a python class, this variable is static. This means this variable can be accessed without any need to instantiate an object from a class and can be accessed by the class name directly. For example: class my_class: i=12 def __init__(self,j): self.j=j instance=my_class(10) my_class.i: &gt;12 instance.i: &gt;12 instance.i=13 instance.i: &gt;13 my_class.i: &gt;12 You can see that we can access the static variable i through both instance object and the class name. However, when we change the value of i for instance object it does not affect the value of the class(my_class.i is still 12). On the other hand, things totally change if we are working with array static variables. Considering the similar example: class my_class: i=[] def __init__(self,j): self.j=j instance=my_class(10) my_class.i: &gt;[] instance.i: &gt;[] instance.i.append(13) instance.i: &gt;[13] my_class.i: &gt;[13] You can see that when I change the variable for the array of instance object it also affects the class value. What is going on here? I would appreciate if someone could help me better understand this issue as it is not that much obvious to me. By the way, I have a Java background.
has title: Static variables in python classes
tagged with: python
tagged with: class
type: AnsweredQuestion
score: 0
tagged with: instance
answer count: 3
accepted answer: http://stackoverflow.com/a/49199619
linked to: http://stackoverflow.com/q/68645
has answer: http://stackoverflow.com/a/49199619
has answer: http://stackoverflow.com/a/49199650

http://stackoverflow.com/q/49243018
has comment: http://stackoverflow.com/comment/85566585
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/85569361
has comment: http://stackoverflow.com/comment/85592971
has comment: http://stackoverflow.com/comment/85574724
tagged with: python
has title: A follow-up to https://stackoverflow.com/questions/49239919/pandas-groupby-quantile-transform
has body: I noticed that sklearn does the wrong thing with NaNs: namely, it chokes. (there is a big discussion of fixing this here: https://github.com/scikit-learn/scikit-learn/issues/10404) I would like to transform the non-NaN data and leaves the NaNs alone, in input like: date ticker volume percent_change 2018-01-01 A 10000 0.01 2018-01-01 AA 15000 0.002 2018-01-01 AAPL 20000 NaN 2018-01-01 FB 10000 0.05 2018-01-02 A 10000 -0.01 2018-01-02 AA 15000 0.03 2018-01-02 AAPL 20000 -0.02 2018-01-02 FB 10000 -0.01 (maybe AAPL did not trade that day). Other than holding my breath for the sklearn guys to fix this, or implementing my own transformer (if done in python, this will be horribly slow, if done in C, painful to integrate), is there some other way of doing this?
type: Question
score: 0
answer count: 0
tagged with: pandas
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85578151

http://stackoverflow.com/comment/85397745
type: Comment
has text: thank you for your answer it works for the column class I will try to adapt for the table
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49196265

http://stackoverflow.com/a/74995071
downvote count: 0
answers question: http://stackoverflow.com/q/49268725
score: 2
type: Answer
has body: This effect was a surprise to me, too - thanks for pointing it out. Geeks for Geeks provides a simple way to force the superclass constructor to use an overridden method of the superclass by substituting A.do(self) for self.do() in the superclass constructor: class A: def __init__(self): A.do(self) def do(self): print("A") class B(A): def __init__(self): super().__init__() self.do() def do(self): super().do() print("B") b = B() This will produce A A B as required.
upvote count: 2

http://stackoverflow.com/q/49136400
has body: I have got some data from DB in List of List format which i am comparing with the Table displayed in UI. I Extracted UI Tables data into List of List and comparing DB vs UI. Here is the result. KEYWORD Collections . Lists Should Be Equal ${DataFromDB}, ${DataFromUI} Documentation: Fails if given lists are unequal. Start / End / Elapsed: 20180306 22:33:28.245 / 20180306 22:33:28.245 / 00:00:00.000 22:33:28.245 FAIL Lists are different: Index 0: ('3/6/2018', '16', '8', '50.00', '3024', '841', '27.81') != [u'3/6/2018', u'16', u'8', u'50.00', u'3024', u'841', u'27.81'] Index 1: ('3/5/2018', '16', '9', '56.25', '3024', '2114', '69.91') != [u'3/5/2018', u'16', u'9', u'56.25', u'3024', u'2114', u'69.91'] Index 2: ('3/4/2018', '16', '9', '56.25', '3024', '2224', '73.54') != [u'3/4/2018', u'16', u'9', u'56.25', u'3024', u'2224', u'73.54'] Index 3: ('3/3/2018', '16', '9', '56.25', '3024', '2132', '70.5') != [u'3/3/2018', u'16', u'9', u'56.25', u'3024', u'2132', u'70.50'] Index 4: ('3/2/2018', '16', '9', '56.25', '3024', '2112', '69.84') != [u'3/2/2018', u'16', u'9', u'56.25', u'3024', u'2112', u'69.84'] Index 5: ('3/1/2018', '16', '9', '56.25', '3024', '2112', '69.84') != [u'3/1/2018', u'16', u'9', u'56.25', u'3024', u'2112', u'69.84'] Index 6: ('2/28/2018', '16', '9', '56.25', '3024', '2112', '69.84') != [u'2/28/2018', u'16', u'9', u'56.25', u'3024', u'2112', u'69.84'] Index 7: ('2/27/2018', '16', '9', '56.25', '3024', '2112', '69.84') != [u'2/27/2018', u'16', u'9', u'56.25', u'3024', u'2112', u'69.84'] Though Values are same. But List should Be Equal function is failing.. Not sure if this is due to because of letter 'u' in the list from UI. Can any one tell what could have went wrong.? Edit: Also from RF doc {For example, Python tuple and list with same content are considered equal.} not sure why "Lists Should Be Equal" Keyword failing
has answer: http://stackoverflow.com/a/49136800
score: 0
answer count: 1
type: Question
tagged with: python-3.x
tagged with: robotframework
type: UnansweredQuestion
has title: List of List Comparisons fails
tagged with: python
linked to: http://stackoverflow.com/q/16296643

http://stackoverflow.com/q/49192744
has comment: http://stackoverflow.com/comment/85390245
tagged with: python
has comment: http://stackoverflow.com/comment/85390341
score: 0
has body: So I've been doing some basic code right now, following a tutorial, but I'm stuck on generating an actual table. My code is: from pandas import DataFrame, read_csv import matplotlib.pyplot as plt import pandas as pd import sys import matplotlib df = pd.read_csv("TB_burden_countries_2018-03-06.csv") df = df.set_index(['country']) df2 = df.loc["United States of America","e_mort_num"] df = pd.DataFrame(data = df2, columns=["e_mort_num"]) print(df) df.to_csv('example.csv') df.to_csv('example.html') And the output is: e_mort_num country United States of America 1400 United States of America 1400 United States of America 1300 United States of America 1200 United States of America 1100 United States of America 1000 United States of America 990 United States of America 890 United States of America 900 United States of America 790 United States of America 800 United States of America 730 United States of America 670 United States of America 700 United States of America 620 United States of America 620 United States of America 610 However, when I look at the html file I create, it doesn't generate the table as above, but shown below: country,e_mort_num United States of America,1400 United States of America,1400 United States of America,1300 United States of America,1200 United States of America,1100 United States of America,1000 United States of America,990 United States of America,890 United States of America,900 United States of America,790 United States of America,800 United States of America,730 United States of America,670 United States of America,700 United States of America,620 United States of America,620 United States of America,610 Any recommendations on what I'm doing wrong?
tagged with: pandas
has title: Python/Pandas - Creating a HTML table
has comment: http://stackoverflow.com/comment/85390283
type: Question
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/49184469
has comment: http://stackoverflow.com/comment/85374839
has comment: http://stackoverflow.com/comment/85407757
has comment: http://stackoverflow.com/comment/85451912
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85375020
has comment: http://stackoverflow.com/comment/85374959
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/85419861
has comment: http://stackoverflow.com/comment/85406665
accepted answer of: http://stackoverflow.com/q/49184422
has comment: http://stackoverflow.com/comment/85402355
has comment: http://stackoverflow.com/comment/85407091
has comment: http://stackoverflow.com/comment/85379898
has comment: http://stackoverflow.com/comment/85374936
answers question: http://stackoverflow.com/q/49184422
has comment: http://stackoverflow.com/comment/85451153
score: 1
has body: Using textvariable in Tkinter can be handy, but it requires thinking a bit in Tcl/Tk style instead of Python style. You may want to read up on it I'm not sure where the best docs are, but Entry and The Variable Classes in the old book are probably a good place to start. Anyway, a textvariable binding has to refer to a Tcl variable, like a StringVar. Somewhere before creating that Label with textvariable=cantidad1 you need to do something like this: cantidad1 = StringVar('0') And then, instead of this: cantidad1 = cursor.fetchone() … you have to do this: cantidad1.set(cursor.fetchone()) What you're doing is changing the name cantidad1 to refer to the new result, but what you need to do is leave it referring to the StringVar and change the value of the StringVar, so Tk can see it and update the label. While we're at it, I think you actually want something like cursor.fetchone()[0]; otherwise you're trying to use a row (probably a list or other sequence, not a string). Finally, you could use an IntVar here. That would allow you to initialize it to 0 instead of '0', but then of course you have to set it to int(spam) instead of just spam, and you may need some error handling to deal with what happens if the database returns Null. If all of this is Greek to you (or, worse, Tcl), the other option is to just not use Tk variables: cantidad = Label(ventana, text='0').grid(row=1, column=3) Notice that the difference here is that I set the initial text, rather than setting a textvariable. So now, every time you fetch new data, you'll have to manually update (re-config) the label's text, like this: cantidad1 = ... # code that just gets a normal Python string cantidad.config(text=cantidad1) This is much less idiomatic Tk code, and arguably less idiomatic Tkinter code—but it's a lot more Pythonic, so it may be easier for you to read/debug/write. (Notice that the first line is exactly what you instinctively wrote, which was wrong with your original design, hence your question, but …
has comment: http://stackoverflow.com/comment/85452386
has comment: http://stackoverflow.com/comment/85407347
has comment: http://stackoverflow.com/comment/85406298
has comment: http://stackoverflow.com/comment/85406188

http://stackoverflow.com/comment/85550422
type: AnswerComment
has text: yes otherwise it wont be able to recognize that class .
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49273409

http://stackoverflow.com/a/49122829
type: Answer
has body: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#values You could use values or values_list here to get the fields of the related model Term. For example expanding on your current request: To retrieve all the Terms' name and duration for the Courses in your queryset Course.objects.filter(students = request.user).values('term__name', 'term__duration') I am not sure what the fields are of your Term model, but you would replace name or duration with whichever you are trying to get at.
score: 0
answers question: http://stackoverflow.com/q/49122666

http://stackoverflow.com/q/49255421
upvote count: 1
has body: I have the following frame: df = pd.DataFrame(data={'id':[1,2,3],'x':[3,2,1]}).set_index('id') print df x id 1 3 2 2 3 1 I need to iterate the rows, so that for each id, we append the remaining rows, e.g. the output should be: x id 1 3 2 1 2 2 1 3 1 Ideally O(n) solution that generalizes to m columns.
has title: Pandas iterating over index and appending remaining rows
has answer: http://stackoverflow.com/a/49256602
has answer: http://stackoverflow.com/a/49257142
has comment: http://stackoverflow.com/comment/85517865
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
score: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/49256602
accepted answer: http://stackoverflow.com/a/49257142
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/comment/85324452
has text: @JimFasarakisHilliard because it shows that it is doable quickly and simply, so part of the answer "why" is because it wasn't considered necessary since the solution to this particular problem is easy.
score: 0
comment on: http://stackoverflow.com/a/49159335
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49148771
has body: I have a problem with getObject access from my lambda function (FrameWork serverless) to S3 service in AWS. here a sample of my code : import boto3 import csv def hello(event, context): s3 = boto3.resource('s3') bucket = s3.Bucket('myBucket') obj = bucket.Object(key='MOCK_DATA.csv') response = obj.get() lines = response['Body'].read().split() body = [] for row in csv.DictReader(lines): body.append(row) return body and in my serverless.yml, i gave to my lambda the full access to the bucket iamRoleStatements: - Effect: "Allow" Action: - "s3:*" Resource: - "arn:aws:s3:::myBucket" but when i run the code, i receive the error: START RequestId: a6c006b7-21e5-11e8-8193-c3378825927 Version: $LATEST An error occurred (AccessDenied) when calling the GetObject operation: Access Denied: ClientError Traceback (most recent call last): File "/var/task/handler.py", line 5, in hello response = obj.get() File "/var/runtime/boto3/resources/factory.py", line 520, in do_action response = action(self, *args, **kwargs) File "/var/runtime/boto3/resources/action.py", line 83, in __call__ response = getattr(parent.meta.client, operation_name)(**params) File "/var/runtime/botocore/client.py", line 317, in _api_call return self._make_api_call(operation_name, kwargs) File "/var/runtime/botocore/client.py", line 615, in _make_api_call raise error_class(parsed_response, operation_name) ClientError: An error occurred (AccessDenied) when calling the GetObject operation: Access Denied do you have any idea why the boto3 dosent not take the permission from the iam role ? Because its working only if i declare boto3 with private and access keys: s3 = boto3.resource('s3',aws_access_key_id='accesskey',aws_secret_access_key='privateKey') Thank you in advance
has title: Serverless AWS (Python) read from S3 : Access Denied
tagged with: amazon-web-services
favorite count: 0
has comment: http://stackoverflow.com/comment/85302433
type: AnsweredQuestion
tagged with: serverless-framework
accepted answer: http://stackoverflow.com/a/49149306
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/49149306
upvote count: 5
tagged with: python
tagged with: boto3
type: Question
score: 5
has comment: http://stackoverflow.com/comment/85302223
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85328620
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49161202
has text: Apologies for the format of the pictures, is there a better way to display dataframes?
score: 0

http://stackoverflow.com/q/49213205
has body: I am trying to automate a task through a Python script. The idea is to login as a regular user and then send a su command and switch to the root account. The reason I can't directly login as root is that SSHD doesn't allow root logins. Here's what I have: ip='192.168.105.8' port=22 username='xyz' password='abc' ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,port,username,password) print ("SSH connection established") stdin,stdout,stderr=ssh.exec_command('sudo fast.sh') outlines=stdout.readlines() outlines+=stderr.readlines() resp=''.join(outlines) print(resp) Now, I want to send the su command and echo the root password. I am aware this is not good practice but I need a quick and easy way to test this so I am OK with that. However, when I do this stdin,stdout,stderr=ssh.exec_command('su') and provide the password, I get an error su: must be run from a terminal Can some one help me to solve this. I am running Python script on my Windows laptop to ssh into a Linux device and then switch to the root user using the su command and echo the password so that I can run other commands as root. Thanks.
tagged with: sudo
upvote count: 3
score: 3
downvote count: 0
has title: Getting "must be run from a terminal" when switching to root user using Paramiko module in Python
linked to: http://stackoverflow.com/q/40142559
answer count: 1
linked to: http://stackoverflow.com/q/44276916
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49218212
type: UnansweredQuestion
tagged with: ssh
linked to: http://stackoverflow.com/q/33291631
tagged with: python
tagged with: paramiko
tagged with: su

http://stackoverflow.com/comment/85415263
type: Comment
has text: You're very welcome! In future posts, if you post a minimal example (as you did in the end) so that people can play with it, it helps a lot.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49204993

http://stackoverflow.com/q/49126457
has comment: http://stackoverflow.com/comment/85258975
answer count: 1
has answer: http://stackoverflow.com/a/49127876
has comment: http://stackoverflow.com/comment/85259683
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Finding values in a Dataframe in Python that follow a trend
tagged with: time-series
tagged with: python
has comment: http://stackoverflow.com/comment/85259633
type: AnsweredQuestion
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49127876
has body: I have a dataframe which contains information of compressors as follows: The Dataframe of compressors: I would like to know the loading time of each of the compressors. It can be computed by finding an occurrence of a set point (say 32000) after the most recent value of 0 in the ACTIVEPOWER column of the respective compressor and counting the number of rows between them (as each row represents a minute). How can I achieve this operation in pandas in python? d1 = {'ACTIVEPOWER_1': [23000, 34000 , 45000, 0, 34000, 32000, 132000, 45000, 30000, 0, 32000, 132000]} df1 = pd.DataFrame(data=d1) If the input is the above dataframe (df1) ,then the output should look something like df2 given below d2 = {'Loading Times': [ 3, 2]} df2 = pd.DataFrame(data=d2)
score: 0
has comment: http://stackoverflow.com/comment/85258710

http://stackoverflow.com/comment/85712605
score: 0
comment on: http://stackoverflow.com/a/49240983
type: Comment
type: AnswerComment
has text: @Bhu_24 Create a new question detailing what you have tried and what are the problems you have encountered.

http://stackoverflow.com/a/49137252
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49136617
score: 3
has comment: http://stackoverflow.com/comment/85305831
upvote count: 3
has comment: http://stackoverflow.com/comment/85310226
accepted answer of: http://stackoverflow.com/q/49136617
has comment: http://stackoverflow.com/comment/93246382
has body: I think these two things actually make some sense. The significance level or p-value in the Anderson-Darling test is extrapolated based on where the test statistic falls within the range of critical values. The further to the right that the test statistic falls, the more significantly you can reject the null hypothesis that they are from the same distribution. Note that for, say, 80-90 samples using your example distribution parameters, you see the test statistic (for normal1 vs. normal2) starts to be hugely larger than the largest critical value, which means the extrapolation of the significance is free to grow (hugely, as the exponential of a convex-up quadratic function from polyfit) towards infinity. So yes, for a large sample size, you'll be computing the exponential of some huge number and getting overflow. In other words, your data is so obviously not from the same distribution, that the significance extrapolation overflows. In such a case, you might bootstrap a smaller data set from your actual data, just to avoid overflow (or bootstrap several times and average the statistic). On the other end of the spectrum, when the sorted data sets are identical, it looks like some steps of the formula admits the possibility of negative values. Essentially this means the statistic is far to the left of the critical values, indicating a perfect match. Once again, the significance is calculated by extrapolation, but this time it extrapolates from the test statistic towards the smallest critical value, rather than going from the largest critical value towards the test statistic as for the mismatching case. Since the relative size of the statistic on the left just happens to be smaller (I'm seeing statistics of around -1.3 for using the same sample) relative to the smallest critical value (around 0.3), you get an extrapolation that is "merely" as huge as around 140%, instead of exploding exponentially large numbers ... but still seeing a significance value of 1.4 is a signa…
type: AcceptedAnswer

http://stackoverflow.com/q/49244298
tagged with: mayavi
type: Question
answer count: 0
type: UnansweredQuestion
has body: Basically this is the question - how to plot a transparent cube with given coordinates of two opposite corners. Surely something simple exists, but I cannot find it. I have tried using tvtk.visual.box, but it doesn't support transparency as far as I could tell.
tagged with: python
favorite count: 0
tagged with: vtk
score: 3
upvote count: 3
has title: How to plot a transparent cube with mayavi?
downvote count: 0
tagged with: enthought

http://stackoverflow.com/comment/85434262
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49214915
has text: Ideone is on the same SciPy version you're on, and NumPy 1.12.0. Are you sure you didn't accidentally alter `X` or `y`? If not, maybe you have a bad LAPACK.
type: Comment

http://stackoverflow.com/comment/85360005
comment on: http://stackoverflow.com/a/49175477
score: 0
type: AnswerComment
has text: Perfect, I really appreciate you having helped me, thank you!
type: Comment

http://stackoverflow.com/a/51443536
has body: You need to improve your contour detection. Eventually by not changing it, but by better pre-processing the earlier stage. Contour detection works better with more contrast and color separation in image. If you don´t have yet need to threshold you image with techniques like Simple Threshold, Adaptive or more smart techniques like Otsu's. Check Open CV document here. Besides that, for your case eventually need more advanced techniques like "Adaptive Thresholding Using the Integral Image", described here.
has comment: http://stackoverflow.com/comment/89857032
type: Answer
answers question: http://stackoverflow.com/q/49236146
score: 0

http://stackoverflow.com/a/49228576
score: 0
has comment: http://stackoverflow.com/comment/85473989
answers question: http://stackoverflow.com/q/49155366
type: Answer
has body: I think you're missing several pieces here. First, your client app (doesn't really matter whether it's Android, iOS, smart tv, etc.) needs to "hit" an "endpoint" that you create on the backend. This basically means that you need to create a url that can receive information that you're passing from your mobile client. You'll receive the info in your Flask app then open a DB connection and store it there. Your web page (looks like you're going with '/') will pull the necessary info from the database and display it. You'll need to figure out how your backend should accept the data (should it allow only that one android device? any android device?) and how it should store the data (only have one DB entry and keep overwriting it for every call to the service? new entry for every unique call to the service?) There are definitely other ways to do it and ways to cheat a bit but I think this is the approach you're going for which is a very typical pattern for a barebones system.

http://stackoverflow.com/a/51207922
score: 6
answers question: http://stackoverflow.com/q/49222636
type: Answer
upvote count: 6
has body: Nobody is using re! Time for an answer [ab]using the regular expression built-in module ;) import re Finding all the maximal substrings that are repeated repeated_ones = set(re.findall(r"(.{4,})(?=.*\1)", mystring)) This matches the longest substrings which have at least a single repetition after (without consuming). So it finds all disjointed substrings that are repeated while only yielding the longest strings. Finding all substrings that are repeated, including overlaps mystring_overlap = "abcdeabcdzzzzbcde" # In case we want to match both abcd and bcde repeated_ones = set() pos = 0 while True: match = re.search(r"(.{4,}).*(\1)+", mystring_overlap[pos:]) if match: repeated_ones.add(match.group(1)) pos += match.pos + 1 else: break This ensures that all --not only disjoint-- substrings which have repetition are returned. It should be much slower, but gets the work done. If you want in addition to the longest strings that are repeated, all the substrings, then: base_repetitions = list(repeated_ones) for s in base_repetitions: for i in range(4, len(s)): repeated_ones.add(s[:i]) That will ensure that for long substrings that have repetition, you have also the smaller substring --e.g. "sample" and "ample" found by the re.search code; but also "samp", "sampl", "ampl" added by the above snippet. Counting matches Because (by design) the substrings that we count are non-overlapping, the count method is the way to go: from __future__ import print_function for substr in repeated_ones: print("'%s': %d times" % (substr, mystring.count(substr))) Results Finding maximal substrings: With the question's original mystring: {'abcd', 'text', 'sample'} with the mystring_overlap sample: {'abcd'} Finding all substrings: With the question's original mystring: {'abcd', 'ample', 'mple', 'sample', 'text'} ... and if we add the code to get all substrings then, of course, we get absolutely all the substrings: {'abcd', 'ampl', 'ample', 'mple', 'samp', 'sampl', 'sample', 'text'} with the mystrin…
downvote count: 0

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

http://stackoverflow.com/q/49190186
has comment: http://stackoverflow.com/comment/85388321
has answer: http://stackoverflow.com/a/49190718
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85385736
tagged with: performance
answer count: 3
tagged with: operating-system
score: 1
has title: how to reduce running time in python?
downvote count: 0
has body: I have the following program which generates 100 million mac's and append it into the list. But the 100 million mac's generation and insertion itself takes ~7 Minutes in python??? import datetime def mac_gen(): hex_byte1=0 hex_byte2=0 hex_byte3=0 hex_byte4=0 hex_byte5=0 hex_byte6=0 hex_byte7=0 hex_byte8=0 hex_byte9=0 hex_byte10=0 hex_byte11=0 hex_byte12=0 total_mac = 0 for hex_byte_12 in range(0,16): for hex_byte11 in range(0,16): for hex_byte10 in range(0,16): for hex_byte9 in range(0,16): for hex_byte8 in range(0,16): for hex_byte7 in range(0,16): for hex_byte6 in range(0,16): for hex_byte5 in range(0,16): for hex_byte4 in range(0,16): for hex_byte3 in range(0,16): for hex_byte2 in range(0,16): for hex_byte1 in range(0,16): total_mac +=1; if total_mac &gt; number_of_mac_to_print: return mac_list.append("%X%X:%X%X:%X%X:%X%X:%X%X:%X%X" %(hex_byte_12,hex_byte11,hex_byte10,hex_byte9,hex_byte8,hex_byte7,hex_byte6,hex_byte5,hex_byte4,hex_byte3,hex_byte2,hex_byte1)) mac_list=list() number_of_mac_to_print = 100000000 print(datetime.datetime.utcnow()) mac_gen() print(datetime.datetime.utcnow()) print(len(mac_list)) Output: 2018-03-09 07:15:41.650460 &lt;--- time stamp before calling mac_gen method 2018-03-09 07:22:33.902744 &lt;--- time stamp after calling mac_gen method 100000000 . &lt;---- total entries. 100 million so question is: how to reduce the running time from 7 minutes to lowest as possible in python? if the same problem i am solving in C or C plus plus give please give me generrfic solution for that as well? when running the same code for 1 Billion mac it is terminating automatically i belive. and taking much more time. how to achive for 1 Billion mac generation? Thanks in advance
has comment: http://stackoverflow.com/comment/85385793
has comment: http://stackoverflow.com/comment/85394393
has answer: http://stackoverflow.com/a/49190723
favorite count: 0
has comment: http://stackoverflow.com/comment/85387532
has comment: http://stackoverflow.com/comment/85385605
type: Question
has comment: http://stackoverflow.com/comment/85385903
has comment: http://stackoverflow.com/comment/85402340
tagged with: network-programming
has answer: http://stackoverflow.com/a/49190912
tagged with: algorithm
type: UnansweredQuestion

http://stackoverflow.com/comment/85408914
comment on: http://stackoverflow.com/q/49201556
score: 0
type: Comment
type: QuestionComment
has text: Your test text has "Temperature (K)", but your regular expression is looking for "Temperature (C)". Last I checked, "(K)" doesn't match "(C)".

http://stackoverflow.com/comment/85497769
type: Comment
type: AnswerComment
has text: I am actually using PyCharm! When I get back into school tomorrow I'll see if I was ignoring any underlines or did anything to disable them.
score: 0
comment on: http://stackoverflow.com/a/49246917

http://stackoverflow.com/a/49150547
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49149491
has body: Both your classes extend [Python 2]: class unittest.TestCase(methodName='runTest'). According to [Python 2]: Skipping tests and expected failures Skipped tests will not have setUp() or tearDown() run around them. Skipped classes will not have setUpClass() or tearDownClass() run. Also, according to [Python 2]: setUpClass and tearDownClass: If you want the setUpClass and tearDownClass on base classes called then you must call up to them yourself. What happens: login.py: LoginPage is instantiated (and run) automatically by the unittest framework (unittest.main()) and setUpClass method is called - which adds the driver attribute to the LoginPage class - and (automatically, to) all its instances Company_Management.py: LoginPage is instantiated manually by you (em = login.LoginPage()), but the setUpClass method isn't called - and thus LoginPage (or any of its instances) doesn't have the driver attribute - hence your error. To fix it, manually call the method yourself, either: After instantiating the class (on the instance): em = login.LoginPage() em.setUpClass() On the class itself (better, before instantiating it) login.LoginPage.setUpClass() em = login.LoginPage()
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49149491

http://stackoverflow.com/comment/109719922
type: AnswerComment
has text: thats the error i get :'returned "Invalid value at 'data.values[0]' (type.googleapis.com/google.protobuf.ListValue), "20191213150000" Invalid value at 'data.values[1]' (type.googleapis.com/google.protobuf.ListValue), "20191213160000"'
comment on: http://stackoverflow.com/a/49243865
type: Comment
score: 0

http://stackoverflow.com/comment/85407122
type: Comment
type: QuestionComment
score: 2
has text: `json.load(source)` is, in fact, the correct way to load data from a json file. The problem must be in the files you're reading from. Please share their contents.
comment on: http://stackoverflow.com/q/49200983

http://stackoverflow.com/comment/85491894
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49243434
has text: @Simon I need it to create more dates and fill the columns with duplicates. The data is updated 1 time a month so I just want to create more dates in between
score: 0

http://stackoverflow.com/q/49216223
score: 0
has answer: http://stackoverflow.com/a/49216274
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
upvote count: 2
type: UnansweredQuestion
has body: Let us assume that, I have a Machine Learning model which uses the Tensorflow library and performs a function. And of course, the function requires input and provides some output. Which can be easily done on my terminal. Here comes the area where I need help, IO in the terminal is not what I wanted, I want to create a web application that has multiple functionalities. Let us only consider the area where my ML model has to work, say when I click a button after entering the inputs it runs the ML model back and provides me an output which I could display it on my web application. I can develop websites with NodeJs. Is there any possibility of integrating the ML model with my web application made of NodeJs? I tried running on some packages like child-process,python-shell nothing works, it gives me an error when it comes to the place of importing packages. Please give me suggestions on the Integration of the ML model with a NodeJS web application using MongoDB as a database. All I wanted is that my web application runs my ML model wherever necessary to obtain the results which I can display through my web applications. Also, provide information about technologies that can be easily integrated with the Machine learning model.
downvote count: 2
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/51316883
has title: Integration of Python ML Model with a web application
tagged with: node.js

http://stackoverflow.com/comment/85300276
comment on: http://stackoverflow.com/q/49147264
type: Comment
type: QuestionComment
has text: Can you show a hex dump of the problematic bytes? Copy/pasting your problem character gives me [U+30CF](http://www.fileformat.info/info/unicode/char/30cf/index.htm) which is 0xE3 0x83 0x8F in UTF-8. The error message looks like one or the other of the first two bytes is somehow dropped or missed.
score: 0

http://stackoverflow.com/a/49584133
has comment: http://stackoverflow.com/comment/86220662
answers question: http://stackoverflow.com/q/49255795
type: Answer
has body: I think you are not setting correct path sys.path.insert(0, '/FeedbackAnalysisService/Assemblies/nltk.zip') Try above instead and it should work.
score: 0

http://stackoverflow.com/a/49158534
score: 0
has comment: http://stackoverflow.com/comment/85322946
has body: I suspect that the module has successfully installed, but is dynamically linked against FFMPEG. You can obtain built distributions of FFMPEG from their website (https://www.ffmpeg.org/download.html). They provide both statically linked and dynamically linked builds, though it is going to be the dynamically linked one that is providing the dll's you need. Looking at my own copy of PyAV, it seems that the current release version (3.4.2) is the one that it is linked against. When you download it, it will have a name like ffmpeg-date-build-win64-shared. In the bin directory, you will find all the relevant DLLs. You can either add this directory to the PATH, or more easily, copy the DLLs to your python location.
answers question: http://stackoverflow.com/q/49153792
has comment: http://stackoverflow.com/comment/85322709
type: Answer
has comment: http://stackoverflow.com/comment/85322867

http://stackoverflow.com/comment/85391877
type: Comment
type: QuestionComment
score: 0
has text: I'm not overly familiar with Python syntax but can you make your insert statement parameterised? That will help
comment on: http://stackoverflow.com/q/49193680

http://stackoverflow.com/comment/85503065
comment on: http://stackoverflow.com/a/49243196
type: Comment
type: AnswerComment
score: 0
has text: Cygwin comes with SSH server. You should have mentioned that you have Cygwin in the first place.

http://stackoverflow.com/comment/85358009
type: AnswerComment
score: 0
has text: @Lindow please feedback to my answer
type: Comment
comment on: http://stackoverflow.com/a/49172668

http://stackoverflow.com/comment/85359753
type: QuestionComment
has text: A basic example would help make this a clearer question.
score: 2
comment on: http://stackoverflow.com/q/49177228
type: Comment

http://stackoverflow.com/q/49227051
has comment: http://stackoverflow.com/comment/85457967
tagged with: python
has answer: http://stackoverflow.com/a/49227656
type: Question
has comment: http://stackoverflow.com/comment/85462312
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/85458069
has comment: http://stackoverflow.com/comment/85458110
answer count: 1
has title: How to speedup binary transformation from integer values
accepted answer: http://stackoverflow.com/a/49227656
has body: I wrote the following method (in python 2.7) that generates a set of integers and transform them into binary representation. It takes self-explanatory two parameters: total_num_nodes and dim. It returns numpy matrix-like containing the binary representation of all these integers: def generate(total_num_nodes, dim): # Generate random nodes from the range (0, dim-1) nodes_matrix = [random.randint(0, 2 ** dim - 1) for _ in range(total_num_nodes)] # Removes duplicates nodes_matrix = list(set(nodes_matrix)) # Transforms each node from decimal to string representation nodes_matrix = [('{0:0' + str(dim) + 'b}').format(x) for x in nodes_matrix] # Transforms each bit into an integer. nodes_matrix = np.asarray([list(map(int, list(x))) for x in nodes_matrix], dtype=np.uint8) return nodes_matrix The problem is that when I pass very large values, say total_num_nodes= 10,000,000 and dim=128, the generation time takes really long time. A friend of mine hinted me that the following line is actually a bottleneck and it is likely to be responsible for the majority of computation time: # Transforms each node from decimal to string representation nodes_matrix = [('{0:0' + str(dim) + 'b}').format(x) for x in nodes_matrix] I cannot think of other faster method that can replce this line so that I get to speedup the generation time when it is running on a single processor. Any suggestion from you is really really appreciated. Thank you
has comment: http://stackoverflow.com/comment/85458159
type: AnsweredQuestion

http://stackoverflow.com/comment/104866328
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49153020
has text: Does this answer your question? [PyMongo/Mongoengine equivalent of mongodump](https://stackoverflow.com/questions/24610484/pymongo-mongoengine-equivalent-of-mongodump)

http://stackoverflow.com/q/49274161
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/85560157
has answer: http://stackoverflow.com/a/49278930
answer count: 1
favorite count: 0
tagged with: dask
type: Question
tagged with: http://stackoverflow.com/tag/csv
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
has title: Read tail by partition from CSV file with dask.dataframe
upvote count: 4
has body: With Dash we can easily read CSV files and take first lines with head, even in multiple partitions. import dask.dataframe as dd df = dd.read_csv('data.csv').head(n=100, npartitions=2) But I would like to read last lines of my CSV file on multiple partitions, something like this : import dask.dataframe as dd df = dd.read_csv('data.csv').tail(n=100, npartitions=2) Dask data.frame doesn't seem to support partition on tail method. In pandas I could manage it with skiprows, but this options seems not available in Dask.
score: 4
has comment: http://stackoverflow.com/comment/85552674

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

http://stackoverflow.com/comment/85327359
has text: The docs don't actually say to use the wildcard import. In fact, they start by showing the proper way, before stating many people do it the other way. It's a real pity that they chose to give examples that go against their very guidelines. <shrug> The import thing to remember is that the goal isn't to mimic the documentation, but rather to write good code. PEP8 has proven to be a valuable resource in helping you to write good code.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49155387
type: AnswerComment

http://stackoverflow.com/q/49277640
tagged with: dataframe
has answer: http://stackoverflow.com/a/49277918
has body: I am trying to return a specific item from a Pandas DataFrame via conditional selection (and do not want to have to reference the index to do so). Here is an example: I have the following dataframe: Code Colour Fruit 0 1 red apple 1 2 orange orange 2 3 yellow banana 3 4 green pear 4 5 blue blueberry I enter the following code to search for the code for blueberries: df[df['Fruit'] == 'blueberry']['Code'] This returns: 4 5 Name: Code, dtype: int64 which is of type: pandas.core.series.Series but what I actually want to return is the number 5 of type: numpy.int64 which I can do if I enter the following code: df[df['Fruit'] == 'blueberry']['Code'][4] i.e. referencing the index to give the number 5, but I do not want to have to reference the index! Is there another syntax that I can deploy here to achieve the same thing? Thank you!... Update: One further idea is this code: df[df['Fruit'] == 'blueberry']['Code'][df[df['Fruit']=='blueberry'].index[0]] However, this does not seem particularly elegant (and it references the index). Is there a more concise and precise method that does not need to reference the index or is this strictly necessary? Thanks!...
upvote count: 8
favorite count: 0
score: 8
type: Question
has answer: http://stackoverflow.com/a/49277927
possible better answer: http://stackoverflow.com/a/49277927
has title: How to extract values from a Pandas DataFrame, rather than a Series (without referencing the index)?
has answer: http://stackoverflow.com/a/69541512
has answer: http://stackoverflow.com/a/59182818
tagged with: python
accepted answer: http://stackoverflow.com/a/49277918
answer count: 4
type: AnsweredQuestion
downvote count: 0
tagged with: pandas

http://stackoverflow.com/a/49143918
downvote count: 0
has body: You rather should use fprintf(3) instead of mixing sprintf (which is unsafe, prefer snprintf(3)) with fputs. You really want to output whole lines (because textual protocols are so convenient to debug). And use readline on the Python side. At last, a FILE* obtained by popen(3) is not even guaranteed to be line-buffered (but could have a much larger buffer, perhaps 4Kbytes or more). You might set its buffer using setvbuf(3) but you really should flush explicitly the FILE* buffer with fflush(3). If you don't, the output could stay in the buffer for a long time (without any actual write(2) done by stdio functions like fprintf or fputs) so the pipe(7) stays empty. (so you have problems even on the C side) The program seems to hang at value = sys.stdin.read(). I guess that not a single byte was actually written by your C code (you could check by using strace(1)) because your fputs stayed in the buffer. You might need to wait a long time (perhaps 1000 seconds, to fill a buffer of a few kilobytes) to have it actually write something on the pipe, because you forgot the fflush . A popen-ed file should absolutely be pclosed. So you should replace your (incorrect) while loop with: while(1) { fprintf(fp, "%d\n", inc); inc++; fflush(fp); sleep(1); } And your loop should be exited somehow. Perhaps you might catch some signal(7) -probably SIGTERM- (but be sure to read signal-safety(7)). Be sure to pclose (to avoid zombie processes). (I am assuming you are on Linux or some other POSIX system)
has comment: http://stackoverflow.com/comment/85294077
score: 3
answers question: http://stackoverflow.com/q/49143718
type: Answer
accepted answer of: http://stackoverflow.com/q/49143718
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/comment/85319941
comment on: http://stackoverflow.com/a/49157516
type: AnswerComment
score: 0
type: Comment
has text: Docs say "Any *other* keyword arguments that are specified in the class definition are passed through to all metaclass operations described below." [Emphasis mine]. This implies that the metaclass keyword just doesn't figure outside the interpreter.

http://stackoverflow.com/a/49186002
accepted answer of: http://stackoverflow.com/q/49182766
score: 8
has comment: http://stackoverflow.com/comment/85396232
type: AcceptedAnswer
downvote count: 0
has body: You have the xlsxwriter objects from the dataframe writer object. So you could add a format and set it's properties. Then you can use it loop through writer.sheets['Sheet1'].set_column(col, width). If on the other hand you only want the column names rotated, you can opt to set header=False in df.to_excel() and then write out the column names, one-by-one in a loop. I've provided an example that illustrates this below. You could condition on the 'D1:Y1' if those are the only ones you want to rotate on import pandas as pd df = pd.DataFrame({"Name": ["A", "B", "C"], "Status": [1, 2, 3]}) writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter') columns = [('A:A', 18), ('B:B', 4), ('C:C', 18), ('D:Y', 20), ('Z:Z', 18), ('AA:AA', 12), ('AB:AB', 18), ('AC:AC', 12), ('AD:AD', 4), ('AE:AF', 18), ('AG:AG', 11), ('AH:AK', 16), ('AL:AL', 10), ('AM:AN', 14.5)] header_list = list(df.columns.values) df.to_excel(writer, index=False, header=False, startrow=1, sheet_name='Sheet1') workbook = writer.book format = workbook.add_format({}) format.set_rotation(90) for col, width in columns: writer.sheets['Sheet1'].set_column(col, width) for i in range (0, len(header_list)): writer.sheets['Sheet1'].write(0, i, header_list[i], format) workbook.close() Expected Output:
has comment: http://stackoverflow.com/comment/85401345
has comment: http://stackoverflow.com/comment/85379678
upvote count: 8
answers question: http://stackoverflow.com/q/49182766
type: Answer

http://stackoverflow.com/a/49216930
has body: You need to download and install Anaconda via their installer, at the end of the installation you'll get a prompt to install vscode. You can also install it via the navigator, check here https://visualstudiomagazine.com/articles/2018/02/22/vs-code-anaconda.aspx?m=1
score: 3
has comment: http://stackoverflow.com/comment/88004533
answers question: http://stackoverflow.com/q/49205467
type: Answer
upvote count: 3
downvote count: 0

http://stackoverflow.com/comment/85426319
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49209451
has text: Depending on what you mean by "basic" file handling, you might easily accomplish this with the python standard libary module `subprocess`. Does you chatbot just read and write to stdin and stdout?

http://stackoverflow.com/q/49188488
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49188533
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/49189694
tagged with: python
has answer: http://stackoverflow.com/a/49188533
tagged with: parsing
has comment: http://stackoverflow.com/comment/85383741
tagged with: python-2.7
answer count: 2
has title: JSON Parsing issue - Python
has body: So i have build a REST Client that returns JSON response. However, i have an issue, where the JSON output is not exactly what i need: Current Response: { "output": { "status": "Device 'Test' does not exist", "result": "null", "response": { "output": "success", "result": 204 } } } This output has an outermost enclosing "output" key, but i don't want that to be present. So basically i want my response to look like below: { "status": "Device 'Test' does not exist", "result": "null", "response": { "output": "success", "result": 204 } } I did try converting the JSON to Dict and then remove it, but no luck? any suggestions how to achieve this? Thank you
has answer: http://stackoverflow.com/a/49189694
type: Question

http://stackoverflow.com/comment/85422819
type: QuestionComment
has text: How can i use class as well, i want to use tag with class, how can i write this i tried `soup.find('span', '.productTitle')` not working
comment on: http://stackoverflow.com/q/49209123
score: 0
type: Comment

http://stackoverflow.com/a/49248790
downvote count: 0
has comment: http://stackoverflow.com/comment/85514237
answers question: http://stackoverflow.com/q/49248732
upvote count: 4
has comment: http://stackoverflow.com/comment/85501202
has comment: http://stackoverflow.com/comment/85501913
has body: Depends what you mean by "built-in". If you mean any of the C-implemented (in CPython) classes exposed as builtins (and in builtin), then no, none of them have a different metaclass.* But there are definitely classes in the stdlib that do. For example: &gt;&gt;&gt; type(collections.abc.Iterable) abc.ABCMeta To clarify: Other metaclasses are of course subclasses of type, so, by the normal inheritance rules, it's still true that isinstance(Iterable, type)—but it's not true that type(Iterable) == type. Which is what you were asking for in your question—a type for which type(T) returns &lt;type 'some_type_other_than_type'&gt;. * Not in 3.x, at any rate. Things were different in 2.x, where there were classic classes, and, once upon a time, "fake classes" that were actually functions that looked like type instances but weren't, and returned instances of a hidden type instance when called.
type: Answer
has comment: http://stackoverflow.com/comment/85515769
score: 4
has comment: http://stackoverflow.com/comment/85501154
has comment: http://stackoverflow.com/comment/85525894
accepted answer of: http://stackoverflow.com/q/49248732
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85501761

graph
tags question: http://stackoverflow.com/q/49271359
tags question: http://stackoverflow.com/q/49240453
tags question: http://stackoverflow.com/q/49136668
tags question: http://stackoverflow.com/q/49258982
tags question: http://stackoverflow.com/q/49152232
tags question: http://stackoverflow.com/q/49237889
tags question: http://stackoverflow.com/q/49220796
tags question: http://stackoverflow.com/q/49139968
tags question: http://stackoverflow.com/q/49212467
tags question: http://stackoverflow.com/q/49173854
tags question: http://stackoverflow.com/q/49261149
tag name: graph
tags question: http://stackoverflow.com/q/49262391
type: Tag
tags question: http://stackoverflow.com/q/49262815
tags question: http://stackoverflow.com/q/49269631
tags question: http://stackoverflow.com/q/49174596
tags question: http://stackoverflow.com/q/49173710
tags question: http://stackoverflow.com/q/49133166
tags question: http://stackoverflow.com/q/49235873
tags question: http://stackoverflow.com/q/49137795

http://stackoverflow.com/q/49271629
favorite count: 0
linked to: http://stackoverflow.com/q/1364173
has comment: http://stackoverflow.com/comment/85547209
tagged with: linux
score: 1
tagged with: ssh
has title: How should I terminate long run scripts without any data generated, I tried pressing Ctrl+C in a windows console via paramiko module
has comment: http://stackoverflow.com/comment/85546421
type: Question
type: UnansweredQuestion
tagged with: signals
has answer: http://stackoverflow.com/a/49273330
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has body: This is really interesting. I have following scripts on my linux machine: sleep.py import time from datetime import datetime print(datetime.now()) time.sleep(20) print('Over!') print(datetime.now()) loop.py import time for i in range(20): time.sleep(1) print(i) I can terminate them directly by ctrl+c if I login through PuTTY or git-bash. But when I trying to run the Python scripts on Windows console: test.py def ssh_pty_command(cmd, ip, username, passwd=None, key_filename=None): """run ssh.exec_command with realtime output and return exit_code.""" try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) logging.debug('Connecting to remote server {}...'.format(ip)) ssh.connect(ip, 22, username, password=passwd, key_filename=key_filename, timeout=5) stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True) logging.info('ssh_In: {}'.format(cmd)) # print '$: {}'.format(cmd) for line in iter(stdout.readline, ""): logging.info('ssh_Out: {}'.format( line.rstrip('\n').encode('utf-8'))) for err in iter(stderr.readline, ""): logging.error('ssh_Error: {}'.format( err.rstrip().encode('utf-8'))) exit_code = stdout.channel.recv_exit_status() logging.debug('Task exit with code {}.\n'.format(exit_code)) return exit_code except Exception as err: logging.error('*** Caught SSH exception: %s: %s' % (err.__class__, err)) raise finally: ssh.close() ssh_pty_command('python loop.py',ip,username) ssh_pty_command('python sleep.py',ip,username) When I press ctrl+c , the loop.py terminated immediately, but the sleep.py waits until the time.sleep(20) is finished and then terminate the execution. How can I terminate the sleep.py immediately? Note I did try to use get_pty=True in my exec_command method in my function, but it didn't help. I guess it should have something to do with the signal sent by Paramiko, but not sure where to dig in...
tagged with: paramiko

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

http://stackoverflow.com/q/49157285
has title: Is it possible to access nth element of a dict in python
downvote count: 0
upvote count: 7
favorite count: 0
has body: I have a snippet of code in which the function foo returns a dictionary. def foo(): # do something here # get data from web return { "book": {ln : wd for ln, wd, _ in data["book"]}, "note": {ln : wd for ln, wd, _ in data["note"]}, } def bar(): data = foo() # how to access 0th element of data["book"] # data["book"][0] doesnt work The question is how can I access its first element?
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85319565
score: 7
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/49157380
possible better answer: http://stackoverflow.com/a/72909761
type: Question
has answer: http://stackoverflow.com/a/49157380
answer count: 2
has answer: http://stackoverflow.com/a/72909761

http://stackoverflow.com/q/49159619
has comment: http://stackoverflow.com/comment/85335395
has body: I am trying to debug python file using lldb, but I keep getting below error: xxxxx: lldb python lldb-test-2.py (lldb) target create "python" Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/Users/xxxxx/anaconda2/lib/python2.7/copy.py", line 52, in &lt;module&gt; import weakref File "/Users/xxxxx/anaconda2/lib/python2.7/weakref.py", line 14, in &lt;module&gt; from _weakref import ( ImportError: cannot import name _remove_dead_weakref Current executable set to 'python' (x86_64). (lldb) settings set -- target.run-args "lldb-test-2.py" (lldb) r Process 69299 launched: '/Users/xxxxx/anaconda2/envs/work-env-test/bin/python' (x86_64) Process 69299 stopped * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_SOFTWARE (code=131072, subcode=0x0) frame #0: 0x00007fffa478cb1a libsystem_kernel.dylib`__posix_spawn + 10 libsystem_kernel.dylib`__posix_spawn: -&gt; 0x7fffa478cb1a &lt;+10&gt;: jae 0x7fffa478cb24 ; &lt;+20&gt; 0x7fffa478cb1c &lt;+12&gt;: movq %rax, %rdi 0x7fffa478cb1f &lt;+15&gt;: jmp 0x7fffa4785cd4 ; cerror 0x7fffa478cb24 &lt;+20&gt;: retq Target 0: (python) stopped. (lldb) Here's my test code: #!/Users/xxxxx/anaconda2/envs/work-env-test/bin/python import os import numpy as np def printTest(): print("This is a test") if __name__ == '__main__': printTest() I am able to run this script normally on terminal but cant use lldb to run.
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85331905
has comment: http://stackoverflow.com/comment/85957713
favorite count: 0
score: 1
has comment: http://stackoverflow.com/comment/85335389
has comment: http://stackoverflow.com/comment/85335509
has title: debugging python scripts using lldb
type: Question
tagged with: debugging
has comment: http://stackoverflow.com/comment/85496223
answer count: 0
has comment: http://stackoverflow.com/comment/85335518
tagged with: lldb
type: UnansweredQuestion

http://stackoverflow.com/comment/85397632
has text: By *How can I import different versions of tensorflow in different kernels?* do you mean with different versions of Python?
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49193932

http://stackoverflow.com/q/49141621
has comment: http://stackoverflow.com/comment/85291123
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/85289234
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49146024
answer count: 3
has comment: http://stackoverflow.com/comment/85288812
has comment: http://stackoverflow.com/comment/85289321
accepted answer: http://stackoverflow.com/a/49210671
has comment: http://stackoverflow.com/comment/85331371
has answer: http://stackoverflow.com/a/49143186
possible better answer: http://stackoverflow.com/a/49143186
downvote count: 0
tagged with: selenium
has title: Calling the Firefox webdriver in python
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/85290072
favorite count: 0
has comment: http://stackoverflow.com/comment/85288811
type: Question
has comment: http://stackoverflow.com/comment/85331327
has answer: http://stackoverflow.com/a/49210671
has body: I'm using Debian 9 Stretch and Pycharm IDE and trying to learn web-scramping; I installed the Selenium package simply by running: pip install selenium and the Firefox webdriver by running: wget https://github.com/mozilla/geckodriver/releases/download/v0.19.1/geckodriver-v0.19.1-linux64.tar.gz tar -xvzf geckodriver-v0.19.1-linux64.tar.gz.1 chmod +x geckodriver respectively, to download the last release, extract it and make the driver executable. After that, I added the driver to the following path: usr/local/bin I ran all by using the Pycharm IDE terminal and not the built-in Debian terminal. In order to open Firefox and web-scrape, I run: import selenium from selenium import webdriver from selenium.webdriver.common.keys import Keys webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") The last line gives an error message as output: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/root/PycharmProjects/Example/venv/lib/python3.5/site-packages/selenium/webdriver/firefox/webdriver.py", line 162, in __init__ keep_alive=True) File "/root/PycharmProjects/Example/venv/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 154, in __init__ self.start_session(desired_capabilities, browser_profile) File "/root/PycharmProjects/Example/venv/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 243, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/root/PycharmProjects/Example/venv/lib/python3.5/site-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute self.error_handler.check_response(response) File "/root/PycharmProjects/Example/venv/lib/python3.5/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: connection refused I'm a newbie both in Python and in web-scraping; please, could someone explain what doe…
tagged with: firefox
tagged with: geckodriver
has comment: http://stackoverflow.com/comment/85331498

python-2.7
tags question: http://stackoverflow.com/q/49241332
tags question: http://stackoverflow.com/q/49194895
tags question: http://stackoverflow.com/q/49129934
tags question: http://stackoverflow.com/q/49234502
tags question: http://stackoverflow.com/q/49164562
tags question: http://stackoverflow.com/q/49204190
tags question: http://stackoverflow.com/q/49159617
tags question: http://stackoverflow.com/q/49277109
tags question: http://stackoverflow.com/q/49271638
tags question: http://stackoverflow.com/q/49196889
tags question: http://stackoverflow.com/q/49242411
tags question: http://stackoverflow.com/q/49143198
tags question: http://stackoverflow.com/q/49227521
tags question: http://stackoverflow.com/q/49143359
tags question: http://stackoverflow.com/q/49156160
tags question: http://stackoverflow.com/q/49122952
tags question: http://stackoverflow.com/q/49169483
tags question: http://stackoverflow.com/q/49205354
tags question: http://stackoverflow.com/q/49278341
tags question: http://stackoverflow.com/q/49162578
tags question: http://stackoverflow.com/q/49156153
tags question: http://stackoverflow.com/q/49161006
tags question: http://stackoverflow.com/q/49203359
tags question: http://stackoverflow.com/q/49172935
tags question: http://stackoverflow.com/q/49194330
tags question: http://stackoverflow.com/q/49155839
tags question: http://stackoverflow.com/q/49261303
tags question: http://stackoverflow.com/q/49213200
tags question: http://stackoverflow.com/q/49245202
tags question: http://stackoverflow.com/q/49265329
tags question: http://stackoverflow.com/q/49142463
tags question: http://stackoverflow.com/q/49215267
tags question: http://stackoverflow.com/q/49151662
tags question: http://stackoverflow.com/q/49151497
tags question: http://stackoverflow.com/q/49151547
tags question: http://stackoverflow.com/q/49237117
tags question: http://stackoverflow.com/q/49149139
tags question: http://stackoverflow.com/q/49251560
tags question: http://stackoverflow.com/q/49145666
tags question: http://stackoverflow.com/q/49179568
tags question: http://stackoverflow.com/q/49142819
tags question: http://stackoverflow.com/q/49234814
tags question: http://stackoverflow.com/q/49191943
tags question: http://stackoverflow.com/q/49143799
tags question: http://stackoverflow.com/q/49218302
tags question: http://stackoverflow.com/q/49171370
tags question: http://stackoverflow.com/q/49270400
type: Tag
tags question: http://stackoverflow.com/q/49199164
tags question: http://stackoverflow.com/q/49210485
tags question: http://stackoverflow.com/q/49268864
tags question: http://stackoverflow.com/q/49218483
tags question: http://stackoverflow.com/q/49263249
tags question: http://stackoverflow.com/q/49213278
tags question: http://stackoverflow.com/q/49229385
tags question: http://stackoverflow.com/q/49187779
tags question: http://stackoverflow.com/q/49185593
tags question: http://stackoverflow.com/q/49249130
tags question: http://stackoverflow.com/q/49225602
tags question: http://stackoverflow.com/q/49175540
tags question: http://stackoverflow.com/q/49183519
tags question: http://stackoverflow.com/q/49148689
tags question: http://stackoverflow.com/q/49127897
tags question: http://stackoverflow.com/q/49150330
tags question: http://stackoverflow.com/q/49215099
tags question: http://stackoverflow.com/q/49268947
tags question: http://stackoverflow.com/q/49121900
tags question: http://stackoverflow.com/q/49153714
tags question: http://stackoverflow.com/q/49227051
tags question: http://stackoverflow.com/q/49188092
tags question: http://stackoverflow.com/q/49227864
tags question: http://stackoverflow.com/q/49195225
tags question: http://stackoverflow.com/q/49158730
tags question: http://stackoverflow.com/q/49222392
tags question: http://stackoverflow.com/q/49263973
tags question: http://stackoverflow.com/q/49136149
tags question: http://stackoverflow.com/q/49198415
tags question: http://stackoverflow.com/q/49171098
tags question: http://stackoverflow.com/q/49140099
tags question: http://stackoverflow.com/q/49180779

http://stackoverflow.com/q/49172914
has title: How to fill nan values with rolling mean in pandas
answer count: 3
has comment: http://stackoverflow.com/comment/85356331
upvote count: 14
tagged with: pandas
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/61879671
has comment: http://stackoverflow.com/comment/85350969
tagged with: nan
has comment: http://stackoverflow.com/comment/85350851
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85351099
accepted answer: http://stackoverflow.com/a/49173196
tagged with: mean
has answer: http://stackoverflow.com/a/71046117
has answer: http://stackoverflow.com/a/49173196
downvote count: 0
tagged with: python
has body: I have a dataframe which contains nan values at few places. I am trying to perform data cleaning in which I fill the nan values with mean of it's previous five instances. To do so, I have come up with the following. input_data_frame[var_list].fillna(input_data_frame[var_list].rolling(5).mean(), inplace=True) But, this is not working. It isn't filling the nan values. There is no change in the dataframe's null count before and after the above operation. Assuming I have a dataframe with just integer column, How can I fill NaN values with mean of the previous five instances? Thanks in advance.
score: 14
has answer: http://stackoverflow.com/a/61879671
has comment: http://stackoverflow.com/comment/85351077
type: AnsweredQuestion

http://stackoverflow.com/comment/85275366
type: AnswerComment
comment on: http://stackoverflow.com/a/49134812
has text: Both are on the newest version
type: Comment
score: 0

http://stackoverflow.com/q/49220973
score: 0
has body: Before asking my question, I'll explain what this short piece of code exactly does: first you get a menu where you can make a choice, if you choose 1, it should ask for the watch time (W) views (V) then for the duration of the video (h),(m) and (s). But now when you choose 1 it gives me this error: Traceback (most recent call last): File "C:/Users/Arcky/Desktop/youtube-avarage-watch-time-v2 help.py", line 72, in &lt;module&gt; main() File "C:/Users/Arcky/Desktop/youtube-avarage-watch-time-v2 help.py", line 65, in main getchoice(Choice) NameError: name 'Choice' is not defined so far I can see is Choice defined in the function called choice() maybe I should use a different name? If you can help to fix this and let it work, I would be really grateful here's the full code def menu(): print('make your choice') print('1. calculate Av. view duration') print('2. end this shit') def choice(): Choice = 0 Choice = (int(input('make a choice... '))) while Choice &lt;= 0 or Choice &gt;= 3: print('Error!') Choice = (int(input('make a choice... '))) return Choice def getchoice(Choice): if Choice == 1: print(Choice) getwatchtimeandviews() def getwatchtimeandviews(): W =int(input("Enter Watch Time: ")) V =int(input("Enter Views: ")) return W, V def gettimeofvideo(): h =int(input("Enter hours:")) m =int(input("Enter minutes:")) if m &gt;=60: m = m-60 h = h + 1 s =int(input("Enter seconds:")) if s &gt;=60: s = s-60 m = m + 1 if m &gt;=60: m = m-60 h = h + 1 return h, m, s def calculateviewduration(W,V,h,m,s): A = W / V As = A*60 T = (h*3600) + (m*60) + s P = (As/T)*100 Am = 0 return def checkinput(As, P, Am): if As &lt;= 59: print('Av. view duration:',round(As),'sec','(',round(P,2),'%)') while As &gt; 59: Am = Am + 1 As = As - 60 print('Av. view duration:',round(Am),'min', round(As),'sec','(',round(P,2),'%)') if P &gt; 100: print('error! value cannot be higher then 100%!') def stop(): print() def main(): menu() choice() getchoice(Choice) print ("Enter duration of video:") gettimeofvide…
has comment: http://stackoverflow.com/comment/85445446
has title: variable not defined and function doesn't work
has comment: http://stackoverflow.com/comment/85445421
has comment: http://stackoverflow.com/comment/85445495
type: Question
has comment: http://stackoverflow.com/comment/85445530
answer count: 2
has answer: http://stackoverflow.com/a/49221005
has answer: http://stackoverflow.com/a/49221183
has comment: http://stackoverflow.com/comment/85445426
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85445410
has comment: http://stackoverflow.com/comment/85445420
has comment: http://stackoverflow.com/comment/85445481
has comment: http://stackoverflow.com/comment/85445422
has comment: http://stackoverflow.com/comment/85445482

http://stackoverflow.com/q/49274821
has body: I trying to select size of shoe from this website link. I tried almost all the ways like select, select_by_index, select_by_value etc but getting the following error - selenium.common.exceptions.ElementNotInteractableException: Message: Element &lt;option&gt; could not be scrolled into view My code looks like- from selenium.webdriver.support.select import Select s1= Select(driver.find_element_by_name('id')) s1.select_by_index(2)
linked to: http://stackoverflow.com/q/43868009
has title: Selenium select option from dropdown menu even when I am getting all the tags
tagged with: selenium-webdriver
score: 1
answer count: 1
downvote count: 0
tagged with: selenium
upvote count: 1
has comment: http://stackoverflow.com/comment/85552097
type: AnsweredQuestion
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49275106
has comment: http://stackoverflow.com/comment/85552410
has answer: http://stackoverflow.com/a/49275106
tagged with: python

http://stackoverflow.com/q/49156484
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49162176
score: 1
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49162176
tagged with: python
linked to: http://stackoverflow.com/q/47398081
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85330680
has comment: http://stackoverflow.com/comment/85342765
answer count: 1
downvote count: 0
has body: I'm looking for a fast way to map scalars to hex colors in python: import matplotlib import matplotlib.cm as cm import matplotlib.colors as mcol np.random.seed(0) df = pd.DataFrame(np.random.rand(20000,1)) df.head() 0 0 0.548814 1 0.715189 2 0.602763 3 0.544883 4 0.423655 I have 20 colors only, so I wonder if matplotlib is the best solution, or a simple lookup table would be better. colors = ["#084594", "#0F529E", "#1760A8", "#1F6EB3", "#2979B9", "#3484BE", "#3E8EC4", "#4A97C9", "#57A0CE", "#64A9D3", "#73B2D7", "#83BBDB", "#93C4DE", "#A2CBE2", "#AED1E6", "#BBD6EB", "#C9DCEF", "#DBE8F4", "#EDF3F9", "#FFFFFF"] values = df[0].values @profile def apply_method(): # 6.9 sec cm1 = mcol.ListedColormap(colors) norm = matplotlib.colors.Normalize(vmin=np.min(values), vmax=np.max(values), clip=True) mapper = cm.ScalarMappable(norm=norm, cmap=cm1) return df[0].apply(lambda row: mcol.to_hex(mapper.to_rgba(row))) %time apply_method() From the profiler I see that to_rgba() is the most expensive method (6.5 sec for only 20.000 values). So I'm looking at a way to bypass the to_rgba() method. Is there a way to get the color ranges from cm.ScalarMappable? And then do a lookup to the right hex color?
upvote count: 1
tagged with: optimization
type: AnsweredQuestion
has title: Fast way to map scalars to colors in python

http://stackoverflow.com/comment/85456101
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49226167
has text: with current formatting your code shouldn't compile. The `else` has bad indentation.

http://stackoverflow.com/comment/85475469
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49235785
has text: This seems to be a working URL for the dataset https://www.esrl.noaa.gov/psd/thredds/fileServer/Datasets/cmap/std/precip.mon.mean.nc
type: Comment

http://stackoverflow.com/comment/85369804
score: 0
type: Comment
type: QuestionComment
has text: Thanks, Alasdair! the server had started but the mapping is not working
comment on: http://stackoverflow.com/q/49181126

http://stackoverflow.com/comment/85496699
type: QuestionComment
has text: Please refer to [this](https://stackoverflow.com/questions/49201281/error-message-chromedriver-executable-needs-to-be-path) as well, in case you are having trouble passing the path in the correct format.
comment on: http://stackoverflow.com/q/49245355
score: 1
type: Comment

http://stackoverflow.com/q/49131151
downvote count: 0
tagged with: pandas
has title: How to penalize decision tree for misclassifying a certain class?
has body: You can simply copy/paste the code to run in your environment. The scientific term I found for it is Cost minimization while the algorithm applies accuracy maximization. That is the algorithm aims to get the highest score in accuracy while I don't care about the accuracy, I care about not misclassifying a certain class. I know the following uses the CART algorithm for decision trees, how can I change it to stress that misclassifying a False is more dangerous than misclassing a positive. I know the term is Cost Minimization but I am not sure how to apply it or what books to search for in. import numpy as np import pandas as pd from sklearn.datasets import make_classification from sklearn.tree import DecisionTreeClassifier X, y = make_classification(n_samples=1000, n_features=6, n_informative=3, n_classes=2, random_state=0, shuffle=False) # Creating a dataFrame df = pd.DataFrame({'Feature 1':X[:,0], 'Feature 2':X[:,1], 'Feature 3':X[:,2], 'Feature 4':X[:,3], 'Feature 5':X[:,4], 'Feature 6':X[:,5], 'Class':y}) y_train = df['Class'] X_train = df.drop('Class',axis = 1) dt = DecisionTreeClassifier(random_state=42) dt.fit(X_train, y_train)
accepted answer: http://stackoverflow.com/a/49132198
favorite count: 0
type: Question
upvote count: 2
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
tagged with: python
has answer: http://stackoverflow.com/a/49132198
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/49262342
has comment: http://stackoverflow.com/comment/85528252
score: 0
has comment: http://stackoverflow.com/comment/85528309
has body: Since the second element of the tuple is a number, you can invert the direction of the sort by inverting the number itself, which means you only need to sort once by using an appropriate key. dic.sort(key=lambda a: (-a[1], a[0])) It is slightly simpler, though, to use sorted directly on the return value of words.items(): dic = sorted(words.items(), key=lambda a: (-a[1], a[0])) If you couldn't use the negative-number trick, you'd have to write an explicit comparison function and convert it to a key using the functools module. def tup_compare(t1, t2): w1, c1 = t1 w2, c2 = t2 if w1 &lt; w2: return 1 elif w1 &gt; w2: return -1 elif c1 &lt; c2: return -1 elif c1 == c2: return 0 else: return 1 dic = sorted(words.items, key=functools.cmp_to_key(tup_compare))
accepted answer of: http://stackoverflow.com/q/49262273
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49262273
has comment: http://stackoverflow.com/comment/85528274
type: Answer

http://stackoverflow.com/q/49144870
has body: enter image description here This is from my bash shell. but the version i downloaded is 3.6.0.
has title: I installed Python 3.6.0 from the official website. But when i run python -- version on my bash shell .it say 2.7.1. And i don't know why
score: 0
has answer: http://stackoverflow.com/a/49145211
has answer: http://stackoverflow.com/a/49145221
type: Question
has answer: http://stackoverflow.com/a/49144907
has answer: http://stackoverflow.com/a/49144926
type: UnansweredQuestion
tagged with: python
answer count: 4

http://stackoverflow.com/comment/85449139
score: 1
comment on: http://stackoverflow.com/a/49222635
type: Comment
type: AnswerComment
has text: Thank you! It seems my problem, and formerly yours, was splitting the string! Good Day!

http://stackoverflow.com/q/49246876
answer count: 1
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85497443
has comment: http://stackoverflow.com/comment/85497543
has body: I have the following data set: Sample Date Time Elapsed Time (hr) Power (V) Power (mW) Current (A) Main Temp (degC) BRF Temp (degC) SHG Temp (degC) THG Temp (degC) Main Temp Drive (volt) Alt PD (adc) UV PD (adc) IR PD (adc) DIO0 (hex) DIO2 (hex) DIO4 (hex) DIO5 (hex) Annotation 1 2/2/2017 9:54:53 PM 0.0002 -1.0000 61.7638 17.5781 24.1796 48.1374 57.0930 56.0887 2.0742 812 -1 -1 D0F2 0F14 F8B1 FFE4 Start Pos=BI7, Cmd=60.1mW 2 2/2/2016 9:59:52 PM 0.0833 -1.0000 61.8029 17.4072 23.0301 48.0849 57.0220 55.8946 5.1211 812 -1 -1 D0F2 0F14 F8B1 FFE4 # 3 2/2/2016 10:04:50 PM 0.1660 -1.0000 61.8422 17.3584 23.3169 48.0849 57.0398 55.8946 6.1406 813 -1 -1 D0F2 0F14 F8B1 FFE4 # 4 2/2/2012 10:09:49 PM 0.2490 -1.0000 61.8531 17.3584 23.2286 48.0849 57.0220 55.8946 6.0820 811 -1 -1 D0F2 0F14 F8B1 FFE4 # 5 2/2/2016 10:14:46 PM 0.3317 -1.0000 61.8662 17.3340 23.2065 48.0849 57.0220 55.8946 6.1055 811 -1 -1 D0F2 0F14 F8B1 FFE4 # 6 2/2/2015 10:19:44 PM 0.4144 -1.0000 61.8711 17.3096 23.2065 48.0849 57.0220 55.8769 6.1289 812 -1 -1 D0F2 0F14 F8B1 FFE4 # 7 2/2/2016 10:24:42 PM 0.4972 -1.0000 61.8675 17.3584 23.2286 48.0849 57.0220 55.8946 6.1289 812 -1 -1 D0F2 0F14 F8B1 FFE4 # 8 2/2/2013 10:29:42 PM 0.5804 -1.0000 61.8754 17.3584 23.2065 48.0849 57.0220 55.8769 6.1289 812 -1 -1 D0F2 0F14 F8B1 FFE4 # 9 2/2/2016 10:35:34 PM 0.6782 -1.0000 61.8741 17.3340 23.2065 48.0849 57.0220 55.8769 6.1523 812 -1 -1 D0F2 0F14 F8B1 FFE4 # 10 2/2/2016 10:41:22 PM 0.7748 -1.0000 61.8744 17.3584 23.2065 48.0849 57.0220 55.8946 6.1758 812 -1 -1 D0F2 0F14 F8B1 FFE4 # 11 2/2/2014 10:46:30 PM 0.8606 -1.0000 61.8685 17.4072 23.2286 48.0849 57.0220 55.8946 6.1406 811 -1 -1 D0F2 0F14 F8B1 FFE4 # 12 2/2/2016 10:52:05 PM 0.9535 -1.0000 1.0546 0.0244 23.0742 48.0849 57.0398 55.8946 3.8320 0 -1 -1 D0F5 0F14 F093 FFC4 # 13 2/2/2016 10:57:18 PM 1.0406 -1.0000 61.7084 17.2607 23.1183 48.0849 57.0220 55.8769 8.8242 809 -1 -1 D0F2 0F14 F8B1 FFE4 # 14 2/2/2016 11:02:40 PM 1.1300 -1.0000 61.8275 17.3584 23.2507 48.0849 57.…
tagged with: python
tagged with: sorting
tagged with: timestamp
has answer: http://stackoverflow.com/a/49246999
has title: Timestamp sorting
score: 0

http://stackoverflow.com/comment/85556888
has text: Okay, that is indeed very strange. It seems that now the output of the global max pooling layer is computed correctly, but the Dense layer set its internal transformation matrix [48,100] according to what would be expected by the Keras interface... Which tensorflow version are you using?
score: 0
comment on: http://stackoverflow.com/q/49255141
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49228713
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49228666
answers question: http://stackoverflow.com/q/49228666
has comment: http://stackoverflow.com/comment/85489459
type: Answer
has body: How do I, instead of read the contents of 'top.py', run the file and pipe the output into dieharder… In sh, and most other POSIX shells, you run it the same way you'd normally run it, and pipe that (the same way you're piping the output of cat): ./top.py | dieharder … or: python top.py | dieharder The reason you use cat /dev/urandom is that urandom isn't a program, it's a file. Of course it's not a regular file full of bytes sitting on the disk, it's a special device file, created by a device driver and mounted via mknod, but you don't have to worry about that (unless you want to write your own device drivers); it acts as if it were a regular file full of bytes. You can't easily do the same thing, but then you don't have to. You should read a good tutorial on basic shell scripting. I don't have one to recommend, but I'm sure there are plenty of them.
score: 1
type: AcceptedAnswer

http://stackoverflow.com/a/49244708
score: 0
answers question: http://stackoverflow.com/q/49244430
has body: The error was due to pandas having to convert between numpy.datetime64 objects and pandas.Timestamp objects. datetimes in pandas generally seem to be quite messy. This was my solution: timestamps = [pd.Timestamp(np_datetime).to_pydatetime() for np_datetime in minuteDF['timestamp']] lowerTime = timestamps[0] Then, as I am changing lowerTime and continuously need to check if it is still a datetime in minuteDF, I can just check: lowerTime in timestamps
type: Answer

http://stackoverflow.com/a/49200765
accepted answer of: http://stackoverflow.com/q/49200518
type: Answer
has body: You should be deleting such columns because it will provide no extra information about how each data point is different from another. It's fine to leave the column for some machine learning models (due to the nature of how the algorithms work), like random forest, because this column will actually not be selected to split the data. To spot those, especially for categorical or nominal variables (with fixed number of possible values), you can count the occurrence of each unique value, and if the mode is larger than a certain threshold (say 95%), then you delete that column from your model. I personally will go through variables one by one if there aren't any so that I can fully understand each variable in the model, but the above systematic way is possible if the feature size is too large.
answers question: http://stackoverflow.com/q/49200518
has comment: http://stackoverflow.com/comment/85406931
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

pyspark
tags question: http://stackoverflow.com/q/49177352
tags question: http://stackoverflow.com/q/49132151
tags question: http://stackoverflow.com/q/49168338
tags question: http://stackoverflow.com/q/49184050
tags question: http://stackoverflow.com/q/49223886
tags question: http://stackoverflow.com/q/49196607
tags question: http://stackoverflow.com/q/49230602
tags question: http://stackoverflow.com/q/49249620
tags question: http://stackoverflow.com/q/49148647
tags question: http://stackoverflow.com/q/49180047
tags question: http://stackoverflow.com/q/49162854
tags question: http://stackoverflow.com/q/49238777
tags question: http://stackoverflow.com/q/49245050
tags question: http://stackoverflow.com/q/49167656
tags question: http://stackoverflow.com/q/49204024
tags question: http://stackoverflow.com/q/49222171
tags question: http://stackoverflow.com/q/49151938
tags question: http://stackoverflow.com/q/49163141
tags question: http://stackoverflow.com/q/49242550
type: Tag
tags question: http://stackoverflow.com/q/49144306
tags question: http://stackoverflow.com/q/49263438
tags question: http://stackoverflow.com/q/49234677
tags question: http://stackoverflow.com/q/49243719
tags question: http://stackoverflow.com/q/49216681
tags question: http://stackoverflow.com/q/49235092
tags question: http://stackoverflow.com/q/49189962
tags question: http://stackoverflow.com/q/49169772
tags question: http://stackoverflow.com/q/49260559
tags question: http://stackoverflow.com/q/49272209
tag name: pyspark
tags question: http://stackoverflow.com/q/49232611
tags question: http://stackoverflow.com/q/49160329
tags question: http://stackoverflow.com/q/49191853
tags question: http://stackoverflow.com/q/49189075
tags question: http://stackoverflow.com/q/49181179
tags question: http://stackoverflow.com/q/49188977

http://stackoverflow.com/q/49182302
answer count: 0
has body: I need to send some emails with attachments to different contact groups using python and outlook. The Contact Group I created is called 'Test'. It will not send the emails to 'Test' outlook Contact Group. Error message when I run my code: Traceback (most recent call last): File "", line 11, in send_notification(i) File "", line 10, in send_notification mail.send File "C:\Users\thisguy\AppData\Local\Continuum\Anaconda3\lib\site-packages\win32com\client\dynamic.py", line 516, in getattr ret = self.oleobj.Invoke(retEntry.dispid,0,invoke_type,1) com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Outlook does not recognize one or more names. ', None, 0, -2147467259), None) import win32com.client as win32 import psutil import os import subprocess import glob brands = ['PM', 'KP', 'SW', 'GM'] morning = ' Good Morning, ' # Drafting and sending email notification to senders. You can add other senders' email in the list def send_notification(i): outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = 'Test' # Contact Group I want to send the email to mail.Subject = 'Expenses' mail.Attachments.Add(Source = 'c:/users/thisguy/desktop/Expenses.docx') for f in glob.glob('c:/users/thisguy/desktop/'+ i +' Expense*.xlsx'): mail.Attachments.Add(Source = f) mail.HTMLBody = morning mail.send # Open Outlook.exe. Path may vary according to system config # Please check the path to .exe file and update below def open_outlook(): try: subprocess.call(['C:\Program Files (x86)\Microsoft Office\root\Office16\OUTLOOK.EXE']) os.system("C:\Program Files (x86)\Microsoft Office\root\Office16\OUTLOOK.EXE"); except: print("Outlook didn't open successfully") # Checking if outlook is already opened. If not, open Outlook.exe and send email for item in psutil.pids(): p = psutil.Process(item) if p.name() == "OUTLOOK.EXE": flag = 1 break else: flag = 0 if (flag == 1): for i in brands: send_notification(i) else: open_outlook() for i in brands: send_noti…
has comment: http://stackoverflow.com/comment/85482104
type: Question
tagged with: outlook
has comment: http://stackoverflow.com/comment/85480817
has comment: http://stackoverflow.com/comment/85481121
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85480178
tagged with: python
has title: Error when trying to send to Outlook Contact Group using Python
score: 0

http://stackoverflow.com/a/66353004
downvote count: 6
upvote count: 0
score: -6
has comment: http://stackoverflow.com/comment/120033669
answers question: http://stackoverflow.com/q/49228744
type: Answer
has body: $ python3 -c 'import attr; print(attr.__file__)' /path/to/python3.X/site-packages/attr.py Removing this file worked for me. So rm $(python3 -c 'import attr; print(attr.__file__)') solves the issue.

http://stackoverflow.com/comment/85367880
has text: You're talking about "intersection" and "union" and so on, so… is there a reason you're using lists instead of sets here? (In fact, even if these things need to be list for a _different_ part of your code, copying them into sets to write _this_ part could still be a great idea, making it easy to understand and maybe even being the CPU-fastest solution to boot.)
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49181155

http://stackoverflow.com/comment/85416544
score: 0
comment on: http://stackoverflow.com/q/49205223
type: QuestionComment
has text: do you get the same error when trying to run import in python shell?
type: Comment

http://stackoverflow.com/comment/85416711
score: 0
has text: I think you can use `Series.dt`. https://pandas.pydata.org/pandas-docs/stable/api.html#datetimelike-properties
comment on: http://stackoverflow.com/q/49205526
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49216483
has title: Initialize an empty multidimensional list
has comment: http://stackoverflow.com/comment/85437035
favorite count: 0
possible better answer: http://stackoverflow.com/a/49216524
type: Question
linked to: http://stackoverflow.com/q/30740490
has comment: http://stackoverflow.com/comment/85437024
has comment: http://stackoverflow.com/comment/85437036
has body: I would like to initialize a multidimensional list capable of storing an object for every minute since year 1950-2050. Something like: minute = [None]*61 hour = [minute]*25 day = [hour] month = [day] data = [month]*100 So you can do: data[89][1][29][23][55] = 'It was a good minute the one from January 29th in 1989 when it was 23:55' How would be such a multidimensional list be initialized in Python? Would it be an actual different object than the one created with the above code? Initially the multidimensional list would contain objects None. Python 2.7 Following answer I tried: # Data structure minute = 60 hour = 24 day = 31 month = 12 year = 100 test = [[[[[None for _minute in range(minute)] for _hour in range(hour)] for _day in range(day)] for _month in range(month)] for _year in range(year)] But it seems too much for multidimensional lists, as I get "Killed" when trying to execute this.
tagged with: python
accepted answer: http://stackoverflow.com/a/49216591
has answer: http://stackoverflow.com/a/49216524
has comment: http://stackoverflow.com/comment/85437070
upvote count: 2
has comment: http://stackoverflow.com/comment/85436989
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85437242
score: 2
has comment: http://stackoverflow.com/comment/85437105
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85437005
has answer: http://stackoverflow.com/a/49216591

http://stackoverflow.com/a/75078294
answers question: http://stackoverflow.com/q/49248551
type: Answer
has body: To pass a dictionary of dictionaries to list() is more concise and faster: dic_of_dicts = {1: {"a": "A"}, 2: {"b": "B"}, 3: {"c": "C"}} list_of_dicts = list(dic_of_dics.values()) list_of_dicts [{'a': 'A'}, {'b': 'B'}, {'c': 'C'}] Benchmark: %timeit [value for value in dic_of_dics.values()] 153 ns ± 1.13 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) %timeit list(dic_of_dics.values()) 95.3 ns ± 0.639 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)
score: 0

http://stackoverflow.com/comment/85492293
comment on: http://stackoverflow.com/a/49244140
type: AnswerComment
score: 0
has text: Yes that makes more sense to me. Is there a way of telling how many extra "slots" it opens up when it creates a list? Is it always one extra blank slot?
type: Comment

http://stackoverflow.com/comment/85431957
type: Comment
type: QuestionComment
has text: Yes, but the question nevertheless is theoretical. IO could be quite intensive because of using DB for example
comment on: http://stackoverflow.com/q/49213647
score: 0

http://stackoverflow.com/a/49134866
has comment: http://stackoverflow.com/comment/85275255
has comment: http://stackoverflow.com/comment/85275124
has comment: http://stackoverflow.com/comment/85275137
has body: Try adding this for cross compatibility instead of your previous import code.: (Hoping that's the problem) try: from tkinter import * from tkinter import ttk,filedialog except: from Tkinter import * from Tkinter import ttk,filedialog
has comment: http://stackoverflow.com/comment/85274542
has comment: http://stackoverflow.com/comment/85275053
answers question: http://stackoverflow.com/q/49134554
type: Answer
has comment: http://stackoverflow.com/comment/85275864
score: 0

http://stackoverflow.com/q/49145328
downvote count: 0
upvote count: 1
tagged with: google-colaboratory
favorite count: 0
type: Question
has title: "UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80" while loading pickle file using pydrive on google colaboratory
has answer: http://stackoverflow.com/a/49167860
has comment: http://stackoverflow.com/comment/85319502
score: 1
has comment: http://stackoverflow.com/comment/85296314
tagged with: pickle
tagged with: python
tagged with: utf-8
has answer: http://stackoverflow.com/a/49165682
answer count: 2
tagged with: pydrive
has body: I am new to using google colaboratory (colab) and pydrive along with it. I am trying to load data in 'CAS_num_strings' which was written in a pickle file in a specific directory on my google drive using colab as: pickle.dump(CAS_num_strings,open('CAS_num_strings.p', 'wb')) dump_meta = {'title': 'CAS.pkl', 'parents': [{'id':'1UEqIADV_tHic1Le0zlT25iYB7T6dBpBj'}]} pkl_dump = drive.CreateFile(dump_meta) pkl_dump.SetContentFile('CAS_num_strings.p') pkl_dump.Upload() print(pkl_dump.get('id')) Where 'id':'1UEqIADV_tHic1Le0zlT25iYB7T6dBpBj' makes sure that it has a specific parent folder with this given by this id. The last print command gives me the output: '1ZgZfEaKgqGnuBD40CY8zg0MCiqKmi1vH' Hence, I am able to create and dump the pickle file whose id is '1ZgZfEaKgqGnuBD40CY8zg0MCiqKmi1vH'. Now, I want to load this pickle file in another colab script for a different purpose. In order to load, I use the command set: cas_strings = drive.CreateFile({'id':'1ZgZfEaKgqGnuBD40CY8zg0MCiqKmi1vH'}) print('title: %s, mimeType: %s' % (cas_strings['title'], cas_strings['mimeType'])) print('Downloaded content "{}"'.format(cas_strings.GetContentString())) This gives me the output: title: CAS.pkl, mimeType: text/x-pascal --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) &lt;ipython-input-9-a80d9de0fecf&gt; in &lt;module&gt;() 30 cas_strings = drive.CreateFile({'id':'1ZgZfEaKgqGnuBD40CY8zg0MCiqKmi1vH'}) 31 print('title: %s, mimeType: %s' % (cas_strings['title'], cas_strings['mimeType'])) ---&gt; 32 print('Downloaded content "{}"'.format(cas_strings.GetContentString())) 33 34 /usr/local/lib/python3.6/dist-packages/pydrive/files.py in GetContentString(self, mimetype, encoding, remove_bom) 192 self.has_bom == remove_bom: 193 self.FetchContent(mimetype, remove_bom) --&gt; 194 return self.content.getvalue().decode(encoding) 195 196 def GetContentFile(self, filename, mimetype=None, remove_bom=False): UnicodeDecodeErr…
type: UnansweredQuestion

http://stackoverflow.com/comment/106752329
comment on: http://stackoverflow.com/a/49156972
type: Comment
score: 0
type: AnswerComment
has text: this works, but it seems like questionable implementation for `mode='a'`. neither here nor there, just a comment... Especially not at pault

http://stackoverflow.com/comment/85548462
comment on: http://stackoverflow.com/q/49272861
score: 0
type: Comment
has text: The error tells you what is wrong. There is no variable named wordList, so you cannot do `wordList[i]=word`
type: QuestionComment

http://stackoverflow.com/q/49273725
has answer: http://stackoverflow.com/a/49283416
has body: I have a flask server, which is connected via vpn to another local machine. To have access to the local machine, I reroute it through: @app.route('/portal/&lt;page&gt;') def portal(page): return requests.get('http://192.168.0.69/'+page).content This allows me to open every page on the local machine. But there are some php forms on the page that I cant figure out how to post to. I tried: @app.route('/portal/&lt;page&gt;', methods=['POST','GET']) def portal(page): if request.form: return requests.post('http://192.168.0.69/'+page, data = request.form).content else: return requests.get('http://192.168.0.69/'+page).content But this only ends up refreshing the page. Nothing happens.
has comment: http://stackoverflow.com/comment/85557014
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: flask
has title: Flask - Access another website through server
upvote count: 0
answer count: 1
tagged with: python-requests
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/85284316
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49139458
has text: I'm not sure where the `{}` would come from, but you would perhaps have a better time with `resultmovies = [item[0] for item in c.fetchall()]` and then `for item in resultmovies: program.infoBox("Your Movie list", item, parent = None)` or similar.
score: 1

http://stackoverflow.com/comment/85335965
has text: Thanks **Brendon Abel ** , I was not having idea about enumerate , I will learn about it. Thanks for your help :)
type: AnswerComment
comment on: http://stackoverflow.com/a/49159595
score: 0
type: Comment

http://stackoverflow.com/comment/85452719
has text: yes that is correct
comment on: http://stackoverflow.com/q/49224133
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85497110
has text: Hey I've tried this out however, it seems to only update the first x amount of players in the 'totalRank' list where x is the amount of players in the 'playerPoints' list. So for example, if the 'playerPoints' list is: [[P1, 10], [P12, 10], [P19, 10]] it updates the 'totalRank' list to: [[P1], 10], [[P2], 10], P3, 10
comment on: http://stackoverflow.com/a/49246502
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/comment/85548346
score: 0
type: Comment
type: QuestionComment
has text: What happens if `7 yes` ?
comment on: http://stackoverflow.com/q/49272851

http://stackoverflow.com/comment/85555515
type: AnswerComment
comment on: http://stackoverflow.com/a/49276446
score: 0
has text: Hmm... So where are my four lists? I mean a,b,c and d?? I don't need them inside anything, I already had that.. Or am I misunderstanding?
type: Comment

http://stackoverflow.com/q/49203954
type: AnsweredQuestion
upvote count: 3
downvote count: 0
answer count: 1
tagged with: decorator
tagged with: newrelic
favorite count: 0
type: Question
score: 3
has body: I am using New Relic to monitor my Python (2.7) app, but only in my Production environment. I want to use their function_trace decorator. In wsgi.py try: import newrelic.agent newrelic.agent.initialize('/path/') except Exception as e: pass In views.py if settings.ENV == "test": pass else: import newrelic @newrelic.agent.function_trace() def my_function(): .... This works great in Production, but fails in Test, of course. I can't put if-else directly around a decorator so I was thinking that I could use a conditional decorator: def newrelic_conditional_decorator(function) # What magic goes in here... if settings.ENV == "test": just return function else: use @newrelic.agent.function_trace() decorator @newrelic_conditional_decorator def my_function(): .... I'm always a bit hazy on decorators so am hoping for some help here! (Or another way to handle not having the same package in Test as in Production.)
has answer: http://stackoverflow.com/a/49204061
tagged with: python
accepted answer: http://stackoverflow.com/a/49204061
has title: Python, conditional use of a decorator (package not installed in all env)

http://stackoverflow.com/comment/85431162
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49212087
has text: It did, "You can accept your own answer in 2 days.". No choice but to wait.

http://stackoverflow.com/a/49216285
type: Answer
has body: isn't the popped list going to just always be equal to nothing []? Not always. At the third if statement, it recursively adds to the group list, and only when that call stack returns (when the sum of the group exceeds the total, or the index is outside the input range), does the most recent pushed value get popped. In execution order of the first input , here's the group values 0 0, 2 0, 2, 4 0, 2, 4, 8... Sum is greater than 10, return False 8 is popped, and the previous index increases 0, 2, 4.... The index is out of range, and the group sum is not the total 4 is popped and the previous index increases 0, 2, 8... This is equal to 10, so we return True back up the call stack At the end of unwinding the recursion, yes the group list will be empty, but the output only requires a boolean, not tracking the group that matches the criteria
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49216095
answers question: http://stackoverflow.com/q/49216095

http://stackoverflow.com/comment/85514023
score: 1
type: Comment
type: QuestionComment
has text: Please do not put images of code into a question. It's text - add it to the question **as text**.
comment on: http://stackoverflow.com/q/49255507

http://stackoverflow.com/a/49253755
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49161652
has body: The problem comes from the fact that ht requires grad: ht = Variable(torch.from_numpy(np.random.normal(0,1,(batch_size,500,1,1))), requires_grad=True) And with variables that require grads, you are not allowed by pytorch to assign values to (slices) of them. You can't do: ht[idx] = some_tensor That means that you will need to find another way to do your customized shrink function using built in pytorch functions like squeeze, unsqueeze, etc. Another option is to assign your shrink_ht(ht[idx]) slices to another variable or tensor which does not require grads.
has comment: http://stackoverflow.com/comment/85633562
type: Answer
score: 2

http://stackoverflow.com/a/49243270
accepted answer of: http://stackoverflow.com/q/49241059
type: Answer
has body: It looks like you've redefined list. For example: Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; list() # list is certainly callable... [] &gt;&gt;&gt; type(list) &lt;class 'type'&gt; &gt;&gt;&gt; list = [1,2,3] # Now list is used as a variable and reassigned. &gt;&gt;&gt; type(list) &lt;class 'list'&gt; &gt;&gt;&gt; list() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'list' object is not callable Don't use list as a variable name. You're code as show works as is, so there is some code missing that is assigning to list and causing the problem: Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:54:40) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from PIL import Image &gt;&gt;&gt; im = Image.open('exp.jpg','r') &gt;&gt;&gt; pix_val = list(im.getdata()) &gt;&gt;&gt;
answers question: http://stackoverflow.com/q/49241059
upvote count: 2
score: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49155187
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85315134
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85314970
answers question: http://stackoverflow.com/q/49155117
has comment: http://stackoverflow.com/comment/85314937
has body: in will check each element of your data. So in the case of: data = ['Karma', 19, 'e', 'Kunugigaoka JH'] it will check 'Karma', then 19, then... Instead you should try: data = 'Karma', 19, 'e', 'Kunugigaoka JH' This is a list, in a list. Now the first thing in will check will be: ['Karma', 19, 'e', 'Kunugigaoka JH']

http://stackoverflow.com/q/49175091
has body: So usually the problem is that indexes can only be read once unless clear_on_read is false. But I haven't come across this error yet "Could not write to TensorArray index 0 because it has already been written to.". def bod(i, centroids, base, seq, thres): eu_dist = tf_sqrt(tf_reduce_sum(tf_square(tf_subtract(base,centroids[i])), axis=1)) argmin = tf_cast(tf_argmin(eu_dist), tf_int32) default_write = tf_constant([0,0,0], tf_int32) seq = tf_cond(tf_less(eu_dist[argmin], thres), lambda: seq.write(i, centroids[i,argmin]), lambda: seq.write(i, default_write)) return i, centroids, base, seq, thres def find_sequence(centroids, thres = 1.0): centroids_tf = tf_placeholder(tf_float32, shape=(3,None,3)) base_tf = tf_placeholder(tf_float32, shape=(3)) thres_tf = tf_placeholder(tf_float32) i_tf = tf_constant(0, tf_int32) seq = tf_TensorArray(tf_float32, size=(tf_shape(centroids_tf)[0]), ) con = lambda i, cen, base, seq, thres_: tf_less(i, tf_shape(centroids_tf)[0]) i, centroids_out, base_out, part, thres_ = tf_while_loop(con, bod, [i_tf, centroids_tf, base_tf, seq, thres_tf]) part_seq = part.stack() object_seq = [] with tf_Session() as sess: for cent in centroids[0]: seq_out = sess.run(part_seq, feed_dict={centroids_tf: centroids[1:], base_tf: cent, thres_tf: thres}) append = True for s in seq_out: if s == [0,0,0]: append = False break if append: object_seq.append(seq_out) return object_seq Can anyone help? or tell me how I can get around it?
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85360448
has title: "Could not write to TensorArray index 0 because it has already been written to." why not?
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/85359622
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85417536
has text: Possible duplicate of [create a pyqt build in GitLab](https://stackoverflow.com/questions/37662616/create-a-pyqt-build-in-gitlab)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49184586
type: Comment

http://stackoverflow.com/comment/85609314
type: AnswerComment
score: 0
type: Comment
has text: would exec("filename=input('Filename?')+'.txt'") work @PatrickArtner
comment on: http://stackoverflow.com/a/49261504

http://stackoverflow.com/comment/85272967
type: Comment
has text: Your problem can be reduced to `subprocess.Popen(["echo", "hello", "|", "cat"])`.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49134151

http://stackoverflow.com/comment/103609077
type: Comment
type: QuestionComment
score: 0
has text: damn, i've been stuck on this for a while. it's crazy
comment on: http://stackoverflow.com/q/49141696

http://stackoverflow.com/comment/85547327
type: QuestionComment
has text: By the way, the internal storage for ints is a lot simpler than strings, and floats even more so. And, as a bonus, it's a lot more obvious why it's a bad idea to change the value of `42` to `23` than why it's a bad idea to change the value of `"My name is Y"` to `"My name is X"`.
comment on: http://stackoverflow.com/q/49271750
score: 3
type: Comment

http://stackoverflow.com/q/49252247
answer count: 2
has answer: http://stackoverflow.com/a/49252477
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/85509117
has body: With Python's decimal module, does a context with a higher precision value use more memory. If not, for what reason would you not always use the maximum?
has answer: http://stackoverflow.com/a/49252373
favorite count: 0
tagged with: precision
upvote count: 3
has title: Does a higher decimal precision use more memory per instance?
tagged with: python
has comment: http://stackoverflow.com/comment/85507848
type: Question
score: 2
has comment: http://stackoverflow.com/comment/85509073
tagged with: decimal

http://stackoverflow.com/q/49137151
linked to: http://stackoverflow.com/q/339007
has comment: http://stackoverflow.com/comment/85279460
score: 0
has comment: http://stackoverflow.com/comment/85279614
tagged with: concatenation
answer count: 3
has answer: http://stackoverflow.com/a/49137525
has comment: http://stackoverflow.com/comment/85279975
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49137606
tagged with: loops
has comment: http://stackoverflow.com/comment/85280098
has answer: http://stackoverflow.com/a/49137608
type: Question
has body: im incrementing a counter that leads to an index of a list code: delist = [] i = 1 idx = [0, ..., 10, ..., 100, ..., 1000, ...] while( i &lt; len(idx)): if i in range(1, 10): delist.append("ladybug_cube_00000" + str(idx[i]) + "_0.jpg") elif i in range(10, 100): delist.append("ladybug_cube_0000" + str(idx[i]) + "_0.jpg") elif i in range(100, 1000): delist.append("ladybug_cube_000" + str(idx[i]) + "_0.jpg") elif i in range(1000, 10000): delist.append("ladybug_cube_00" + str(idx[i]) + "_0.jpg") elif i in range(10000, 100000): delist.append("ladybug_cube_0" + str(idx[i]) + "_0.jpg") elif i in range(100000, 1000000): delist.append("ladybug_cube_" + str(idx[i]) + "_0.jpg") #this deletes that index from the list del idx[i] #this goes an step back so it repeats the loop with the new index's variable. i = i-1 i= i+1 The issue is that it should store every string into a new index in the list "delist" and every element should have exacly 6 digits after "cube_" and before "_0.jpg", but it is storing an extra 0 before "str(idx[i])". example output: delist=["ladybug_cube_000001_0.jpg", "ladybug_cube_000010_0.jpg", "ladybug_cube_000100_0.jpg", "ladybug_cube_001000_0.jpg", "ladybug_cube_010000_0.jpg", "ladybug_cube_100000_0.jpg"] What I'm getting: delist=["ladybug_cube_000001_0.jpg", "ladybug_cube_0000010_0.jpg", "ladybug_cube_00000100_0.jpg", "ladybug_cube_000001000_0.jpg", "ladybug_cube_0000010000_0.jpg", "ladybug_cube_00000100000_0.jpg"] like it won't pass from "range(1, 10)".
has comment: http://stackoverflow.com/comment/85279870
has title: concatenating strings creates an extra 0
tagged with: python

http://stackoverflow.com/comment/85543728
comment on: http://stackoverflow.com/a/49270094
type: Comment
has text: @Tia The way you normally have the PID is either (a) the script is only ever started by your app, so you can store the pid when you start it, or (b) the script writes a "pidfile" (just a text file with one line with the pid) in a known place. (Or, of course, it's managed by `systemd` or a custom `apachectl`-style script, so you don't have to worry about it, but that's not going to be the case here.)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85423967
comment on: http://stackoverflow.com/a/49196427
score: 0
type: AnswerComment
has text: Is it also possible to do the same for a gaussian fit? I mean the mean squared error?
type: Comment

http://stackoverflow.com/comment/85436470
has text: Don't filter out characters. You **will** miss some. Whitelist the ones you want to accept.
comment on: http://stackoverflow.com/q/49216206
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85492849
has text: For a good dark humor answer why not use regex for xml/xhtml, please read this stackoverflow answer: https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454. ps. Don't take this comment too seriously. The answer itself is serious. ;-)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49244441

http://stackoverflow.com/q/49199987
has answer: http://stackoverflow.com/a/49200168
tagged with: 4d
has body: I have a 4D data like below. I really want to make a 4D plot with Matplotlib. The plot I am looking for is exactly like the 4D scatter plot made by @user3666197 It looks so great. I did some research but still have no idea how to make one like it. user3666197 briefly mentioned Adding { 3D | 4D | 5D } transcoding, but I have no clue how to do that. Here is the picture. A sample of my data below: X Y Z W 25 25 135 775 25 25 140 785 25 25 145 795 25 25 150 805 25 25 155 815 25 25 160 825 25 25 165 835 25 25 170 845 25 25 175 855 25 25 180 865 25 25 185 875 25 25 190 885 25 25 195 895 25 25 200 905 25 25 205 915 25 25 210 925 25 25 215 935 25 25 220 945 25 25 225 955 25 25 230 965 25 25 235 975 25 30 135 790 25 30 140 800 25 30 145 810 25 30 150 820 25 30 155 830 25 30 160 840 25 30 165 850 25 30 170 860 25 30 175 870
linked to: http://stackoverflow.com/q/45324258
score: 1
has comment: http://stackoverflow.com/comment/85405356
has comment: http://stackoverflow.com/comment/85405140
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/24123659
upvote count: 1
favorite count: 0
type: Question
has title: How to make a 4D plot using Matplotlib
has comment: http://stackoverflow.com/comment/85405278
linked to: http://stackoverflow.com/q/32764722
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
tagged with: plot

http://stackoverflow.com/comment/85266021
has text: Tool/product/tutorial recommendation questions are expressly off-topic for Stack Overflow. You'll need to choose one that's right for you. And also: this isn't a free code-writing service, and your question reads as "write this code for me" - that's not the purpose of the site.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/49130730

ethereum
type: Tag
tags question: http://stackoverflow.com/q/49230396
tag name: ethereum
tags question: http://stackoverflow.com/q/49181126

http://stackoverflow.com/comment/85483232
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49239645
has text: Will you have more than value in `value` column ?

http://stackoverflow.com/comment/85347600
has text: can you provide the error also for now what i see is you create the `c = conn.cursor()` out side the methods and using that inside of methods.
type: QuestionComment
comment on: http://stackoverflow.com/q/49171240
score: 0
type: Comment

http://stackoverflow.com/comment/85314970
comment on: http://stackoverflow.com/a/49155187
score: 2
type: AnswerComment
has text: @Chris_Rands Lists cannot be members of sets.
type: Comment

http://stackoverflow.com/q/49151547
has comment: http://stackoverflow.com/comment/85337470
linked to: http://stackoverflow.com/q/49427533
has comment: http://stackoverflow.com/comment/85336104
has comment: http://stackoverflow.com/comment/85337722
type: AnsweredQuestion
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/50211292
has comment: http://stackoverflow.com/comment/85337777
has comment: http://stackoverflow.com/comment/85335842
tagged with: scipy
has title: Quadratic or cubic 1d interpolate without large interpolator-building overhead?
type: Question
tagged with: numpy
has body: I'd like to quad or cube interpolate a long series of floats (or vectors) in 1d, where long could be 1E+05 or 1E+06 (or more). For some reason SciPi's handy interp1d()'s time overhead to prepare the interpolators scales as almost n^3 for both quadratic and cubic splines. I don't need a spline interpolator necessarily. I can write one fairly easily (at least for equal-spaced data) that just uses the closest 3 or 4 points to do a local (piecewise) quadratic or cubic interpolation, though it may end up being ugly and possibly slow. But I'm wondering if something like that exists already? Something faster to generate than the splines from interp1d? Using scipy v.0.17.0 and numpy v.1.13.0 Using a (what I thought was) recent Anaconda installation: scipy v.0.17.0 and numpy v.1.11.0 import time import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d times = [] for n in np.logspace(1, 3.5, 6).astype(int): x = np.arange(n, dtype=float) y = np.vstack((np.cos(x), np.sin(x))) start = time.clock() bob = interp1d(x, y, kind='quadratic', assume_sorted=True) times.append((n, time.clock() - start)) n, tim = zip(*times) plt.figure() plt.plot(n, tim) plt.xscale('log') plt.yscale('log') plt.show()
has comment: http://stackoverflow.com/comment/85337588
has answer: http://stackoverflow.com/a/50211292
answer count: 1
tagged with: python

http://stackoverflow.com/a/49253671
has body: I could resolve this issue. The payload has to look as follows (different quotation marks): payload = {'Email':'[MAIL]','Password':'[PASSWORD]'}
accepted answer of: http://stackoverflow.com/q/49224871
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49224871
score: 1
type: Answer

http://stackoverflow.com/q/49206815
downvote count: 0
favorite count: 0
type: Question
has body: I'm just getting to know the Wagtail. How to configure all built-in draftail formats for my Wagtail. I need to add code and qoutes.
type: UnansweredQuestion
tagged with: wagtail
tagged with: draftjs
tagged with: python
has title: Include elements of the display code and quotes in draftail for wagtail
has answer: http://stackoverflow.com/a/49207774
linked to: http://stackoverflow.com/q/49179072
upvote count: 2
score: 2
answer count: 1

http://stackoverflow.com/q/49164407
has comment: http://stackoverflow.com/comment/85334541
has comment: http://stackoverflow.com/comment/85334627
tagged with: python
score: -2
type: Question
has body: What is the best way to remove single quotes in a python list? I have the following input: ['{"name": "Brian", "city": "Seattle"}', '{"name": "Rick", "city": "Boston"}'] But i want the following output: [{"name": "Brian", "city": "Seattle"}, {"name": "Rick", "city": "Boston"}]
has comment: http://stackoverflow.com/comment/85334356
upvote count: 0
accepted answer: http://stackoverflow.com/a/49164456
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/49164456
favorite count: 0
has title: Remove single quotes in python list
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85334372

http://stackoverflow.com/a/49238260
upvote count: 0
has comment: http://stackoverflow.com/comment/102812687
downvote count: 1
answers question: http://stackoverflow.com/q/49238036
has body: When I enter pylint warnings into a web (google) search bar, the first hit is PyLint Messages, with a link to a page explaining each message.
has comment: http://stackoverflow.com/comment/85481843
type: Answer
score: -1
has comment: http://stackoverflow.com/comment/85485279

http://stackoverflow.com/comment/132833816
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49267401
type: Comment
has text: Yeah this works, but suddenly your tasks.json is not portable, and if you have many targets in your tasks.json you have to duplicate for each (so if path to venv changes that's a maintenance headache). I use an env var to set the path to my venv relative to my home directory & refer to that which helps with the duplication. Gist showing this: https://gist.github.com/pzelnip/6265212ad8190e2202d7474f05f7384a Still not portable though (if I move to a different machine & my venv is in a different path then I have to tweak my tasks.json).

http://stackoverflow.com/q/49274048
tagged with: opencv
type: AnsweredQuestion
score: 0
has body: After authorizing Google Drive, installing opencv and uploading the data in my Google Drive, I still can't read the image that I want using OpenCV Where goes wrong? Any help will be appreciated!
has answer: http://stackoverflow.com/a/49277200
tagged with: gpu
tagged with: python
type: Question
has title: Google CoLab: how to use opencv to read data from my Google drive?
accepted answer: http://stackoverflow.com/a/49277200
tagged with: google-colaboratory
answer count: 1

http://stackoverflow.com/q/49152634
tagged with: postgresql
type: Question
has body: I'm new to Django. usually, when having a many to many relationships I would create a separate table to hold the relationship can somebody explain how to do that in Django here is my attempt: a 'Etudiant' can 'Etudier' many 'Modules' a 'Modules' can be 'Etudier' by many 'Etudiant' class Etudiant(models.Model): id_etudiant = models.OneToOneField('Utilisateur', models.DO_NOTHING, db_column='id_Utilisateur', primary_key=True) id_groupe = models.ForeignKey('Groupe', models.DO_NOTHING, db_column='id_Groupe') class Meta: db_table = 'Etudiant' class Module(models.Model): id_module = models.CharField(db_column='id_Module', primary_key=True, max_length=25) titre_module = models.CharField(db_column='titre_Module', max_length=25, blank=True, null=True) uniteenseignement_module = models.CharField(db_column='uniteEnseignement_Module', max_length=25, blank=True, null=True) finsaisie_module = models.IntegerField(db_column='FinSaisie_Module', blank=True, null=True) class Meta: db_table = 'Module' class Etudier(models.Model): id_etudiant = models.ForeignKey('Etudiant', models.DO_NOTHING, db_column='id_etudiant') id_module = models.OneToOneField('Module', models.DO_NOTHING, db_column='id_Module', primary_key=True) class Meta: db_table = 'etudier' unique_together = (('id_module', 'id_etudiant'),)
has comment: http://stackoverflow.com/comment/85313516
tagged with: django
type: UnansweredQuestion
tagged with: python
tagged with: many-to-many
has title: Many to Many relationships in DJANGO with or without a relation table
score: 0
has answer: http://stackoverflow.com/a/49152679
answer count: 1
has comment: http://stackoverflow.com/comment/85309537

http://stackoverflow.com/comment/85436476
score: 0
has text: In 2nd row, `2012-05-10` is neither present in the admit date nor the corresponding Num1 is in range 5-12 why is it flagged 1??
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49164935

http://stackoverflow.com/a/49192402
score: -1
upvote count: 0
answers question: http://stackoverflow.com/q/49191798
has body: I think you are just trying to regroup it. So try something like: for i in json: for j,k in i.items(): ...
downvote count: 1
type: Answer

http://stackoverflow.com/comment/85491008
comment on: http://stackoverflow.com/q/49243497
type: Comment
type: QuestionComment
has text: I knew I was missing somthing because of the difference between QtWidgets.QPushButtin(self) and how Coord() lacked a "self"
score: 0

http://stackoverflow.com/comment/85460686
type: AnswerComment
has text: @tgmjack modified my code as i was not aware that you are reading from file hence check now.
type: Comment
comment on: http://stackoverflow.com/a/49226694
score: 0

http://stackoverflow.com/comment/85298337
has text: What is `print (type(df.loc[0, 'tweet']))` ?
comment on: http://stackoverflow.com/q/49146816
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/133788335
score: 0
has text: [xkcd.com/1172](https://xkcd.com/1172/) may also be relevant (though much less so than 292)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49155330

http://stackoverflow.com/a/49206385
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49203044
type: Answer
has body: You can try this : list1 = [0,3,5] list2 = ['a','b','c','d','e','f'] print(list(map(lambda x:list2[x],list1))) output: ['a', 'd', 'f']

http://stackoverflow.com/q/49222992
tagged with: python
tagged with: gil
has comment: http://stackoverflow.com/comment/85451629
has comment: http://stackoverflow.com/comment/85450339
type: AnsweredQuestion
score: 3
has body: i have a program where i have to print to user after each successful step my program do, i have tried using Lock but it really slow down my program. Basically what i want to do is to print to user (ordered) each a succesful operation, like i have some code that perform post to certain pages and i print that operation X has done in ordered way An example showing what im trying to do: (it seem to work) but it really slow down the task: lock = Lock() def run(u): lock.acquire() buff = [] e = requests.post('#personal_url', data=mydata) buff.append(e.text) buff.append('----------------') f = requests.get('#personal_urlx') buff.append(u + ' --&gt; ' f.text) print('\n'.join(buff)) lock.release() p = Pool(4) p.map(run, uu) p.close() p.join() I will really appreciate any help, thanks.
accepted answer: http://stackoverflow.com/a/49223567
has comment: http://stackoverflow.com/comment/85458689
has comment: http://stackoverflow.com/comment/85451030
upvote count: 3
has comment: http://stackoverflow.com/comment/85451311
has comment: http://stackoverflow.com/comment/85450842
favorite count: 0
type: Question
tagged with: multiprocessing
possible better answer: http://stackoverflow.com/a/49224304
answer count: 2
has title: Ordered status printing in multiprocessing
tagged with: locking
has comment: http://stackoverflow.com/comment/85450081
has answer: http://stackoverflow.com/a/49224304
has comment: http://stackoverflow.com/comment/85450599
has comment: http://stackoverflow.com/comment/85452181
has comment: http://stackoverflow.com/comment/85451920
tagged with: multithreading
downvote count: 0
has answer: http://stackoverflow.com/a/49223567

http://stackoverflow.com/comment/85412593
comment on: http://stackoverflow.com/a/49180565
has text: @SalahAdDin this call seems wrong `get_comments_number('slug')` because you have certain values of slugs there and not the constant key `slug`. Have a look on your code in `item = {thread['slug']: thread['posts']}`
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85428006
has text: yeah the `run()` method was added in 3.5 or 3.6 but what are the advantages compared to the `check_output()` method which returns the output directly without any need to catch it using Pipes or whatever?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49211320
score: 0

http://stackoverflow.com/comment/85471595
has text: @vipul-rao, I have edited the `parse_url` method. Check it out. Hope it helps.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49233970
type: Comment

http://stackoverflow.com/comment/85481695
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49238725
score: 1
has text: you have a fixture with the object created that hopefully will also be useful for other tests (function scope) and then you delete the object. And you test the creation separately. Just an observation (which might have to do with trying to provide a MCVE), keep in mind that your `test_put_stuff` is not really a test and is working as some sort of extended fixture.

http://stackoverflow.com/comment/85551382
type: Comment
has text: Just after calling `time.sleep(3)` at the end of the loop, grab a screenshot by calling `driver.save_screenshot('screen' + people[1] + '.png')`. This way you'll come to know what values it is saving.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49273708

http://stackoverflow.com/comment/85452341
comment on: http://stackoverflow.com/q/49224133
has text: I have adden an excerpt however to see the entire thing you just need to visit the link inside a code.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85401010
has text: I simply took the extra step with json.dump. `with open('tree_test.json', 'w') as fp: json.dump(build_tree(source.split("\n")), fp)` I know nothing of json now, but i will soon. Cheers!!!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49186411
score: 0

http://stackoverflow.com/q/49200423
type: Question
has answer: http://stackoverflow.com/a/49212961
tagged with: neural-network
tagged with: python
has body: I'm a computer science teacher currently building an introductory course on deep learning. Python and the Keras framework are my tools of choice. I'd like to show my students what is overfitting by training a model of increasing complexity on some predefined 2D data, just like at the end of this example. The same idea appears in a programming activity for Andrew Ng's course on neural networks tuning. However, no matter how hard I try, I can't replicate this behavior with Keras. Using the same dataset and hyperparameters, the decision boundaries are always "smoother" and the model never fits the noisy points in the dataset. See my results below and click here to browse the associated code. Here's the relevant extract: # Varying the hidden layer size to observe underfitting and overfitting plt.figure(figsize=(16, 32)) hidden_layer_dimensions = [1, 2, 3, 4, 5, 20, 50] for i, hidden_layer_size in enumerate(hidden_layer_dimensions): fig = plt.subplot(4, 2, i+1) plt.title('Hidden Layer size: {:d}'.format(hidden_layer_size)) model = Sequential() model.add(Dense(hidden_layer_size, activation='tanh', input_shape=(2,))) model.add(Dense(1, activation='sigmoid')) model.compile(SGD(lr=1.0), 'binary_crossentropy', metrics=['accuracy']) history = model.fit(data, targets, verbose=0, epochs=50) plot_decision_boundary(lambda x: model.predict(x) &gt; 0.5, data, targets, fig) Am I doing something wrong? Are there some internal optimization mechanisms in Keras kicking in? Can I mitigate them with other compilation choices?
has comment: http://stackoverflow.com/comment/85409695
accepted answer: http://stackoverflow.com/a/49212961
has answer: http://stackoverflow.com/a/49245043
type: AnsweredQuestion
has title: Demonstrating overfitting with Keras on 2D data
answer count: 3
score: 1
downvote count: 0
possible better answer: http://stackoverflow.com/a/49202166
upvote count: 1
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/85406068
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/49202166

http://stackoverflow.com/comment/85377447
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49185727
type: Comment
has text: please do not post pictures of code. Take the time to copy, paste, and format the code.

http://stackoverflow.com/comment/85417545
has text: Alternatively, consider using `QCoreApplication` when running the unit tests.
type: Comment
comment on: http://stackoverflow.com/q/49184586
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85335395
comment on: http://stackoverflow.com/q/49159619
has text: backtrace is pretty long, pasting in multiple comments: >>>>>>>>>>>>>>>> frame #0: 0x00007fffa478cb1a libsystem_kernel.dylib`__posix_spawn + 10 frame #1: 0x00007fffa4787ed5 libsystem_kernel.dylib`posix_spawn + 386 frame #2: 0x00007fffa4713e10 libsystem_c.dylib`system + 418 frame #3: 0x0000000101b20469 multiarray.so`loadlib + 57 frame #4: 0x0000000100019a1b dyld`ImageLoaderMachO::doModInitFunctions(ImageLoader::LinkContext const&) + 385 frame #5: 0x0000000100019c1e dyld`ImageLoaderMachO::doInitialization(ImageLoader::LinkContext const&) + 40
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85325881
type: AnswerComment
has text: Can we do similar min function instead of max , to find minimum of values
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49159640

http://stackoverflow.com/a/49151605
type: AcceptedAnswer
type: Answer
score: 0
has body: You can use: first concat columns c1, c2, sort and if necessary remove duplicated merge both DataFrames by left join last repeat values by ffill and bfill df = (pd.concat([df1'c1','c2', df2'c1','c2']) .sort_values(['c1','c2']) .drop_duplicates() .merge(df1, on=['c1','c2'], how='left') .merge(df2, on=['c1','c2'], how='left') ) df'c4','c5' = df.groupby('c1')['c4','c5'].apply(lambda x: x.ffill().bfill()) print (df) c1 c2 c4 c5 c6 c7 0 10 1 hh 2231.0 NaN NaN 1 10 2 hh 2231.0 110.0 231.0 2 10 3 hh 2231.0 111.0 332.0 3 11 1 fgf 2142.0 NaN NaN 4 11 2 fgf 2142.0 112.0 123.0 5 11 3 fgf 2142.0 113.0 432.0 6 12 1 fg 1232.0 NaN NaN 7 12 2 fg 1232.0 114.0 432.0 8 12 3 fg 1232.0 115.0 432.0 9 13 2 NaN NaN 116.0 432.0 10 13 3 NaN NaN 117.0 432.0 11 14 2 NaN NaN 118.0 432.0 12 14 3 NaN NaN 119.0 432.0
accepted answer of: http://stackoverflow.com/q/49147103
answers question: http://stackoverflow.com/q/49147103

http://stackoverflow.com/q/49257445
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0
tagged with: python
tagged with: cmake
tagged with: c++
has title: Segmentation fault on execution of C++ code from Python – using Boost.Python on Mac OS
has comment: http://stackoverflow.com/comment/85531529
score: 1
tagged with: boost
has body: I am trying to write a library in C++ so that one could work with its methods from Python (especially jupyter notebooks) on different platforms. For this purpose I am using Boost.Python. I am debugging my code on my laptop with macOS Sierra 10.12.6. I was able to compile my sources into a .so library, but regretfully its methods crash when I call them. I installed Boost and Boost.Python libraries with the following sequence of commands: brew install --build-from-source --with-python --fresh -vd boost brew install boost-python After that, I took the following simple C++ code (main.cpp): #include &lt;boost/python.hpp&gt; using namespace boost::python; #include &lt;string&gt; namespace { std::string greet() { return "hello, world"; } int square(int number) { return number * number; } } BOOST_PYTHON_MODULE(boost_python_example) { def("greet", greet); def("square", square); } And created a CMakeLists.txt (cmake verison is 3.9.6): cmake_minimum_required(VERSION 3.0) set(CMAKE_BUILD_TYPE Release) if(APPLE) set(CMAKE_SHARED_LIBRARY_SUFFIX ".so") endif(APPLE) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -v -lstdc++ -lpython2.7 -lboost_python") include_directories(${CMAKE_CURRENT_SOURCE_DIR}) add_library(boost_python_example SHARED main.cpp) set_target_properties(boost_python_example PROPERTIES PREFIX "") Then, by executing make clean &amp;&amp; cmake . &amp;&amp; make, I obtained the desired library boost_python_example.so and added the path to it to PYTHONPATH. Now my code can be successfully imported from Python, but it crashes in various ways on the execution of the methods: user-osx1:BoostPythonTest user$ python Python 2.7.14 |Anaconda, Inc.| (default, Oct 5 2017, 02:28:52) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import boost_python_example &gt;&gt;&gt; from boost_python_example import * &gt;&gt;&gt; square(5) Segmentation fault: 11 user-osx1:BoostPythonTest user$…
answer count: 1
has comment: http://stackoverflow.com/comment/85524848
upvote count: 1
linked to: http://stackoverflow.com/q/8451334
has answer: http://stackoverflow.com/a/49258592

http://stackoverflow.com/a/53406072
type: Answer
answers question: http://stackoverflow.com/q/49184578
score: 145
upvote count: 145
has body: I think a decode is also required to get a proper dict. a= b"{'one': 1, 'two': 2}" ast.literal_eval(a.decode('utf-8')) **Output:** {'one': 1, 'two': 2} The accepted answer yields a= b"{'one': 1, 'two': 2}" ast.literal_eval(repr(a)) **output:** b"{'one': 1, 'two': 2}" The literal_eval hasn't done that properly with many of my code so I personally prefer to use json module for this import json a= b"{'one': 1, 'two': 2}" json.loads(a.decode('utf-8')) **Output:** {'one': 1, 'two': 2}
downvote count: 0

http://stackoverflow.com/q/49199100
has comment: http://stackoverflow.com/comment/85403547
has comment: http://stackoverflow.com/comment/85436608
has comment: http://stackoverflow.com/comment/85405229
score: 0
has title: Elasticsearch painless script query loop
answer count: 0
tagged with: java
has comment: http://stackoverflow.com/comment/85403704
type: Question
has comment: http://stackoverflow.com/comment/85404614
has body: We are currently building a search tool based on elasticsearch and our query involves matching nearest value to user input values. Say user inputs [1,10,100,1000,10000] it should return closest value available in our index to each of those elements in the array. Right now we are using the following query to retrieve values one at a time and we are passing user input array via loop and its really slow. { "query": { "term": {"CHR": "chr1"} }, "sort" : { "_script" : { "type" : "number", "script" : { "lang": "painless", "params": { "factor": 10000 }, "inline": "def cur = 0; cur = (params.factor - doc['START'].value); if (cur &lt; 0) { cur = cur * -1 } else { cur = cur}" }, "order" : "asc" } } } Our requirement is that the factor would take an array of integers rather than a single value and gives our the first closest value that it finds in our index. The complete python function is posted below (Python) def gene_peek(coordinate, chr): peek_liver = [] for i in range(0,len(coordinate)): a = int(coordinate[i]) res = requests.post("http://localhost:9200/lab/peek_liver/_search?pretty=true&amp;scroll=10m&amp;size=1", json={ "query": { "term": {"CHR": chr[i]} }, "sort" : { "_script" : { "type" : "number", "script" : { "lang": "painless", "params": { "factor": a }, "inline": "def cur = 0; cur = (params.factor - doc['START'].value); if (cur &lt; 0) { cur = cur * -1 } else { cur = cur}" }, "order" : "asc" } } }) data = res.json() peek_liver.append(data["hits"]["hits"][0]["_source"]) return peek_liver Any help would be greatly appreciated. Thanks.
tagged with: elasticsearch-painless
type: UnansweredQuestion
tagged with: elasticsearch
tagged with: python
tagged with: lucene

http://stackoverflow.com/comment/85275117
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49133591
score: 0
has text: If [0,1,2,3,4,5] are logically connected I would put them in a SequenceExample. You can extract the subsequences afterwards.

http://stackoverflow.com/q/49176873
has comment: http://stackoverflow.com/comment/85364389
has title: Remove div tag using BeautifulSoup but keep contents
type: UnansweredQuestion
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85361399
upvote count: 4
score: 3
has body: Using Python/BeautifulSoup I would like to just remove an outer div tag but retain it's contents. So starting with this: Paragraph 1 Paragraph 2 Would end up like this. Paragraph 1 Paragraph 2 I feel like this should be simple but can't find a way to do it..
has comment: http://stackoverflow.com/comment/85361207
has comment: http://stackoverflow.com/comment/85363155
downvote count: 1
has answer: http://stackoverflow.com/a/49209366
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/85289234
comment on: http://stackoverflow.com/q/49141621
type: Comment
has text: Hi @RamazanPolat and thanks for your help too! Anyway, for the first point, I checked in the about Firefox Tab and I confirmed that the Firefox version is the 52.6.0 (64-bit). Lastly, I tried to install GeckoDriver by making it executable with chmod a+x geckodriver but the error message remains.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85377373
comment on: http://stackoverflow.com/q/49185572
type: Comment
score: 0
type: QuestionComment
has text: Thank eagle, I will try this

http://stackoverflow.com/comment/85427068
type: QuestionComment
has text: All elements in all columns specified. x is applied on a per column basis. `x.min()` and `x.max()` I have no knowledge of. They will have no wider scope than the column which `apply` is currently applying to.
score: 1
comment on: http://stackoverflow.com/q/49211337
type: Comment

http://stackoverflow.com/comment/85458920
type: Comment
comment on: http://stackoverflow.com/a/49227597
type: AnswerComment
has text: if I recall math.nan if you import the math module will give you: nan. If you want it formatted the way that your original code was, you can do the string 'NaN'. And if you want something such as None you can just set the value = to None. I'm assuming one of those options will work for you.
score: 0

http://stackoverflow.com/a/49249910
downvote count: 1
has comment: http://stackoverflow.com/comment/85516543
has body: Comparison with astype(int) Tentatively convert your column to int and test with np.array_equal: np.array_equal(df.v, df.v.astype(int)) True float.is_integer You can use this python function in conjunction with an apply: df.v.apply(float.is_integer).all() True Or, using python's all in a generator comprehension, for space efficiency: all(x.is_integer() for x in df.v) True
has comment: http://stackoverflow.com/comment/85503807
has comment: http://stackoverflow.com/comment/107821829
has comment: http://stackoverflow.com/comment/85517403
score: 54
type: Answer
has comment: http://stackoverflow.com/comment/139929797
answers question: http://stackoverflow.com/q/49249860
has comment: http://stackoverflow.com/comment/139929785
type: AcceptedAnswer
upvote count: 55
accepted answer of: http://stackoverflow.com/q/49249860
has comment: http://stackoverflow.com/comment/85503732

http://stackoverflow.com/comment/85384037
comment on: http://stackoverflow.com/q/49188279
has text: Can always do it for you ;)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85527760
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49261990
type: QuestionComment
has text: Yikes. Sorry. I'm editing it right away.

http://stackoverflow.com/comment/85263185
comment on: http://stackoverflow.com/q/49129300
score: 3
type: Comment
has text: is this module somewhere in your python (environment?) path? If it is not you need to make a relative import `from .p1 import file1`. If it is, you can import it with `from sandbox.p1 import file1`
type: QuestionComment

http://stackoverflow.com/comment/85932931
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49460859
has text: I played around with the calibration values a bit and found room to make the posted results even closer to the expected values. Map key 77 seems the best (although 78 is close too but causes the results to be a bit high) but the results are slightly low, and by using a scale of around 100175 this increases the values marginally. No questions? You are able to port this code to python?
type: Comment

http://stackoverflow.com/q/49178610
score: 2
upvote count: 3
tagged with: tfrecord
has title: Getting "AttributeError: 'MapDataset' object has no attribute 'prefetch'" when trying to decode tensorflow data
downvote count: 1
tagged with: tensorflow
tagged with: tensorflow-datasets
favorite count: 0
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49237537
answer count: 1
tagged with: python
has body: I have a trained model and I am trying to run testing but I keep getting an error. This is my function that decodes the TFRecord data: def getTestData(filename, dataSize, batch_size): dataset = tf.contrib.data.TFRecordDataset(filename).map(decodeTest).prefetch(batch_size) dataset = dataset.shuffle(dataSize) dataset = dataset.batch(batch_size) return dataset This is the error I got: Traceback (most recent call last): File "&lt;ipython-input-1-2f1981301a24&gt;", line 1, in &lt;module&gt; runfile('H:/Documents/project/main.py', wdir='H:/Documents/project') File "C:\apps\Miniconda2\envs\tensorflowGPU\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile execfile(filename, namespace) File "C:\apps\Miniconda2\envs\tensorflowGPU\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "H:/Documents/project/main.py", line 44, in &lt;module&gt; ts.test(netOut,x,y,sess, testSize,0) File "H:\Documents\project\testing\test.py", line 14, in test dataset = d.getTestData(test, testSize, 1) File "H:\Documents\project\readTF\readDataTF.py", line 26, in getTestData dataset = tf.contrib.data.TFRecordDataset(filename).map(decodeTest).prefetch(batch_size) AttributeError: 'MapDataset' object has no attribute 'prefetch' Then i removed the .prefetch(batch_size) and got this error instead. Traceback (most recent call last): File "&lt;ipython-input-1-2f1981301a24&gt;", line 1, in &lt;module&gt; runfile('H:/Documents/project/main.py', wdir='H:/Documents/project') File "C:\apps\Miniconda2\envs\tensorflowGPU\lib\site-packages\spyder\utils\site\sitecustomize.py", line 880, in runfile execfile(filename, namespace) File "C:\apps\Miniconda2\envs\tensorflowGPU\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "H:/Documents/project/main.py", line 44, in &lt;module&gt; ts.test(netOut,x,y,sess, testSize,0) File "H:\Docum…

http://stackoverflow.com/q/49190525
downvote count: 0
has answer: http://stackoverflow.com/a/56114311
favorite count: 0
type: Question
tagged with: python-asyncio
linked to: http://stackoverflow.com/q/40571786
accepted answer: http://stackoverflow.com/a/49191200
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/49191200
has body: I want to implement an awaitable and noticed that __await__ 'needs' to be a generator. From PEP-492: An object with an __await__ method returning an iterator. ... Objects with __await__ method are called Future-like objects in the rest of this PEP. It is a TypeError if __await__ returns anything but an iterator. In my experience, before await was a statement, yield from was used together with coroutines implemented as generators. Nowadays python (I'm using 3.5) has asynchronous methods using the async def syntax. I therefore consider the yield from syntax as old/deprecated. So I broke out the interpreter to see how/if this works: &gt;&gt;&gt; class A: ... def __await__(self): ... yield from (asyncio.sleep(1).__await__()) ... return 'spam' ... &gt;&gt;&gt; a = A() &gt;&gt;&gt; loop = asyncio.get_event_loop() &gt;&gt;&gt; loop.run_until_complete(a) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib64/python3.5/asyncio/base_events.py", line 467, in run_until_complete return future.result() File "/usr/lib64/python3.5/asyncio/futures.py", line 294, in result raise self._exception File "/usr/lib64/python3.5/asyncio/tasks.py", line 240, in _step result = coro.send(None) File "/usr/lib64/python3.5/asyncio/tasks.py", line 585, in _wrap_awaitable return (yield from awaitable.__await__()) File "&lt;stdin&gt;", line 3, in __await__ AttributeError: 'generator' object has no attribute '__await__' So it appears asyncio.sleep doesn't have the __await__ method. It also feels very awkward to use this yield from syntax. So I decided to try with the async syntax, just to see if it would work: &gt;&gt;&gt; class A: ... async def __await__(self): ... await asyncio.sleep(1) ... return 'spam' ... &gt;&gt;&gt; a = A() &gt;&gt;&gt; &gt;&gt;&gt; loop = asyncio.get_event_loop() &gt;&gt;&gt; loop.run_until_complete(a) 'spam' It actually seems to work! So now I'm wondering, does the __await__ method really need to be a generator using the yield from…
has title: Does __await__ need to be a generator?
upvote count: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/42917109
answer count: 2
tagged with: python-3.5
possible better answer: http://stackoverflow.com/a/56114311

http://stackoverflow.com/a/49177793
type: Answer
has body: It looks like the port is added twice to the socks_proxy_string - so it will end with ...compute-1.amazonaws.com:3128:8181 If you have tunnel on localhost, then socks_proxy_string should be socks5://localhost:9191
has comment: http://stackoverflow.com/comment/85362237
answers question: http://stackoverflow.com/q/49177677
has comment: http://stackoverflow.com/comment/85368295
has comment: http://stackoverflow.com/comment/85362143
has comment: http://stackoverflow.com/comment/85364644
score: 0

http://stackoverflow.com/q/49236977
score: 0
has body: I have to boost the time for an interpolation over a large (NxMxT) matrix MTR, where: N is about 8000; M is about 10000; T represents the number of times at which each NxM matrix is calculated (in my case it's 23). I have to compute the interpolation element-wise, on all the T different times, and return the interpolated values over a different array of times (T_interp, in my case with lenght 47) so, as output, I want an NxMxT_interp matrix. The code snippet below defines the function I built for the interpolation, using scipy.interpolate.Rbf (y is the array MTR[i,j,:], x is the times array with length T, x_interp is the new array of times with length T_interp: #============================================================================== # Interpolate without nans #============================================================================== def interp(x,y,x_interp,**kwargs): import numpy as np from scipy.interpolate import Rbf mask = np.isnan(y) y_mask = np.ma.array(y,mask = mask) x_new = [x[i] for i in np.where(~mask)[0]] if len(y_mask.compressed()) == 0: return [np.nan for i,n in enumerate(x_interp)] elif len(y_mask.compressed()) == 1: return [y_mask.compressed() for i,n in enumerate(x_interp)] interp = Rbf(x_new,y_mask.compressed(),**kwargs) y_interp = interp(x_interp) return y_interp I tried to achieve my goal either by looping over the NxM elements of the MTR matrix: new_MTR = np.empty((N,M,T_interp)) for i in range(N): for j in range(M): new_MTR[i,j,:]=interp(times,MTR[i,j,:],New_times,function = 'linear') or by using the np.apply_along_axis funtion: new_MTR = np.apply_along_axis(lambda x: interp(times,x,New_times,function = 'linear'),2,MTR) In both cases I extimated the time it takes to perform the whole operation and it appears to be slightly better for the np.apply_along_axis function, but still it will take about 15 hours!! Is there a way to reduce this time? Maybe by vectorizing the entire operation? I don't know much about vectorizing and how it can …
tagged with: interpolation
has comment: http://stackoverflow.com/comment/85477307
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: vectorization
has comment: http://stackoverflow.com/comment/85506539
has comment: http://stackoverflow.com/comment/85492147
has title: Vectorizing or boosting time for an interpolation in Python

http://stackoverflow.com/comment/85436962
comment on: http://stackoverflow.com/q/49215833
type: Comment
score: 0
has text: @shuwnyuantee yes, I stated that in my question above too.
type: QuestionComment

http://stackoverflow.com/comment/85262678
comment on: http://stackoverflow.com/q/49129050
score: 0
has text: @cᴏʟᴅsᴘᴇᴇᴅ so there are no differences in terms of performance between B() and B2() or are you just referring to A()?
type: Comment
type: QuestionComment

sql
tags question: http://stackoverflow.com/q/49242759
tags question: http://stackoverflow.com/q/49137152
tags question: http://stackoverflow.com/q/49236731
tags question: http://stackoverflow.com/q/49150698
tags question: http://stackoverflow.com/q/49200845
tags question: http://stackoverflow.com/q/49138864
tags question: http://stackoverflow.com/q/49223150
tags question: http://stackoverflow.com/q/49193680
tags question: http://stackoverflow.com/q/49213003
tags question: http://stackoverflow.com/q/49266143
tags question: http://stackoverflow.com/q/49137057
tags question: http://stackoverflow.com/q/49201920
tags question: http://stackoverflow.com/q/49246721
tags question: http://stackoverflow.com/q/49171240
tags question: http://stackoverflow.com/q/49189836
tags question: http://stackoverflow.com/q/49169497
tags question: http://stackoverflow.com/q/49268763
tag name: sql
tags question: http://stackoverflow.com/q/49276547
tags question: http://stackoverflow.com/q/49175720
type: Tag
tags question: http://stackoverflow.com/q/49139458
tags question: http://stackoverflow.com/q/49240140
tags question: http://stackoverflow.com/q/49181433
tags question: http://stackoverflow.com/q/49142767

http://stackoverflow.com/comment/85267611
has text: Can you describe in plain language how it should behave?
type: Comment
score: 2
comment on: http://stackoverflow.com/q/49131518
type: QuestionComment

http://stackoverflow.com/comment/85442751
type: QuestionComment
comment on: http://stackoverflow.com/q/49219019
has text: Have you had a look at the [Troubleshooting](https://pypi.python.org/pypi/SpeechRecognition/) section of the documentation? Maybe it's trying to recognize too much, which, via internet, would obviously slow things down and cause misses. Are you sure it starts recognition on speech only?
score: 1
type: Comment

http://stackoverflow.com/q/49240103
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49240386
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: Suppose I have the following: I'd like to return foo bar I cannot seem to strip the comments in questions. I can access those comments: soup = BeautifulSoup(xlf, "lxml") comments = soup.find_all(text=lambda text: isinstance(text, Comment)) for comment in comments: print(comment) but cannot return the souped object with those changes. Any help would be greatly appreciated.
tagged with: python
has comment: http://stackoverflow.com/comment/85484149
has title: Replace a named comment using BS4

http://stackoverflow.com/q/49172072
score: 0
answer count: 3
upvote count: 1
tagged with: python
has title: Sort list based on a subset list (without nested loops)
accepted answer: http://stackoverflow.com/a/49172869
possible better answer: http://stackoverflow.com/a/49172470
type: Question
downvote count: 1
tagged with: loops
tagged with: string
tagged with: sorting
has body: I'm trying to sort a long list of labels based on a master list, and am struggling to implement this efficiently. As the example below shows, I want to group together all items in the long list which share a common start to the string, then create a new list with these in the same order as the "master list". With Python I'd normally try to vectorize and parallel process arrays, but this seems to work less well for arrays based on strings. Here is my example and solution using nested loops: fruits = ['apple', 'banana', 'orange'] # "master list" labels = ['banana2', 'apple2', 'orange1', 'banana1', 'apple1', 'apple3'] # "long list" new_list = [] for fruit in fruits: for label in labels: if fruit in label: new_list.append(label) print(new_list) then returns ['apple2', 'apple1', 'apple3', 'banana2', 'banana1', 'orange1'] Can this be done without nested loops? For an added bonus, I'd ideally like the labels to be sorted based on the final number in the string too, e.g. giving the result: ['apple1', 'apple2', 'apple3', 'banana1', 'banana2', 'orange1']
has answer: http://stackoverflow.com/a/49172251
favorite count: 0
has answer: http://stackoverflow.com/a/49172470
has answer: http://stackoverflow.com/a/49172869
type: AnsweredQuestion

http://stackoverflow.com/a/49477242
type: Answer
answers question: http://stackoverflow.com/q/49235442
has comment: http://stackoverflow.com/comment/86726508
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85957086
has body: All your site packages aren't stored in the qpython folder especially if you are not using an external sdcard On my phone all libraries are stored in "/data/data/org.qpython.qpy/files/lib/python2.7/site-packages" path If you cant access this path on your phone ,then you need to root your phone
score: 0
accepted answer of: http://stackoverflow.com/q/49235442

http://stackoverflow.com/comment/124578320
type: QuestionComment
comment on: http://stackoverflow.com/q/49185065
has text: I was wondering if it was possible to do a "input_processor"/"output_processor" in the file "item.py" to do this job.
score: 0
type: Comment

http://stackoverflow.com/comment/85353977
type: AnswerComment
comment on: http://stackoverflow.com/a/49173106
has text: So the primary key isn't valid due to you adding a value to it: `code: File "C:\Users\Owner\eclipse-workspace\Diss\db.py", line 31, in <module> data_entry() File "C:\Users\Owner\eclipse-workspace\Diss\db.py", line 22, in data_entry c.execute("INSERT INTO illnesses(illnessID, illness , illnessinfo) VALUES(1,'Flu','Influenza - Common Cold.')") sqlite3.IntegrityError: UNIQUE constraint failed: illnesses.illnessID`
type: Comment
score: 0

http://stackoverflow.com/q/49216060
favorite count: 0
has title: Get all elements in a Python list starting from an index
tagged with: indexing
type: Question
has comment: http://stackoverflow.com/comment/85436193
has answer: http://stackoverflow.com/a/49216087
duplicate of: http://stackoverflow.com/q/509211
tagged with: python
type: UnansweredQuestion
tagged with: list
score: 0
has body: Say I have a list arr and an index i within [0:len(arr)], how do I get all the elements starting from arr[i] up to arr[-1] in a Pythonic way? For example: arr = 'abcdef' i = 3 I basically want to get b = 'def' I tried b = a[i:-1] but obviously that'll leave out the last element. Also, my list sometimes has only 1 element, so i = 0. How do I safely treat that edge case? Thank you!
upvote count: 1
linked to: http://stackoverflow.com/q/509211
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85436198

http://stackoverflow.com/q/49214286
answer count: 3
has answer: http://stackoverflow.com/a/49215716
tagged with: pandas
score: 1
downvote count: 0
upvote count: 1
has title: Find common values between 3 DataFrames?
has answer: http://stackoverflow.com/a/49214519
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49214312
possible better answer: http://stackoverflow.com/a/49214519
tagged with: counter
has answer: http://stackoverflow.com/a/49214312
tagged with: dataframe
tagged with: python
has body: I have 3 dataframes: df1, df2, and df3. df1 = 'num' 'type' 23 a 34 b 89 a 90 c df2 = 'num' 'type' 23 a 34 b 56 a 90 c df3 = 'num' 'type' 56 a 34 s 71 a 90 c What I want is an output of all of the 'num' values which appear in 2 or more of the dfs, and I want to flag how many dfs that 'num' value appeared in. So I want something like this: df = 'num' 'type' 'count' 23 a 2 34 s 3 90 c 3 56 a 2 I tried doing an inner merge, but that only accounts for 'num' values that appear in all 3 dfs, ignoring the ones that appear in 2/3 dfs. What's the best way to go about this?
type: AnsweredQuestion

http://stackoverflow.com/q/49247648
tagged with: python
tagged with: dictionary
has title: Python creating a dictionary from a csv file
has comment: http://stackoverflow.com/comment/85499075
type: AnsweredQuestion
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/49247748
accepted answer: http://stackoverflow.com/a/49247748
type: Question
has comment: http://stackoverflow.com/comment/85499166
tagged with: http://stackoverflow.com/tag/csv
has body: I am trying to create a data dictionary from a csv file and am having some trouble. I have successfully been able to make a dictionary from two lists in my program below is my code: playerRank = [[tournamentResults[i],rankingPoints[8]] for i in range(0,len(tournamentResults))] dict1 = dict(playerRank) However, when I attempt to make a dictionary out of data I have in a csv file I get an error 'TypeError: unhashable type: 'list''. Below is the code I tried: totalRank = [] with open("mycsvfile.csv") as players: for row in csv.reader(players): totalRank.append(row) totalRank = [[totalRank[i],0] for i in range(0,len(totalRank))] dict2 = dict(totalRank) I don't understand why the second attempt at making a dictionary is throwing back the error whereas, the first dictionary is fine? Any help on how I could resolve this would be greatly appreciated!

http://stackoverflow.com/comment/85358221
type: AnswerComment
comment on: http://stackoverflow.com/a/49175797
type: Comment
has text: To list all duplicates (i.e. found more than once) across all files would require different logic and would require all data to be read in before the output file is created.
score: 0

http://stackoverflow.com/q/49153387
has answer: http://stackoverflow.com/a/49153522
favorite count: 0
has comment: http://stackoverflow.com/comment/138996342
tagged with: python
has title: Python : read excel in python with default module
type: Question
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49157117
answer count: 2
upvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/7465445
has body: I have Python 2.6.6 version and I don't have access to install new modules like pandas,xlrd,xlwt. I want to read Excel using Python . Is it possible to read Excel using Python with default modules present in Python.
downvote count: 3
score: -3
has comment: http://stackoverflow.com/comment/85328409

http://stackoverflow.com/comment/85506093
comment on: http://stackoverflow.com/q/49251023
type: Comment
type: QuestionComment
score: 0
has text: @Malik thanks very much, I will try it now.

http://stackoverflow.com/comment/85532344
type: Comment
has text: Yes, on Python 3.
comment on: http://stackoverflow.com/a/49264259
score: 0
type: AnswerComment

http://stackoverflow.com/comment/102325564
comment on: http://stackoverflow.com/a/53853872
score: 0
type: AnswerComment
has text: You deserve a medal
type: Comment

http://stackoverflow.com/q/49205375
has comment: http://stackoverflow.com/comment/85416179
has title: mysql-python install error: Cannot open include file: 'config-win.h
has comment: http://stackoverflow.com/comment/91995426
answer count: 1
downvote count: 0
tagged with: mysql
has body: Hi, Im trying to pip install mysql-python and I keep getting an error. I was wondering if anyone knows what I need to do get this working? I'm using Windows 10, python 3.6 and mysql 5.7. I'm new to coding so if there is something I missed please let me know. Thanks This is the error I keep getting: _mysql.c(42): fatal error C1083: Cannot open include file: 'config-win.h': No such file or directory error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.13.26128\bin\HostX86\x64\cl .exe' failed with exit status 2
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/53422604
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85416145
linked to: http://stackoverflow.com/q/37092125
tagged with: django
has comment: http://stackoverflow.com/comment/85416078
tagged with: python

http://stackoverflow.com/q/49258986
has answer: http://stackoverflow.com/a/49261081
has comment: http://stackoverflow.com/comment/85521491
has comment: http://stackoverflow.com/comment/85521113
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49261057
has answer: http://stackoverflow.com/a/49259072
has comment: http://stackoverflow.com/comment/85521388
has comment: http://stackoverflow.com/comment/85521163
tagged with: python
upvote count: 6
answer count: 4
score: 4
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85521174
has body: Suppose we have x = ['a', 'b']. What is happening under the hood for the statement: x not in {None, False} that raises the unhashable type: 'list' error? The workaround I found is to write this instead: x != None and x!= False but I am confused because, mathematically, both boolean expressions are equivalent.
has title: x not in set versus x != each element in the set?
has comment: http://stackoverflow.com/comment/85521201
linked to: http://stackoverflow.com/q/82831
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/85521202
has comment: http://stackoverflow.com/comment/85541682
linked to: http://stackoverflow.com/q/3460650
has answer: http://stackoverflow.com/a/49259194

http://stackoverflow.com/comment/85493037
type: QuestionComment
has text: yes, apologies - check my updated question with function code
comment on: http://stackoverflow.com/q/49244476
score: 0
type: Comment

http://stackoverflow.com/a/49269748
type: Answer
has body: The result of sys.stdout.write isn't very useful—it's just the number of characters in whatever you wrote. Of course you can store that in a global variable: written = 0 def myfunc(): global written written += sys.stdout.write(blahblah) … but I can't see why you'd want to. What sys.stdout.write writes to the terminal (or redirected file, or whatever) seems a lot more useful. But you already have that. You're doing this: sys.stdout.write(output) So, what it writes is going to be exactly what's in output. So just store that. For example: outputs = [] def myfunc(): global outputs output = blah blah blah sys.stdout.write(output) outputs.append(output) Now, if you have no control over the function that's writing stuff, because it's in some library that you're not allowed to modify or something, you can capture its output. This is usually not a good idea, but if you need to, you can write a wrapper around the real sys.stdout that saves the output and then passes it through to the real thing (or doesn't, if you don't want it to hit the screen), and then just assign sys.stdout = mywrapper. But if you can't figure out how to write that, you almost certainly don't want to.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49268740
score: 1

ml-studio
tags question: http://stackoverflow.com/q/49188966
tag name: ml-studio
type: Tag

http://stackoverflow.com/a/49204699
score: 3
has body: python list are 0 indexed so you need to use. while l &lt; len(ordenado): for your case for loop is more suitable. mylist = ['a', 'b', 'c'] for i, item in enumerate(mylist): print(i, item) #where i will be 0,1,2 and item will be a,b,c
answers question: http://stackoverflow.com/q/49204669
accepted answer of: http://stackoverflow.com/q/49204669
type: Answer
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85417018
has comment: http://stackoverflow.com/comment/85418301

http://stackoverflow.com/comment/85479098
type: Comment
comment on: http://stackoverflow.com/q/49225195
type: QuestionComment
has text: @andilabs I saw it a few minutes ago and upvoted, thank you! I get the idea. I am currently trying to make ends meet with the "save to server" bit of the equation and something like [this approach](https://stackoverflow.com/a/13737176/2996101) seems to be a good idea.
score: 0

http://stackoverflow.com/a/49226880
answers question: http://stackoverflow.com/q/49226804
score: 0
has body: The reason you have all 4 outputs and then the code exiting is because you call all four home_act functions immediately by doing action(home_act1(), home_act2(), home_act3(), home_act4()), which executes one after another and exits the program due to the exit() in home_act4(). Another thing that is problematic is that you return after each action within the while-loop, which means the code would have stopped once the user has done one single action. Fixing these problems results in the following code: def action(): loop = True while loop: #print(menu) player_action = input("Where would you like to go? ") if player_action == '1': home_act1() # call the respective action function here elif player_action == '2': home_act2() elif player_action == '3': home_act3() elif player_action == '4': home_act4() else: print("Please type \'1\', \'2\', \'3\', or \'4\'") def home_act1(): print("Welcome to the wilderness!") def home_act2(): print("Welcome to the town!") def home_act3(): print("Welcome to the store!") def home_act4(): print("You left the adventure.") exit() action() Good luck with further coding :)
type: Answer

http://stackoverflow.com/a/57407013
has comment: http://stackoverflow.com/comment/101295019
has comment: http://stackoverflow.com/comment/117584599
has body: At least one example isn't an image. You can check the datatype before feeding the image to the Neural Network. I'm doing it with the library imghdr: Code: import imghdr import os l_FileNames = os.listdir("images_path") for image in l_FileNames: if not imghdr.what(image) == "png": l_FileNames.remove(image)
type: Answer
upvote count: 4
score: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/101295056
answers question: http://stackoverflow.com/q/49227501

http://stackoverflow.com/a/49139198
type: Answer
accepted answer of: http://stackoverflow.com/q/49136816
has body: "Destroy window not closing all windows properly" Nor should it. destroy method destroys a widget, and when a widget is destroyed so are its children. Since neither frame1 nor frame2 are 'windows' or a window's parents, there's no window destruction taking place. "When I click "Run" I need to close all windows and need to execute another script in the same directory. Is that possible to do it?" It is possible. Use quit on any GUI object, instead of destroy. It stops the mainloop, hence destroying the entire GUI. In that it solves the first problem as well. Then import another_script: ... def close_window(): frame1.quit() ... root.mainloop() import another_script
answers question: http://stackoverflow.com/q/49136816
type: AcceptedAnswer
downvote count: 0
upvote count: 1
score: 1

readfile
tags question: http://stackoverflow.com/q/49263508
type: Tag
tag name: readfile

http://stackoverflow.com/a/49181534
score: 0
answers question: http://stackoverflow.com/q/49179118
has body: You can do doc.to_bytes() to serialize the annotations, and then load them back with doc.from_bytes() However for your purpose you should probably just save the doc.vector. If you have a lot of pairwise similarities to compute, have a look at an approximate nearest neighbours solution such as the annoy library.
type: Answer

http://stackoverflow.com/comment/85442694
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49219352
type: AnswerComment
has text: Sorry, this is the output of 1 of the lines: dict_keys(['contributors', 'truncated', 'text', 'is_quote_status', 'in_reply_to_status_id', 'id', 'favorite_count', 'source', 'retweeted', 'coordinates', 'entities', 'in_reply_to_screen_name', 'in_reply_to_user_id', 'retweet_count', 'id_str', 'favorited', 'retweeted_status', 'user', 'geo', 'in_reply_to_user_id_str', 'possibly_sensitive', 'lang', 'created_at', 'in_reply_to_status_id_str', 'place', 'extended_entities'])

http://stackoverflow.com/q/49211863
tagged with: web-scraping
has answer: http://stackoverflow.com/a/49215100
accepted answer: http://stackoverflow.com/a/49215100
type: Question
linked to: http://stackoverflow.com/q/33618324
tagged with: python
has title: Scrape latitude and longitude of address obtained from Mapbox
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85431482
has body: I'm working on my first open source project https://github.com/raybellwaves/cfanalytics I want to scrape information for each gym (affiliate) from here https://map.crossfit.com/ . This answer on SO helped me to get the metadata for each affiliate from the map e.g. https://map.crossfit.com/getAffiliateInfo?aid=9347 (which gives address, city, state, zip and country) but I would also like to add the latitude and longitude for each affiliate. Am I able to scrape this information from Mapbox? It is displayed on a map so it must have the information somewhere. Otherwise I will look at obtaining the latitude and longitude from the affiliate address (using python).
answer count: 1

http://stackoverflow.com/q/49226840
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: setup.py
upvote count: 1
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49237518
accepted answer: http://stackoverflow.com/a/49237518
favorite count: 0
type: Question
has title: Questions regarding python setup script
has body: I have a few questions regarding python setup scripts or rather how to properly setup a module (as I am doing this for the first time and kind of struggling). For simplicity I just post a link to the corresponding github repository rather than explaining the project in detail. I am fully aware that the project as it is will not work (e.g. the file constants.py is missing) but for starters I would like the "structure" to work. There are two main components in this project, i.e. pymap and agb - both dependent on each other (which should not be a problem I guess). I also would like to use scripts located in the bin/ directory which of course use the modules pymap and agb. For installation I use sudo ./setup.py develop which installs the modules as I can now use them in a python3 shell. The line import pymap.pymap_gui will throw an error (since constants.py is not yet in the project) however the import can be resolved. When - on the other hand - calling the scripts with pymap.py the same import can not even be resolved: ModuleNotFoundError: No module named 'pymap.pymap_gui'; 'pymap' is not a package How can this be even though from a python3 shell the import works perfectly fine? Furthermore - where to improve my project structure? Is my setup the way to go (not minding the messy code and not yet working project itself - I am viewing this from kinda structure-ish perspective).

http://stackoverflow.com/comment/85441303
comment on: http://stackoverflow.com/a/49212360
has text: I'm casting the returned type to pointer. Also, how does it have memory leak? I mean it would if i wouldn't free the memory which I do in another method (that's a different subject)
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85409342
score: 3
has text: Yes, the [Gaussian integers](https://en.wikipedia.org/wiki/Gaussian_integer) ("integer complex type") are closed under addition and multiplication, but certainly not when square roots are involved. There's no reason to expect the complex modulus (absolute value) of a Gaussian integer to be an integer in general.
type: Comment
comment on: http://stackoverflow.com/a/49201115
type: AnswerComment

http://stackoverflow.com/a/49287278
type: Answer
type: AcceptedAnswer
has body: I found the solution browsing the fastavro official github https://github.com/tebeka/fastavro/issues/12 "Currently fastavro supports only "one shot" writes. However records can be any iterable, including a generator the creates records one by one. I'll look into appending." Buffering the values and write only at the end of the loop did it insert_regex = re.compile('''INSERT INTO `pagelinks` VALUES (.*)\;''') row_regex = re.compile("""(.*),(.*),'(.*)',(.*)""") avro_content = [] for line in sys.stdin: avro_file = open("pagelinks.avro", 'wb') match = insert_regex.match(line.strip()) if match is not None: data = match.groups(0)[0] rows = data[1:-1].split("),(") for row in rows: row_match = row_regex.match(row) if row_match is not None: # &gt;&gt;&gt; row_match.groups() # (12,0,'Anti-statism',0) # # page_id, pl_namespace, pl_title, pl_from_namespace if row_match.groups()[1] == '0': page_id, pl_title = row_match.groups()[0], row_match.groups()[2] avro_content.append({"page_id":int(page_id), "page_title":pl_title}) writer(avro_file, schema, avro_content)
accepted answer of: http://stackoverflow.com/q/49278649
score: 0
answers question: http://stackoverflow.com/q/49278649

http://stackoverflow.com/comment/85303914
type: Comment
score: 0
type: AnswerComment
has text: @PaulPanzer not as smart as I'd hoped. There's no valid `identity` for `maximum` and `minimum`. Had to fudge a bit
comment on: http://stackoverflow.com/a/49146228

http://stackoverflow.com/a/49224874
has comment: http://stackoverflow.com/comment/85482232
has comment: http://stackoverflow.com/comment/85453582
has body: Are you sure about the content of tags_data variable? Could you put there traceback and debug it (see: using (i)pdb for debugging)? I think wrong is these line: post.tags.add(tags_data) lets try: post.tags.add(*tags_data) The star unpack list. See these answer for reference: https://stackoverflow.com/a/4959580/953553 In my project I ma handling tags which are in model M2M and in serializer I decided to use this approach: tags = serializers.SlugRelatedField( many=True, queryset=Tag.objects.all(), slug_field='text' ) my models: class Spot(models.Model): tags = models.ManyToManyField(Tag, related_name='spot_facilities', null=True, blank=True) class Tag(models.Model): text = models.CharField(max_length=100, unique=True)
has comment: http://stackoverflow.com/comment/85455966
has comment: http://stackoverflow.com/comment/85482584
answers question: http://stackoverflow.com/q/49224385
has comment: http://stackoverflow.com/comment/85479474
type: Answer
has comment: http://stackoverflow.com/comment/85453765
score: 0
has comment: http://stackoverflow.com/comment/85480077
has comment: http://stackoverflow.com/comment/85455746

http://stackoverflow.com/q/49203300
answer count: 6
has comment: http://stackoverflow.com/comment/85412002
has title: Is there a way to convert this json file?
has comment: http://stackoverflow.com/comment/85412085
downvote count: 13
has answer: http://stackoverflow.com/a/49203602
has answer: http://stackoverflow.com/a/49203382
has answer: http://stackoverflow.com/a/49203409
has body: I have this json file: { "spain" : "spanish.", "usa" : "english", "france" : "french", "italy" : "italian", ... } Is there a fast way to convert that json file in this below? [ { "country": "spain", "language": "spanish." } { "country": "usa", "language": "english." } { "country": "france", "language": "french." } { "country": "italy", "language": "italian." } ... }
has answer: http://stackoverflow.com/a/49203384
has comment: http://stackoverflow.com/comment/85412081
upvote count: 0
has comment: http://stackoverflow.com/comment/85412007
tagged with: http://stackoverflow.com/tag/json
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49203419
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49203458
has comment: http://stackoverflow.com/comment/85412041
score: -13
has comment: http://stackoverflow.com/comment/85411990
tagged with: javascript
tagged with: python

http://stackoverflow.com/a/49250134
downvote count: 0
score: 4
has body: Now Get request is working , by setting the proxies with port number. Added proxy setting in above code: proxies = { 'http': 'web-proxy.xxxxxx.xx.com:8080','https': 'web-proxy.xxxxxx.xx.com:8080'} Output : 200 { "version" : "1.0", "email_address" : "xxxx@emailin.com" }
type: Answer
answers question: http://stackoverflow.com/q/49234416
upvote count: 4

http://stackoverflow.com/a/49206664
score: 1
has body: Use extend instead of append to add more entries to mylist in __init__ and call instance_name.mylist in main to print list. Something like this: class Class_Name: def __init__(self, input1, input2): self.mylist = [] self.mylist.extend([input1, input2]) if __name__ == "__main__": val1 = Class_Name("Value_1", "Value_2") print(val1.mylist) # ['Value_1', 'Value_2']
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49206561
type: Answer

http://stackoverflow.com/a/49199132
score: 22
has body: load_model first builds the saved model architecture with its saved weights and then tries to build the saved optimizer with its saved weights. However, you get an error message because there is a mismatch between the shape of the saved optimizer weights and the shape of the weights that the optimizer is expecting based on the architecture of the loaded model. I ran into this issue using Keras 2.1.4 when I tried to save and re-load a model that had inner submodels that were set to trainable=False. This information seems not to be preserved when you save the model, so after re-instatiating the inner submodel is set to trainable=True and the optimizer would expect more saved weights than were actually saved. If this might be the problem in your case, I described a workaround in this bug-report: Set the trainability of all the inner model layers explicitly Right before saving, the trainability flags of all the layers have to be set to the state that they had at model compile time If you want to get rid of the warning and you do not need the optimizer after saving anyway, you can also save your model without the optimizer: use model.save(filename, include_optimizer=False)
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/129027545
answers question: http://stackoverflow.com/q/49195189
accepted answer of: http://stackoverflow.com/q/49195189
type: Answer
upvote count: 22

http://stackoverflow.com/comment/85308602
score: 0
has text: It needs to happen continuously and in real time. Basically, I'm trying to stream audio recording to Speech-To-Text API
comment on: http://stackoverflow.com/q/49151497
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49256299
possible better answer: http://stackoverflow.com/a/49257134
tagged with: python
has answer: http://stackoverflow.com/a/49257134
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49258002
linked to: http://stackoverflow.com/q/19859282
has body: Example: pw = input("enter your password:") Input: "bikash413SSS" How can I know when there is integer, capital letter, etc?
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85519674
accepted answer: http://stackoverflow.com/a/49258002
answer count: 2
downvote count: 5
has comment: http://stackoverflow.com/comment/85515607
has title: How to identify the integers in a string in Python?
score: -3

http://stackoverflow.com/comment/85432678
type: AnswerComment
score: 2
has text: So, if webserver start ("open") only **one** Django app ("program"), then until current request wouldn't be served another one request will be suspend?
comment on: http://stackoverflow.com/a/49214051
type: Comment

http://stackoverflow.com/q/49213699
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49213840
tagged with: pandas
has answer: http://stackoverflow.com/a/49213840
tagged with: python
accepted answer: http://stackoverflow.com/a/49213718
tagged with: numpy
score: 2
answer count: 2
has answer: http://stackoverflow.com/a/49213718
upvote count: 2
has body: I have a pandas dataframe of correlations. I'm searching through the dataframe to find correlations greater than the threshold 0.5 then return the column name and row name (both are strings) for those elements that match the condition. Currently, I can transform the correlation matrix to values greater than the threshold, then all other values are NaN using this: correlations[np.abs(correlations) &gt; 0.5] Now that I have this matrix of numbers that match my query and NaNs, how do I get the row+col names of each element whose value is not NaN?
downvote count: 0
favorite count: 0
type: Question
has title: pandas find row+col names for elements with condition

http://stackoverflow.com/a/49254286
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49225393
has body: import random #create an empty list y = list() # continue picking cards until you have 7 cards -&gt; avoid duplicates while len(y) &lt; 7: rank = random.choice(('A','2','3','4','5','6','7','8','9','T','J','Q','K')) suit = random.choice( ('c','d','h','s') ) card = rank + suit #if the card is not present in the list, add it if not card in y: y.append(card) #sort your list (by 1st letter -&gt; no sort criteria were given) y = sorted(y) print(y)
score: 1
type: Answer

http://stackoverflow.com/comment/85535645
has text: Oh well... whoever made that decision may want to reconsider. Pandas is an extremely helpful too for exactly what you're trying to do.
type: Comment
comment on: http://stackoverflow.com/a/49265721
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85417306
type: AnswerComment
has text: Iam sry but its loading the first part of comment section as u said.How to get the all comments on that page
comment on: http://stackoverflow.com/a/49205538
score: 0
type: Comment

http://stackoverflow.com/comment/85358532
type: Comment
has text: sorry, cant get it right! def f("attmlk1" = "CWT" , "attctl1" ="RJ"):
type: AnswerComment
comment on: http://stackoverflow.com/a/49155147
score: 0

http://stackoverflow.com/comment/85460573
comment on: http://stackoverflow.com/a/49227897
score: 0
type: Comment
has text: @BennettBrown If you want more detail, this could make for a good question, where an answer could go into the reasons why it isn't trivial, the history, the design reasoning involved, the idiomatic way to simulate `or` in the C API, etc. By the way, you may have guessed this, but if you need a function that does `or`, you can't use `operator.or_`, because that's `|` again, so you need something like `lambda x, y: x or y`.
type: AnswerComment

http://stackoverflow.com/comment/85367527
has text: Yes, possibly. See [mcve] and update your question with one if you want help here.
comment on: http://stackoverflow.com/q/49180822
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49157542
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49156908
type: Answer
has body: scipy.optimize.fsolve finds the root of functions from Rn ↦ R. Your function func seems to be Cn ↦ R, in particular the starting point u1 has explicit complex type (though it's value is real), and that's exactly what the error is talking about. If your input is always real, simply set dtype='float' in u1. Otherwise you'd have to use a different function for optimization, e.g. mpmath.findroot from sympy.

http://stackoverflow.com/q/49235545
has answer: http://stackoverflow.com/a/49235883
tagged with: python
score: 2
has body: When trying to groupby a dataframe by month and country I am getting the following error: 'tuple' object has no attribute 'lower' here is the code I am using: df = df.groupby( [pd.to_datetime(df.time).dt.strftime('%b %Y'), 'Country'])['% Return'].mean().reset_index() example dateframe time Country % Return 2017-07-30 br 3 2017-07-31 br 4 2017-08-01 br 5 2017-08-02 br 6 2017-08-03 br 7 2017-07-30 es 2 2017-07-31 es 3 2017-08-01 es 4 2017-08-02 es 5 2017-08-03 es 6 desired output: time Country % Return 2017-07-01 br 3.5 2017-08-01 br 6 2017-07-01 es 2.5 2017-08-01 es 5 I have used this same code for simialr DFs. Not sure why its not working this time Thanks in advance edit: python version: Python 2.6.6 pandas version: 0.22.0 full error AttributeError Traceback (most recent call last) &lt;ipython-input-29-db720e55a304&gt; in &lt;module&gt;() 1 new_return_poster_df_g = new_return_poster_df_g.groupby( ----&gt; 2 [pd.to_datetime(new_return_poster_df_g.time).dt.strftime('%b %Y'), 'Country'] 3 )['% Return Poster'].mean().reset_index(name='% Return Poster') /var/local/ishbook.executor.daemon/lib/python-venvs/libraries/pandas==0.22.0/lib/python2.7/site-packages/pandas/core/tools/datetimes.pyc in to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact, unit, infer_datetime_format, origin) 374 result = Series(values, index=arg.index, name=arg.name) 375 elif isinstance(arg, (ABCDataFrame, MutableMapping)): --&gt; 376 result = _assemble_from_unit_mappings(arg, errors=errors) 377 elif isinstance(arg, ABCIndexClass): 378 result = _convert_listlike(arg, box, format, name=arg.name) /var/local/ishbook.executor.daemon/lib/python-venvs/libraries/pandas==0.22.0/lib/python2.7/site-packages/pandas/core/tools/datetimes.pyc in _assemble_from_unit_mappings(arg, errors) 444 return value 445 --&gt; 446 unit = {k: f(k) for k in arg.keys()} 447 unit_rev = {v: k for k, v in unit.items()} 448 /var/local/ishbook.executor.daemon/lib/python-venvs/libraries/pandas==0.22.0/lib/python2.7/si…
has comment: http://stackoverflow.com/comment/85474886
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85474270
has title: Pandas Groupby error
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85474486
tagged with: pandas-groupby
tagged with: pandas

http://stackoverflow.com/a/49226671
has comment: http://stackoverflow.com/comment/85457242
score: 2
has comment: http://stackoverflow.com/comment/85457262
answers question: http://stackoverflow.com/q/49226574
has comment: http://stackoverflow.com/comment/85457209
upvote count: 2
downvote count: 0
type: Answer
has body: The first problem i that n.update(…) tries to update the dictionary, not the current value in the dictionary. It expects to be given a sequence of key-value pairs, and you're not giving it that, you're giving it a single value. Hence the exception. But anyway, you want to modify n[i], not n. Since each n[i] is a list, and what you want to do is append a new value to that list, just call n[i].append(…) instead of n.update(…). Put into context: for i in n: length = len(n[i]) for length in range(0, 2): b = ["1", "0", "1"] n[i].append(random.choice(b)) print(n) If you run this, you will see that each key ends up with a list of exactly two values; about two thirds of those values are the string '1' and the rest are the string '0'. It also prints out a whole bunch of stuff. So I'm guessing this still isn't exactly what you want, but it does solve the problem you were asking about, and should be enough to get you to the next step.

http://stackoverflow.com/q/49196720
has body: I have a long running function which I want to run on heroku as a background function. I'm using redis and rq to manage this. My dashboard view function which loads the data into the session object starts with: @login_required @main.route('/dash', methods=['GET', 'POST']) def dash(): if request.method =='POST': print(request.form.get('posting')) session['posting']=request.form.get('posting') session['folder']=request.form.get('folder') Then after selection the info gets passed to: @login_required @main.route('/confirm', methods=['GET', 'POST']) def confirm(): print(session['posting']) return foreground_vs_background(confirm_function,[session]) Then: def foreground_vs_background(func, args): j= get_queue().enqueue(func,args = args,result_ttl=5000) return (j.get_id()) finally my function that I pass in starts with: def confirm_function(): p = session['posting'] folder = session['folder'] The heroku logs show: 2018-03-09T14:43:14.357633+00:00 app[worker.1]: return self.run(*args, **kwargs) 2018-03-09T14:43:14.357642+00:00 app[worker.1]: File "manage.py", line 111, in run_worker 2018-03-09T14:43:14.357861+00:00 app[worker.1]: worker.work() 2018-03-09T14:43:14.357870+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/worker.py", line 460, in work 2018-03-09T14:43:14.360547+00:00 app[worker.1]: self.execute_job(job, queue) 2018-03-09T14:43:14.360590+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/worker.py", line 575, in execute_job 2018-03-09T14:43:14.360593+00:00 app[worker.1]: self.fork_work_horse(job, queue) 2018-03-09T14:43:14.360594+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/worker.py", line 521, in fork_work_horse 2018-03-09T14:43:14.360596+00:00 app[worker.1]: self.main_work_horse(job, queue) 2018-03-09T14:43:14.360598+00:00 app[worker.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rq/worker.py", line 590, in main_work_horse 2018-03-09T14:43:14.360599+00:00 app[w…
tagged with: flask
has answer: http://stackoverflow.com/a/49220343
tagged with: python-rq
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/12162021
type: Question
tagged with: heroku
tagged with: redis
has title: Flask Session UnpickleError
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/59854437
has comment: http://stackoverflow.com/comment/130135126
upvote count: 0
downvote count: 1
type: Answer
score: -1
has body: Concise Python Solution def arrayChange(inputArray): a = 0 for i in range(1, len(inputArray)): if inputArray[i] &lt;= inputArray[i - 1]: f = (inputArray[i - 1] - inputArray[i]) + 1 inputArray[i] = inputArray[i - 1] + 1 a += f return a
answers question: http://stackoverflow.com/q/49216987

http://stackoverflow.com/comment/85497560
comment on: http://stackoverflow.com/a/49229970
type: Comment
type: AnswerComment
has text: Yeah they definitely take a moment to get used to. This goes through each row. Then the list comprehension, creates a new list which includes all the values except those that are ''.
score: 0

http://stackoverflow.com/q/49163592
has body: I am trying to train a CNN model using Keras using Tensorflow backend. The problem is, it won't run using my GPU (i.e. there is no speed up than when previously using tensorflow on CPU), despite the fact that I installed tensorflow-gpu and not the normal tensorflow as the solution described in this link. I have installed CUDA version 9.0 and cuDNN version 7.1, received no issues as this link described. I have also made sure that tensorflow is able to detect my GPU [name: "/device:CPU:0" device_type: "CPU" memory_limit: 268435456 locality { } incarnation: 18032619952595111467 , name: "/device:GPU:0" device_type: "GPU" memory_limit: 3187841433 locality { bus_id: 1 } incarnation: 7706357628903921514 physical_device_desc: "device: 0, name: GeForce GTX 1050, pci bus id: 0000:01:00.0, compute capability: 6.1" ] After some further researching, I have found this link. And my script didn't load the local cuDNN libraries. EDIT Below is a screenshot of the nvidia-smi.exe, this is before and after I started the CNN training (i.e. no changes). EDIT v2 Ok, I have made some little progress, turns out there is something weird with running the script in Spyder, so I ran it using python my_python_script.py in Command Prompt. I can say for sure that the GPU is recognized by tensorflow, as Keras has given jobs to the GPU. But, I still get 0% utilization I don't know what else could be wrong. Please help. Thanks in advance!
type: Question
has answer: http://stackoverflow.com/a/49313044
has comment: http://stackoverflow.com/comment/85336391
has comment: http://stackoverflow.com/comment/85340654
has comment: http://stackoverflow.com/comment/85336464
has comment: http://stackoverflow.com/comment/85336414
has comment: http://stackoverflow.com/comment/85345808
has comment: http://stackoverflow.com/comment/85340210
tagged with: python
has title: Keras is not Using Tensorflow GPU
has comment: http://stackoverflow.com/comment/85336131
has comment: http://stackoverflow.com/comment/85336356
has comment: http://stackoverflow.com/comment/85335633
has comment: http://stackoverflow.com/comment/85336272
score: 2
type: AnsweredQuestion
upvote count: 2
has comment: http://stackoverflow.com/comment/85344478
linked to: http://stackoverflow.com/q/39859260
linked to: http://stackoverflow.com/q/46080634
has comment: http://stackoverflow.com/comment/85336461
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49313044
tagged with: keras
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/101906989
score: 9
type: AnswerComment
has text: my prospector linter requires a certain length
type: Comment
comment on: http://stackoverflow.com/a/49220098

http://stackoverflow.com/q/49167024
favorite count: 0
tagged with: oop
type: Question
score: 3
has comment: http://stackoverflow.com/comment/85339367
tagged with: python
has answer: http://stackoverflow.com/a/49167188
has answer: http://stackoverflow.com/a/49167148
accepted answer: http://stackoverflow.com/a/49167188
has body: I wrote a simple program. class Sample: num =45 def __init__(self): print('Inside constructor') @classmethod def modifyUsingClassMethod(cls): cls.num = cls.num + 45 @staticmethod def modifyUsingStaticMethod(): Sample.num = Sample.num+5 s1 = Sample() s2 = Sample() s1.modifyUsingClassMethod() print(s1.num, s2.num) s1.num = s1.num + 5 print(s1.num) s1.modifyUsingClassMethod() print(s1.num, s2.num) s1.modifyUsingStaticMethod() print(s1.num, s2.num) Output: Inside constructor Inside constructor 90 90 95 95 135 95 140 Can anyone explain how and why the @staticmethod and @classmethod are acting on the variable 'num'?. Why does the output shows 95,135 even after I changed the value of num using s1 instance using modifyUsingClassMethod() and why not it is updating in both cases using @staticmethod and @classmethod? I guess when I am referring to the variable num using class object then python is treating the variable num as an instance variable but when I change the variable num using Class name then the value is not updating in the s1 but in s2. I am highly confused how @classmethod and @staticmethod works.
tagged with: static-methods
has title: How does @staticmethod and @classmethod act on the variable in python?
type: AnsweredQuestion
tagged with: class-method
upvote count: 3
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/49167148

http://stackoverflow.com/comment/85342386
type: AnswerComment
has text: Thank you, your edit worked! I have to be more careful, when implementing my __init__ in the future.
comment on: http://stackoverflow.com/a/49155416
score: 0
type: Comment

http://stackoverflow.com/q/49236619
type: Question
has title: Search for dynamic number of words in Pandas Dataframe
has answer: http://stackoverflow.com/a/49236725
downvote count: 0
answer count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49236725
tagged with: pandas
upvote count: 1
score: 1
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85476392
has body: I have a .csv file with 1 column and 9999 rows, I have to write an algorithm to search for strings with specific words in it. So far I have code for fixed number of words (3 words in that case): import pandas as pd df = pd.read_csv('example.csv', encoding='cp1251',header=None) search = input("searching for: " ) search = search.lower().split() df[0] = df[0].str.lower() print (df[df[0].str.contains(search[0]) &amp; df[0].str.contains(search[1]) &amp; df[0].str.contains(search[2])]) Please advise, how can I make similar algorythm for dynamic number of words to search. Thanks for your time!
favorite count: 0

http://stackoverflow.com/comment/85270586
comment on: http://stackoverflow.com/a/49132869
has text: @dennis-ec Using `agg` + `list`? Unfortunately, no, because lists are special-cased by pandas, and the result is almost certainly coerced into a dataframe. Perhaps consider `agg` + `tuple` as an alternative, the same would then work.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/95707248
type: QuestionComment
type: Comment
has text: In case you haven't found a solution yet, I found one that helped me out a ton! Good Luck! http://page.sourceforge.net/html/themes.html
score: 1
comment on: http://stackoverflow.com/q/49217783

http://stackoverflow.com/q/49125081
answer count: 1
downvote count: 0
has body: I have a python program that runs another program using popen. Is it possible to read from the programme's output for a while, and the connect the subprogram's output to sys.stdout, and allow it to run in parallel as if I had started it without the stdout=subprocess.PIPE option? wrapper: #! /usr/bin/env python3 import subprocess from time import sleep import sys p = subprocess.Popen( ["./count.py"], stdout=subprocess.PIPE, ) for line in iter(p.stdout.readline,''): l = line.decode('utf-8') sys.stdout.write("&gt;&gt;" + l) if "8" in l: # somehow reconnect p.stdout to sys.stdout break sleep(1) print("now do some stuff in parallel") sleep(1) p.terminate() test program: #! /usr/bin/env python from time import sleep import sys for x in range(1,100): sleep(.1) print x sys.stdout.flush() output: $ ./wrapper.py &gt;&gt;1 &gt;&gt;2 &gt;&gt;3 &gt;&gt;4 &gt;&gt;5 &gt;&gt;6 &gt;&gt;7 &gt;&gt;8 now do some stuff in parallel is it possible to do this? $ ./wrapper.py &gt;&gt;1 &gt;&gt;2 ... &gt;&gt;7 &gt;&gt;8 9 10 ... 18 19 now do some stuff in parallel 20 21 ... 28 29
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
has title: is it possible to reconnect subprocess.Popen's stdout to sys.stdout? (python3)
tagged with: python
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49127954
tagged with: subprocess
has answer: http://stackoverflow.com/a/49127954

http://stackoverflow.com/a/49225859
has body: You can simply do: data={'foo': [{1: 55}, {'c': 43}], 'bar': [{1: 43}, {'c': 40}]} print({i:sorted(j,key=lambda x:list(x.values())) for i,j in data.items()}) output: {'foo': [{'c': 43}, {1: 55}], 'bar': [{'c': 40}, {1: 43}]}
type: Answer
answers question: http://stackoverflow.com/q/49220428
score: 0

http://stackoverflow.com/comment/125775196
comment on: http://stackoverflow.com/a/49271087
has text: @Z41N It's pretty easy visually if you split the figure into quadrants, centred next to the central square: you end up with four differently sized "triangles", where the biggest two can be joined to form n² and the smallest two can be joined to form (n-1)².
type: Comment
score: 5
type: AnswerComment

http://stackoverflow.com/comment/85250878
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49122407
score: 0
has text: Hmm yeah, not sure where I read that list slices don't create copies, but I seem to be wrong. Sorry.

http://stackoverflow.com/a/49176979
has body: Not really. Closest two options I have in mind: a = a if a else b a = a or b Unless I am misunderstanding and you mean bitwise: a=5 #101 a|=3 #010 result is a==7 (111). Of course |= will work with True and False, but I'm not sure it's considered proper in the language: a=True a|=False works, a will be True. The only concern here is semantic. If the usage is buried in deep code, someone skimming will assume you're using binary operations here - the above methods are more readable when considering logic. An even bigger caveat, mentioned by @Moberg, is that Boolean operators aren't lazy. Define def b(): print("Don't print this!") return False Then a|=b() will print the string even though a is True and it doesn't matter what b is. This is because as far as the Boolean operation is concerned, True is just 1, and b can be any number, so it must be evaluated. Using a or b() or a if a else b() will work as expected.
type: Answer
answers question: http://stackoverflow.com/q/49176905
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/85391409
has comment: http://stackoverflow.com/comment/116680910
score: 4
has comment: http://stackoverflow.com/comment/85359515

http://stackoverflow.com/q/49266385
has comment: http://stackoverflow.com/comment/85541782
tagged with: python
has answer: http://stackoverflow.com/a/49284728
has body: I call a NASM dll from ctypes. In my NASM dll code, I create three arrays using malloc. Their pointers are assigned to final1_ptr, final2_ptr and final3_ptr. If I return any of the pointers individually, I get the correct results. But I want to return an array of all three pointers. For that, I also have an array initialized in the .data section: Return_Pointer_Array: dq 0, 0, 0. At the end I assign the pointers this way: mov rdi,Return_Pointer_Array mov rax,qword[final1_ptr] mov qword [rdi],rax mov rax,qword[final2_ptr] mov qword [rdi+8],rax mov rax,qword[final3_ptr] mov qword [rdi+16],rax mov rax,rdi ret However, what ctypes gets is an array of three extremely small decimals, not valid pointer addresses. The actual program listing is very long, so I hope the code above will be enough to understand the problem. Thanks very much for any help. EDIT: if I return the Return_Pointer_Array without assigning any values, it returns double (floating point) values. The array is initialized as integer, so I don't understand why it defaults to floating point when it's initialized as dq 0, 0, 0. EDIT #2: Per request, here is the Python code: def Test_Data_Read(): #Note: in production, X is a list of 50,000 random floats read from file; #For simplicity, I have reduced it to a short simple list: X = [11.0,1.0,2.0,7.0,4.0,4.0,4.0,6.0,7.0,6.0,11.0,4.0,10.0,7.0,8.0,4.0,9.0,4.0,5.0,3.0,4.0,1.0,2.0,5.0,3.0,5.0,11.0,10.0,11.0,9.0,3.0,12.0] PyGram_Test_01_asm(X) #__________ def PyGram_Test_01_asm(X): Input_Length_Array = [] Input_Length_Array.append(len(X)*8) CA_X = (ctypes.c_double * len(X))(*X) length_array_out = (ctypes.c_double * len(Input_Length_Array))(*Input_Length_Array) hDLL = ctypes.WinDLL("C:/NASM_Test_Projects/Nested_For_Loops/Nested_For_Loops.dll") CallName = hDLL.Main_Entry_fn CallName.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double)] CallName.restype = ctypes.POINTER(ctypes.c_double) start_time = timeit.default_timer() ret_ptr = CallName(CA_X,l…
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85565110
tagged with: x86-64
has comment: http://stackoverflow.com/comment/85565723
type: Question
linked to: http://stackoverflow.com/q/3323445
has comment: http://stackoverflow.com/comment/85537851
has comment: http://stackoverflow.com/comment/85565338
tagged with: ctypes
tagged with: nasm
type: UnansweredQuestion
has title: NASM how to return an array of pointers?
has comment: http://stackoverflow.com/comment/85559665
tagged with: arrays
has comment: http://stackoverflow.com/comment/85539173
has comment: http://stackoverflow.com/comment/85564694

http://stackoverflow.com/q/49239961
has body: I am getting random failures to create the callback model weights file when running Keras (with tensorflow) models in a loop with changing model parameters and input data. I am thinking that it might be something to do with the length of my directory name but if so, it seems like a bug as it only happens sometimes. Prior to the following error it wrote multiple files with same length directories. I am using long names for directories to make it easier to distinguish runs in tensorboard. I will show my basic code setup as pseudo code and then the random error that I am getting. I have a nested for loop that is changing model parameters as well as input data. The basic loop will work fine for hours and then randomly fail for the same error at some point in the loop. I would like to know if I am doing something wrong in my file name that is causing this. I would also like a work around so that when it fails, I can keep running and move on to the next file and skip the one that is failing. Some type of try/except but I don't know enough about h5py to know how to code that. I am running on Windows 10 (conda env), tensorflow-gpu 1.6.0, Keras 2.1.5, h5py 2.7.1, tensorboard 1.6.0. I also set up Windows 10 to handle long file names. This error seems to be coming directly from h5py (h5py\h5f.pyx). Also, the file actually gets created and written. I can load the file using h5py.File() and it is the correct size and has same groups and objects. Update: I included the os.makedirs() line in my code that I did not show before. I also added a check on the directory creation and ran the code again. It still failed in same way and it never triggered the isdir() check. Update 2: Wanted to point out that I am using multiprocessing because of memory leaks when using Keras with Tensorflow. This happens regardless of having K.clear_session() and tf.reset_default_graph(). I now believe this random error is related to multiprocessing as I have not observed this error yet when I eliminate th…
favorite count: 0
type: Question
score: 2
has comment: http://stackoverflow.com/comment/85488081
has comment: http://stackoverflow.com/comment/85487818
upvote count: 2
has comment: http://stackoverflow.com/comment/85487233
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85500327
answer count: 1
downvote count: 0
tagged with: keras
has comment: http://stackoverflow.com/comment/85487276
tagged with: tensorflow
has title: Why is h5py.h5f.create failing with OSError: unable to open file: name ="name",
has answer: http://stackoverflow.com/a/73402610
tagged with: h5py
has comment: http://stackoverflow.com/comment/85487399
tagged with: python

http://stackoverflow.com/a/49243745
has body: So, you're trying to check that each of the 5 strings have the same characters in the column? If the characters in the column all match, you increment i, else you increment n. Your interpretation of the code is correct. Based on the above, I'd hazard to suggest the following code as a faster alternative. I suppose that align is a structure like this: align = [ 'AGCTCGCGGAGGCGCTGCT....', 'ACCTCGGAGGGCTGCTGTAC...', 'AGCTCGGAGGGCTGCTGTAC...', # possibly more ... ] We try to detect the columns of same characters in it. Above, the first column is AAA (a match), the next is GCG (a mismatch). def all_equal(items): """Returns True iff all items are equal.""" first = items[0] return all(x == first for x in items) def compute_match(aligned_sequences): """Returns the ratio of same-character columns in ``aligned_sequences``. :param aligned_sequences: a list of strings or equal length. """ match_count = 0 mismatch_count = 0 for chars in zip(*aligned_sequences): # Here chars is a column of chars, # one taken from each element of aligned_sequences. if all_equal(chars): match_count += 1 else: mismatch_count += 1 return float(match_count) / float(mismatch_count) # What would make more sense: # return float(matches) / len(aligned_sequences[0]) An even shorter version: def compute_match(aligned_sequences): match_count = sum(1 for chars in zip(*aligned_sequences) if all_equal(chars)) total = len(aligned_sequences[0]) mismatch_count = total - match_count # Obviously. return ...
has comment: http://stackoverflow.com/comment/85492576
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/85493199
accepted answer of: http://stackoverflow.com/q/49241130
has comment: http://stackoverflow.com/comment/85492931
score: 5
answers question: http://stackoverflow.com/q/49241130
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85493090

http://stackoverflow.com/comment/85725474
score: 0
comment on: http://stackoverflow.com/q/49255545
type: QuestionComment
has text: If it is "myproject.py" then make it "wsgi.py" because in "myproject.ini" you have mentioned the module as wsgi : app. Hope it works for you
type: Comment

http://stackoverflow.com/a/49164081
answers question: http://stackoverflow.com/q/49163978
upvote count: 1
downvote count: 0
score: 1
has body: I would recommend not using or in this case and rather breaking this up into if and elif statements to preserve what keyword was found. Store that in a variable (in this case value) and use that in the print statement. if line.find("def") != -1: value = "def" elif line.find("if") != -1: value = "if" elif line.find("elif") != -1: value = "elif" print("&lt;span style=\"color: orange;\"&gt;", value,"&lt;/span&gt;","&lt;br&gt;", end="")
type: Answer

http://stackoverflow.com/q/49124037
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: beautifulsoup
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49124392
tagged with: http://stackoverflow.com/tag/html
has body: I'm using the following code to retrieve all the image links on a webpage from bs4 import BeautifulSoup import requests def get_txt(soup, key): key_tag = soup.find('span', text=re.compile(key)).parent return key_tag.find_all('span')[1].text urldes = "https://www.johnpyeauctions.co.uk/lot_list.asp?saleid=4709&amp;siteid=1" headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'} r = requests.get(urldes, headers=headers) soup = BeautifulSoup(r.content, "lxml") image_links = [x['data-img'] for x in soup.find_all('a', rel='popover')] for link in image_links: print(link) I would like to apply the same principle in order to retrieve the text description that goes with each image: soup.find_all(width='41%') for text in soup.find_all('h5'): print(text) This code retrieves all the &lt;h5&gt; tags BUT not the specific tag with the parent (width='41%'). I have tried to apply the same loop as above for the image links: image_text = [x['h5'] for x in soup.find_all(width='41%')] for text in image_text: print(text) But I get the following error: `Traceback (most recent call last): File "C:\Users\alexa\Desktop\jpye_v2.py", line 41, in &lt;module&gt; image_text = [x['h5'] for x in soup.find_all(width='41%')] File "C:\Users\alexa\Desktop\jpye_v2.py", line 41, in &lt;listcomp&gt; image_text = [x['h5'] for x in soup.find_all(width='41%')] File "C:\Python36\lib\site-packages\beautifulsoup4-4.6.0-py3.6.egg\bs4\element.py", line 1011, in __getitem__ return self.attrs[key] KeyError: 'h5'` What I don't understand is why the tag h5 gives an error where the tag a does not or can I not use the same loop to index the text iterations in the same way as the image links?
tagged with: python
has answer: http://stackoverflow.com/a/49124306
possible better answer: http://stackoverflow.com/a/49124306
type: AnsweredQuestion
score: 0
answer count: 2
has title: Retrieve text iteration using loops in BeautifulSoup
has answer: http://stackoverflow.com/a/49124392

http://stackoverflow.com/comment/85321303
type: QuestionComment
has text: `123` can be either a string or int though. What if it's `a1`? Is it still a valid string? If you want only alpha characters you might want to manually handle with `str.isalpha()`.
score: 1
comment on: http://stackoverflow.com/q/49158132
type: Comment

bulkinsert
type: Tag
tag name: bulkinsert
tags question: http://stackoverflow.com/q/49154208

http://stackoverflow.com/q/49166617
tagged with: python
has comment: http://stackoverflow.com/comment/85338645
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85338701
has answer: http://stackoverflow.com/a/49166828
score: 0
answer count: 1
has title: Pandas KeyError('%s not in index' % objarr[mask]) for me but not others with same code
has body: I get this error that my professor does not get, running the identical, sample code he provided for our class. I have not found a solution here or in the Anaconda or Python Tutor lists. We're learning basic python, looking at the simplest Pandas DataFrames and learning to select columns. We built a dataframe df (5 rows, 5 columns) and all but one line of the code works fine. The line that doesn't work is: df[ [0,1] ] It continually, on my system, throws this KeyError on the df[ [0,1] ] command. I get the analogous error for df[ [0] ] or df[ [1] ]. Traceback (most recent call last): File "&lt;ipython-input-7-c392a914e584&gt;", line 1, in &lt;module&gt; df[ [0,1] ] File "C:\Users\xxxx\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py", line 1958, in __getitem__ return self._getitem_array(key) File "C:\Users\xxxx\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py", line 2002, in _getitem_array indexer = self.loc._convert_to_indexer(key, axis=1) File "C:\Users\xxxx\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\indexing.py", line 1231, in _convert_to_indexer raise KeyError('%s not in index' % objarr[mask]) KeyError: '[0 1] not in index' It feels to me like something about how Python is installed on my computer. I have Anaconda Navigator 1.7.0 installed under 64-bit Win 7 Pro. I have restarted both Anaconda and Sypder directly many times and rebooted many times over many days. Same error. I updated Anaconda today. Same error. I'm running spyder, either through anaconda navigator or directly from the start menu - same error. As I mentioned before, my professor has no problem running this same code. Does anyone have any suggestions about what could be wrong that this one thing doesn't work on my computer? My code example below includes a couple other column selections I AM able to do on my machine, so I think the DataFrame is working in general. One thing I notice is that my path is quite long, because of the wa…
tagged with: anaconda
type: Question
tagged with: pandas
tagged with: spyder

http://stackoverflow.com/comment/85471578
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49230989
type: Comment
has text: It's not supported (and the question is too broad to recommend alternatives).

http://stackoverflow.com/comment/85523981
has text: `"%H"` also must be combined: `"--pretty-format:%H"`.
comment on: http://stackoverflow.com/a/49259991
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85480158
has text: Thanks for your comment. Could I ask what is the usage of FLANN? and what exactly `flann.nn()` function is doing? I used it for the coordinates (x,y) of points in dataset and test set by this`flann.nn(dataset,testset, 5, algorithm="kdtree")` to obtain the 5 neareset points. Is it correct or my understanding is wrong?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49229804

http://stackoverflow.com/a/49229356
has comment: http://stackoverflow.com/comment/85480809
has body: One possible solution could be trying auto-plugging, basically you use the typefind element to parse incoming buffers to determine the format.
answers question: http://stackoverflow.com/q/49221839
type: Answer
score: 0

http://stackoverflow.com/comment/85357204
type: Comment
comment on: http://stackoverflow.com/q/49172719
type: QuestionComment
has text: Ok, sorry if it was unclear what i requested. To boil it down; check if an emails exists in multiple csv files regardless of the csv filename (filen,file0 etc). If is found i more than one file, write the email to a new file. Preferably the entire row where the email exists.
score: 0

http://stackoverflow.com/q/49259661
upvote count: 1
has answer: http://stackoverflow.com/a/49260254
favorite count: 0
type: Question
tagged with: timezone
tagged with: database
tagged with: django
tagged with: python
has body: I am looking into django db backends. I have found that datetime values' timezone are changed to and forth by django, while saving dates into db as well as retrieving them. During this conversion process, django uses database connection's timezone settings. I have seen that by default for sqlite db, 'UTC' is the timezone. I want to change the database connections options, during the start of django application. How can I do that ? Thanks in advance.
type: AnsweredQuestion
has title: How to customize database connection settings' timezone in django?
tagged with: database-connection
score: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/49260254
downvote count: 0
linked to: http://stackoverflow.com/q/29311354

http://stackoverflow.com/q/49142826
has comment: http://stackoverflow.com/comment/85291286
has answer: http://stackoverflow.com/a/49142911
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85291298
has comment: http://stackoverflow.com/comment/85291338
has comment: http://stackoverflow.com/comment/85291219
has comment: http://stackoverflow.com/comment/85291417
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/9589453
has comment: http://stackoverflow.com/comment/85291283
has title: How to efficiently extract unique rows from massive CSV using Python or R
has answer: http://stackoverflow.com/a/49142919
answer count: 2
has body: I have a massive CSV (1.4gb, over 1MM rows) of stock market data that I will process using R. The table looks roughly like this. For each ticker, there are thousands of rows of data. +--------+------+-------+------+------+ | Ticker | Open | Close | High | Low | +--------+------+-------+------+------+ | A | 121 | 121 | 212 | 2434 | | A | 32 | 23 | 43 | 344 | | A | 121 | 121 | 212 | 2434 | | A | 32 | 23 | 43 | 344 | | A | 121 | 121 | 212 | 2434 | | B | 32 | 23 | 43 | 344 | +--------+------+-------+------+------+ To make processing and testing easier, I'm breaking this colossus into smaller files using the script mentioned in this question: How do I slice a single CSV file into several smaller ones grouped by a field? The script would output files such as data_a.csv, data_b.csv, etc. But, I would also like to create index.csv which simply lists all the unique stock ticker names. E.g. +---------+ | Ticker | +---------+ | A | | B | | C | | D | | ... | +---------+ Can anybody recommend an efficient way of doing this in R or Python, when handling a huge filesize?
type: UnansweredQuestion
downvote count: 2
upvote count: 1
tagged with: python
score: -1

http://stackoverflow.com/q/49211783
score: 9
type: Question
has body: I am trying to understand why the scipy.optimize.least_squares exists in scipy. This function can be used to perform model-fitting. However, one could use scipy.optimize.minimize to do the same thing. The only difference is that scipy.optimize.least_squares does the calculation of the chi-squared internally, while if one wants to use scipy.optimize.minimize, he/she will have to calculate the chi-squared manually inside the function the user want to minimize. Also, scipy.optimize.least_squares can not be considered a wrapper around scipy.optimize.minimize because the three methods it supports (trf, dogbox, lm), are not supported at all by scipy.optimize.minimize. So my questions are: Why scipy.optimize.least_squares exists when the same result can be achieved with scipy.optimize.minimize? Why scipy.optimize.minimize does not support the trf, dogbox, and lm methods? Thank you.
has comment: http://stackoverflow.com/comment/85428195
has comment: http://stackoverflow.com/comment/85433798
answer count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/44224765
has answer: http://stackoverflow.com/a/57770150
tagged with: python
has comment: http://stackoverflow.com/comment/101977304
tagged with: model-fitting
tagged with: mathematical-optimization
has answer: http://stackoverflow.com/a/77624817
upvote count: 10
downvote count: 1
tagged with: scipy
has title: Why does scipy.optimize.least_squares exist when scipy.optimize.minimize could potentially be used for the same things?
favorite count: 0
has comment: http://stackoverflow.com/comment/85428480

http://stackoverflow.com/q/49220538
type: AnsweredQuestion
tagged with: list
downvote count: 0
upvote count: 1
score: 1
has title: How to print an array in the form of key-value pairs in python?
has body: I have a collection of arrays such as a = [array([0, 1, 2, 3, 4]) array([0, 1, 2, 3]) array([0, 1, 2, 3, 4]) array([0, 1, 2, 3, 4, 5, 6, 7, 8]) array([0, 2, 3, 4, 5, 8, 9]) Is there any way to show this result is the form of key-value pairs like [[(0),(1,2,3,4)],[(1),(0,2,3)],[(2),(0,1,3,4)],[(3),(0,1,2,4,5,6,7,8)] [(4),(0,2,3,5,8,9)]] i will get increment by 1 in the key and that value will be not included in the values list I tried like this, but not able to put it into the required form. c = [id for id in b if id != i] for i, b in enumerate(a)]
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49225981
possible better answer: http://stackoverflow.com/a/49225981
answer count: 2
tagged with: key-value
has answer: http://stackoverflow.com/a/49220596
accepted answer: http://stackoverflow.com/a/49220596
has comment: http://stackoverflow.com/comment/85444697
tagged with: python
tagged with: list-comprehension

http://stackoverflow.com/comment/85393216
type: QuestionComment
score: 0
has text: click.echo('\033[31m' + 'Error:' + '\033[30m' + ' This error ... ')
comment on: http://stackoverflow.com/q/49194147
type: Comment

downsampling
tag name: downsampling
tags question: http://stackoverflow.com/q/49211981
type: Tag

http://stackoverflow.com/a/49240508
score: -3
has comment: http://stackoverflow.com/comment/85484783
has comment: http://stackoverflow.com/comment/85484695
has comment: http://stackoverflow.com/comment/85485972
type: Answer
has body: You can use assertRaises (https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises) like this: with self.assertRaises(Exception): foo() There is also a method assertLogs if you want to test logging.
has comment: http://stackoverflow.com/comment/85484723
upvote count: 0
downvote count: 3
answers question: http://stackoverflow.com/q/49240434

http://stackoverflow.com/comment/85340512
type: Comment
score: 0
has text: I read the file ‘D:/test.3ds’ and I moved an object higher ( +200 to the z axis) then I exported it to ‘D:/Exportedfile.gltf’
type: QuestionComment
comment on: http://stackoverflow.com/q/49151031

http://stackoverflow.com/a/49242762
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49242649
score: 0
answers question: http://stackoverflow.com/q/49242649
type: Answer
has body: df[0] would give you a Series for a column 0, which you don't have (but e.g df[' State-gov'] would work). To get the first entry, use df.iloc(0) Documentation

http://stackoverflow.com/q/49242094
answer count: 1
tagged with: pymongo
accepted answer: http://stackoverflow.com/a/49250889
has answer: http://stackoverflow.com/a/49250889
tagged with: python-3.x
type: AnsweredQuestion
has title: pymongo.errors.BulkWriteError when inserting json, what cause it?
has body: Since the jsons im trying to insert into the database ain't properly formated as json, I append it to a list and json.loads it, for finally to insert it all into a mongodb document. What am I doing wrong? When I try to insert it into the database I get the following error: Traceback (most recent call last): File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/import_messages_dev.py", line 41, in &lt;module&gt; messages.insert_many(json_data) File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/collection.py", line 742, in insert_many blk.execute(self.write_concern.document, session=session) File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/bulk.py", line 432, in execute return self.execute_command(generator, write_concern, session) File "/media/anon/06bcf743-8b4d-409f-addc-520fc4e19299/PycharmProjects/LiveMe/venv1/lib/python3.6/site-packages/pymongo/bulk.py", line 329, in execute_command raise BulkWriteError(full_result) pymongo.errors.BulkWriteError: batch op errors occurred My code is as follow: ### DATABASE #### # Connect to database // login user:password uri = 'mongodb://testuser:password@ds245687.mlab.com:45687/liveme' # Set client. client = pymongo.MongoClient(uri) # Set database. db = client.get_database() # Create collection. messages = db['messages'] # The url to the live.me replays. replay_url = "http://live.ksmobile.net/live/getreplayvideos?" userid = 895324164037541888 # Parsing the urls for replays and profile with the userid. url2 = replay_url + urllib.parse.urlencode({'userid': userid}) + '&amp;page_size=1000' # Printing urls for own validation. print(f"Replay url: {url2}\n") raw_replay_data = requests.get(url2).json() # Insert messages to database. for i in raw_replay_data['data']['video_info']: url3 = i['msgfile'] raw_message_data = urllib.request.urlopen(url3) json_data = [] for line in r…
tagged with: http://stackoverflow.com/tag/json
tagged with: python
type: Question
tagged with: mongodb
score: 0

http://stackoverflow.com/a/49230641
has comment: http://stackoverflow.com/comment/85541518
score: 0
answers question: http://stackoverflow.com/q/49228896
has comment: http://stackoverflow.com/comment/85546819
has body: Use the args argument: args : tuple, optional Extra arguments passed to the objective function. The correct syntax looks like this: res = minimize_scalar(f, args=(2, 3))
type: Answer

http://stackoverflow.com/comment/85457044
type: Comment
type: QuestionComment
has text: The next problem is that `n[i].update(…)` asks it to add every member of a sequence, but you're only giving it a single value. That happens not to be an error, because a single-character string is actually a sequence of one single-character string, but it's confusing.
comment on: http://stackoverflow.com/q/49226574
score: 0

http://stackoverflow.com/comment/85514581
score: 0
has text: The first (zeroeth) argument is the script name itself. If you have two parameters, `sys.argv` will have length 3.
type: QuestionComment
comment on: http://stackoverflow.com/q/49236459
type: Comment

http://stackoverflow.com/q/49261388
score: 0
tagged with: pandas-groupby
accepted answer: http://stackoverflow.com/a/49261431
answer count: 1
has answer: http://stackoverflow.com/a/49261431
has title: groupby.apply apply only to a part of the columns
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/85526596
tagged with: python
has body: I'm trying to do a groupby.apply on a dataframe but only apply to some of the columns. My data looks like that: a b c d e 0 1 1 1 4 9 1 1 2 2 7 0 2 1 1 3 4 7 3 2 1 4 3 3 4 2 2 5 2 8 5 2 3 6 6 3 6 2 1 7 3 6 7 3 2 8 4 4 8 3 3 9 5 2 and I would like to groupby a, b and c (group all rows where all three columns are the same), and then sum columns c and e to get: a b c d e 0 1 1 4 4 16 1 1 2 2 7 0 2 2 1 11 3 9 3 2 2 5 2 8 4 2 3 6 6 3 5 3 2 8 4 4 6 3 3 9 5 2 (I summed values in columns c and e in rows (0,2) and (3,6)) I tried the following: a.groupby(['a','b','d'], as_index = False).apply(sum) But I get: a b c d e a b d 1 1 4 2 2 4 8 16 2 7 1 2 2 7 0 2 1 3 4 2 11 6 9 2 2 2 2 5 2 8 3 6 2 3 6 6 3 3 2 4 3 2 8 4 4 3 5 3 3 9 5 2 My problem here is that the values in columns a, b and d where summed as well, while I wanted them left as-is. How can I avoid applying the sum to the columns I'm grouping by?
type: AnsweredQuestion

http://stackoverflow.com/comment/135832781
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49206672
has text: @neverwalkaloner -- in my dev environment (Visual Studio Code, v1.81.1) that gets flagged as a JS syntax error. It gets confused because you have single quotes nested inside single quotes. Also, you're missing the closing semicolon between the closing single & double quote. Also, the `type="button"` is redundant, this is a ` ` element to begin with.

http://stackoverflow.com/q/49150330
has title: What's happening with these transient models' IDs?
score: 2
type: AnsweredQuestion
tagged with: python-2.7
tagged with: odoo
tagged with: odoo-8
accepted answer: http://stackoverflow.com/a/49152042
tagged with: python
has body: THE CODE I have the following transient models: class MoveLotsManager(models.TransientModel): _name = 'move.lots.manager' product_lots_available = fields.One2many( comodel_name='move.product.lot.available', inverse_name='manager_id', string='Available lots', ) class MoveProductLotAvailable(models.TransientModel): _name = 'move.product.lot.available' manager_id = fields.Many2one( comodel_name='move.lots.manager', string='Lots Manager', ) name = fields.Char( string='Name', ) @api.one @api.onchange('name') def onchange_name(self): # LOGGER 4 _logger.info(self.manager_id) # LOGGER 5 _logger.info(self.manager_id.id) As you can see, they both are connected through a 1:N relationship. I open the transient models' views this way: @api.multi def open_move_lots_manager_wizard(self): self.ensure_one() wizard_id = self.env.ref( 'my_module.view_move_lots_manager_wizard').id default_lots = [( (0, 0, { 'name': 'My lot', }) )] lots_manager = self.env['move.lots.manager'].create({ 'product_lots_available': default_lots, }) # LOGGER 1 _logger.info(lots_manager) # LOGGER 2 _logger.info(lots_manager.id) # LOGGER 3 _logger.info(lots_manager.product_lots_available.mapped('manager_id')) return { 'name': _('Lots manager'), 'view_type': 'form', 'view_mode': 'form', 'view_id': False, 'res_id': lots_manager.id, 'views': [(wizard_id, 'form'), ], 'res_model': 'move.lots.manager', 'type': 'ir.actions.act_window', 'target': 'new', 'flags': { 'form': { 'action_buttons': False, }, }, } MY PURPOSE In the onchange_name method of the model move.product.lot.available, I want to access to its related manager (and their fields). THE EXPECTED BEHAVIOUR Imagine the move.lots.manager I've just created has the ID 11. LOGGER 1: move.lots.manager(11,) LOGGER 2: 11 LOGGER 3: move.lots.manager(11,) LOGGER 4: move.lots.manager(11,) LOGGER 5: 11 THE CURRENT BEHAVIOUR LOGGER 1: move.lots.manager(11,) LOGGER 2: 11 LOGGER 3: move.lots.manager(11,) LOGGER 4: move.lots.manager(&lt;openerp.models.NewId object at 0x7fd1a…
favorite count: 0
type: Question
upvote count: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49152042

http://stackoverflow.com/comment/85389408
has text: Or it's just the number of characters
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49191883

http://stackoverflow.com/comment/85438577
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49217069
has text: That duplicate gets a frustrating number of nuances wrong; for example, edit 5 in the question thinks that class scopes can't access variables from enclosing function scopes at all.
score: 0

http://stackoverflow.com/q/49157985
downvote count: 0
upvote count: 1
answer count: 1
has title: Call a Python script with parameters from a Python script
type: AnsweredQuestion
tagged with: python
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85320916
accepted answer: http://stackoverflow.com/a/49158187
type: Question
has comment: http://stackoverflow.com/comment/85321576
has body: Let's say I have a Python script named script1.py that has the following code: import sys name = sys.argv[1] print("Bye", name) And a second Python script script2.py that calls the first one: import sys name = sys.argv[1] print("Hello", name) import script1 How can I pass an argument from the second script to the first one, as in the given examples? I'd like the output to look like this when I run my script from the terminal: &gt;&gt; python script2.py Bob Hello Bob Bye Bob
has answer: http://stackoverflow.com/a/49158187

http://stackoverflow.com/a/49135795
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49135233
score: 2
has body: This should do it: positions = [(y, x) for x, y in enumerate(np.argmax(np.isin(a, [32,38]), axis=0))] result = np.zeros(a.shape) for p in positions: result[p] = a[p] #[[ 0 , 0 , 0 ], # [ 0 , 0 , 32.], # [38., 0 , 0 ], # [ 0 , 32., 0 ], # [ 0 , 0 , 0 ]]
upvote count: 2

raspberry-pi
tags question: http://stackoverflow.com/q/49156591
tags question: http://stackoverflow.com/q/49161006
tags question: http://stackoverflow.com/q/49211826
tags question: http://stackoverflow.com/q/49198623
tags question: http://stackoverflow.com/q/49197330
tags question: http://stackoverflow.com/q/49228504
tags question: http://stackoverflow.com/q/49237667
type: Tag
tags question: http://stackoverflow.com/q/49151849
tags question: http://stackoverflow.com/q/49185964
tags question: http://stackoverflow.com/q/49132360
tags question: http://stackoverflow.com/q/49267510
tag name: raspberry-pi
tags question: http://stackoverflow.com/q/49274009
tags question: http://stackoverflow.com/q/49236212
tags question: http://stackoverflow.com/q/49153583
tags question: http://stackoverflow.com/q/49182094
tags question: http://stackoverflow.com/q/49252137
tags question: http://stackoverflow.com/q/49144446
tags question: http://stackoverflow.com/q/49149759
tags question: http://stackoverflow.com/q/49195189
tags question: http://stackoverflow.com/q/49229570
tags question: http://stackoverflow.com/q/49222435

http://stackoverflow.com/a/49204479
answers question: http://stackoverflow.com/q/49204453
downvote count: 0
score: 23
has body: I would recommend using pandas to convert your numpy.datetime: import pandas as pd import numpy as np x = np.datetime64('2010-06-01T00:00:00.000000000') x = pd.to_datetime(x) str(x.date()) returns: '2010-06-01' This can also work if you have multiple strings you want to convert: x = [np.datetime64(i) for i in ['2010-06-01T00:00:00.000000000', '2010-12-02T00:00:00.000000000']] x = pd.to_datetime(x) [str(i.date()) for i in x] returns: ['2010-06-01', '2010-12-02']
upvote count: 23
type: Answer
accepted answer of: http://stackoverflow.com/q/49204453
type: AcceptedAnswer

http://stackoverflow.com/q/49215996
tagged with: python
has comment: http://stackoverflow.com/comment/85438050
has comment: http://stackoverflow.com/comment/85437663
linked to: http://stackoverflow.com/q/8699293
has title: python detect new files without walk
downvote count: 0
linked to: http://stackoverflow.com/q/17041889
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85437373
answer count: 1
has answer: http://stackoverflow.com/a/49216294
has comment: http://stackoverflow.com/comment/85437233
has comment: http://stackoverflow.com/comment/85437212
favorite count: 0
tagged with: os.walk
type: Question
has body: There are lots of questions about using python to determine whether files were modified within a directory (see [1], [2]). Invariably the answer to these questions involves walking through the directory (os.walk) to check things individually. Is there any way to do this without a walk? I have a large/deep directory structure and it is costly to check each subdirectory (and its subdirectories, recursively). I am wondering if this task can be accomplished only looking at a top level directory. In this schema, the modification time of dir changes when subdir is created. But it does not change when file is created. The problem would be solved if modification times were affected by all child files and directories. dir/ |--- subdir/ │ |------- file A quick script to facilitate testing: import os os.system('rm -rf dir') os.system('mkdir dir') m1 = os.path.getmtime('dir') os.system('mkdir dir/subdir') m2 = os.path.getmtime('dir') os.system('touch dir/subdir/file') m3 = os.path.getmtime('dir') print m1 == m2 # False print m2 == m3 # True
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85437170
linked to: http://stackoverflow.com/q/19251993

http://stackoverflow.com/comment/85334331
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49164393
has text: Why don't you debug it yourself? Why do you expect that we will be able to debug it better than you?

http://stackoverflow.com/comment/88267397
type: Comment
type: QuestionComment
has text: I have the same issue, importing `requests`
comment on: http://stackoverflow.com/q/49166873
score: 0

http://stackoverflow.com/comment/85552544
score: 0
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/49275041
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85524892
comment on: http://stackoverflow.com/q/49254111
score: 0
type: Comment
type: QuestionComment
has text: An earlier question on row wise divide, https://stackoverflow.com/questions/44080315/division-of-sparse-matrix

http://stackoverflow.com/a/49220296
has body: You can greatly speed your computation by avoiding the for loops. Could you try this first? df1['str'] = df1['str'].add('a').str.upper() If it is still slow you could try: from dask import delayed @delayed def alter_array(df1): df1['str'] = df1['str'].add('a').str.upper() return df1 df1 = alter_array(df1).compute()
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49219737
score: 2
answers question: http://stackoverflow.com/q/49219737
type: Answer

http://stackoverflow.com/a/49175850
has body: This string: file_path = "C:\Script\poop.txt" is un-escaped. Thus the path becomes something like "C:Scriptpoop.txt". Use a raw string: file_path = r"C:\Script\poop.txt" or use \\ instead of \.
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49175172
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85356844

http://stackoverflow.com/comment/85396016
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49193921
has text: I edited my question. I typed wrong coordinates, but the querstion is: How can I create the desired output from the two column (name, Coords) of my Pandas DataFrame table.

http://stackoverflow.com/q/49156883
has title: Grouping and merging two dataframes in Python
has body: I have been banging my head around this one for some time now and can't get my head around it... I have two Pandas Dataframes df1 and df2 which contains information that I want to summarize neatly into one. So far, I have used an aggregate function to summarize each of these as follows: aggregation = {'A' : {'a' : 'mean'}, 'B' : {'b' : 'mean'}, 'C' : {'c' : 'sum'}} &gt;&gt; df1.groupby(by=['LEVEL_1']).agg(aggregation) A B C a b c LEVEL_1 lvl_a 1.0 2.0 3.0 lvl_b 4.0 5.0 6.0 lvl_c 7.0 8.0 9.0 Same for my other DataFrame &gt;&gt; df2.groupby(by=['LEVEL_1']).agg(aggregation) A B C a b c LEVEL_1 lvl_a 10.0 11.0 12.0 lvl_b 13.0 14.0 15.0 lvl_c 16.0 17.0 18.0 Now, I would like to combine these two into one, total, DataFrame where my columns are grouped into the two "information universes", with an additional row totals, which is the mean of all the rows, per column, like so: a b c df1 df2 df1 df2 df1 df2 LEVEL_1 lvl_a 1.0 10.0 2.0 11.0 3.0 12.0 lvl_b 4.0 13.0 5.0 14.0 6.0 15.0 lvl_c 7.0 16.0 8.0 17.0 9.0 18.0 totals 4.0 13.0 5.0 14.0 6.0 15.0 There is, most likely, a supereasy way to do this, but I have not figured it out... Thanks in advance guys.
type: AnsweredQuestion
score: 0
tagged with: pandas-groupby
tagged with: pandas
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/49157029
accepted answer: http://stackoverflow.com/a/49157029
answer count: 1

http://stackoverflow.com/q/49275570
tagged with: python
tagged with: lstm
score: 0
has body: I'm having some trouble calculating the RMSE (root-mean-squared-error) in my LSTM model. The model fits fine and I'm getting a good loss reduction, however when trying to inverse_transform my yhat results I get the following error: non-broadcastable output operand with shape (399,1) doesn't match the broadcast shape (399,4) Here's my code: Preprocessing: btc = pd.read_csv('live_bitcoin.csv') twitter_sent = pd.read_csv('live_tweet.csv') reddit_sent = pd.read_csv('live_reddit.csv') btc.columns = ["price_usd","24h_volume_usd","market_cap_usd","available_supply","total_supply","percent_change_1h","percent_change_24h","percent_change_7d", "Sell", "Buy", "15m", "Stamp"] twitter_sent.columns = ["Sentiment", "Stamp"] reddit_sent.columns = ["Sentiment", "Stamp"] merged = pd.merge(twitter_sent, btc, on='Stamp', how='inner').merge(reddit_sent, on='Stamp', how='inner') data = merged"Sentiment_x", "Sentiment_y","24h_volume_usd", "market_cap_usd", "available_supply","price_usd".groupby(merged['Stamp']).mean() datag = data"24h_volume_usd", "market_cap_usd", "available_supply","price_usd" tw_sentiment = data["Sentiment_x"] rdt_sentiment = data["Sentiment_y"] print "Dataset size: " + str(len(datag)) print "Timespan: " + str(len(datag)/60) + " hours" from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(0, 1)) values = datag.values.reshape(-1, datag.shape[1]) tw_sentiment = tw_sentiment.values.reshape(-1, 1) rdt_sentiment = rdt_sentiment.values.reshape(-1, 1) tw_sentiment = tw_sentiment.astype('float32') rdt_sentiment = rdt_sentiment.astype('float32') values = values.astype('float32') scaled = scaler.fit_transform(values) Training: train_size = int(len(scaled) * 0.7) test_size = len(scaled) - train_size train, test = scaled[0:train_size,:], scaled[train_size:len(scaled),:] split = train_size def create_dataset(dataset, look_back, tw_sentiment, rdt_sentiment, sent=False): dataX, dataY = [], [] for i in range(len(dataset) - look_back): if i &gt;= l…
answer count: 2
type: UnansweredQuestion
tagged with: machine-learning
tagged with: scikit-learn
has title: LSTM. Calculating RMSE using inverse_transform
tagged with: keras
has answer: http://stackoverflow.com/a/56371093
has answer: http://stackoverflow.com/a/50012837
type: Question

http://stackoverflow.com/a/49205765
has body: Both options are valid. The farther you are from the end of your network, the less specialized the features will be to your problem/training set, while still capturing relevant information that may be applied to similar tasks. As you move to the end of the network, the features will be more tuned to your task. Note that you are dealing with two similar problems/tasks. The network was fine-tuned for car classification ("which model is this car?") and now you want to verify if two cars belong to the same model. Considering the network was fine-tuned with a large and representative training set, the features obtained from it are powerful and with a lot of representation capability (i.e., they capture a lot of complex underlying patterns of the task they were trained to) that are useful to your verification task. With this in mind, you could try many ways of comparing two feature vectors: Euclidean Distance is too simple. I would try it only because it is easy/fast to implement; Cosine Similarity [1] might also be a simple, but good starting point; Classifier. Another possibility that I've have done in a similar problem was to train a classifier (SVM, Logistic Regression) on top of a combination of the two features. The input of your classifier could be the concatenation of them side by side. Incorporate the verification task to your network. You could alter the GoogleNet architecture to receive two photos of cars and output if they belong or not to the same model. You would be transforming/fine-tuning your network from the classification problem to a verification task. Check for siamese networks [2]. Edit: there is a mistake when you resize your frame that may be the cause of your problems! # I read my image of size (x,y,3) frame = cv2.imread(frame_path) # resized my image to 224,224,3, network input size. bbox = cv2.resize(frame, (224, 224)) You should have passed frame as input in the cv2.resize() method. You are probably feeding a garbage input to the network and th…
has comment: http://stackoverflow.com/comment/85436857
has comment: http://stackoverflow.com/comment/85417041
answers question: http://stackoverflow.com/q/49200276
has comment: http://stackoverflow.com/comment/85417031
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/85427922
has comment: http://stackoverflow.com/comment/85436877

http://stackoverflow.com/a/49228725
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49228520
score: 1
downvote count: 0
has body: Concatenate your dataframes using concat, and then group and plot them by country using groupby + plot: df = pd.concat( [df4, df5, df6], keys=['Argentina', 'Columbia', 'Brazil'] ) df.astype(int).groupby(level=0).plot.bar(x='Year', y='Mortality'); plt.show() This gives you separate plots for each group.

http://stackoverflow.com/comment/85541169
comment on: http://stackoverflow.com/q/49268864
score: 0
has text: Then I don't understand your question. You use the words shorthand and less iterations. What are you trying to optimize?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/66096646
has body: """ @Author: Aseem Jain @profile: https://www.linkedin.com/in/premaseem/ """ import os import pymongo # configure credentials / db name db_user = os.environ["MONGO_ATLAS_USER"] db_pass = os.environ["MONGO_ATLAS_PASSWORD"] db_name = "sample_mflix" connection_string = f"mongodb+srv://{db_user}:{db_pass}@sharedcluster.lv3wx.mongodb.net/{db_name}?retryWrites=true&w=majority" client = pymongo.MongoClient(connection_string) db = client[db_name] # create database back directory with db_name os.makedirs(db_name, exist_ok=True) # list all tables in database tables = db.list_collection_names() # dump all tables in db for table in tables: print("exporting data for table", table ) data = list(db[table].find()) # write data in json file with open(f"{db.name}/{table}.json","w") as writer: writer.write(str(data)) exit(0)
answers question: http://stackoverflow.com/q/49153020
type: Answer
has comment: http://stackoverflow.com/comment/133941644
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/85457019
has text: @Blender Yes, true. But I've always been taught it was generally considered poor form to put imports anywhere except at the top, above your code?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49226554
type: Comment

http://stackoverflow.com/q/49245996
has title: How to transfer edge directions from one networkx graph object to another?
type: Question
tagged with: dataframe
tagged with: python
type: UnansweredQuestion
tagged with: pandas
score: 0
has answer: http://stackoverflow.com/a/49246514
answer count: 1
tagged with: networkx
tagged with: numpy
has body: Let's say I have a pandas dataframe of the form df Source Target Weight Type A B 0.4 Directed B A 0.2 Directed A C 0.5 Directed C A 0.5 Directed .. I get a directed graph object from this dataframe using networkx called G1. I also have a dataframe df2 of the form, Source Target Weight Type A B 0.4 Undirected A C 0.1 Undirected .. I get an undirected graph from this dataframe called G2. As you can see, unlie G1, this is undirected. I want to know how I can transfer the directions from G1 to G2. This can be done either at the pandas stage or the graph object stage. The following is the basic logic in interpreting directionality in G1 (note that edges exist both ways from A-B and B-A, likewise for A-C and C-A). For a given pair (assume AB) we take the direction for which the value of the weight is higher. In our example, we retain AB as the resultant direction since its weight is greater than BA. In the case of a tie we may take either of the values (for instance CA). Finally, these directions need to be applied to G2. So now AB in G2 is a directed source-target pair and so is CA. What is the best way to achieve this?

http://stackoverflow.com/comment/85550628
has text: EDIT: I am running postgresql 9.3, and it seems this feature has been introduced in 9.4. I replaced the FILTER statements by CASE WHEN statements and it worked. Thanks so much!!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49219402
score: 0

http://stackoverflow.com/a/49230476
answers question: http://stackoverflow.com/q/49230262
has comment: http://stackoverflow.com/comment/85464378
has comment: http://stackoverflow.com/comment/85465516
has comment: http://stackoverflow.com/comment/85465112
type: Answer
has comment: http://stackoverflow.com/comment/85465412
has comment: http://stackoverflow.com/comment/85464340
has comment: http://stackoverflow.com/comment/85464449
has comment: http://stackoverflow.com/comment/85464390
score: 2
has body: Here's an extremely performant solution that manipulates ASCII codes: v = df.Body.values.astype(str) v = v.view(np.uint8).reshape(len(df), -1) df['Uppercase'] = ((v &gt;= 65) &amp; (v &lt;= 90)).sum(1) df['Lowercase'] = ((v &gt;= 97) &amp; (v &lt;= 122)).sum(1) df No Body Uppercase Lowercase 0 1 DaTa Analytics 3 10 1 2 StackOver 2 7 Timings df = pd.concat([df] * 100000, ignore_index=True) # @jezrael1 %%timeit df['Uppercase'] = df['Body'].str.findall(r'[A-Z]').str.len() df['Lowercase'] = df['Body'].str.findall(r'[a-z]').str.len() 979 ms ± 24.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # @jezrael2 %%timeit df['Uppercase'] = [sum(1 for c in x if c.isupper()) for x in df['Body']] df['Lowercase'] = [sum(1 for c in x if c.islower()) for x in df['Body']] 1.11 s ± 130 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # in this post %%timeit v = df.Body.values.astype(str) v = v.view(np.uint8).reshape(len(df), -1) df['Uppercase'] = ((v &gt;= 65) &amp; (v &lt;= 90)).sum(1) df['Lowercase'] = ((v &gt;= 97) &amp; (v &lt;= 122)).sum(1) 91.8 ms ± 315 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/85487237
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49241719
has text: you can use a dictionary or an array to store corresponding tuples (x,y,z). In case of dict, your func can return key-value pair having filename as key and tuple as value.
score: 0

http://stackoverflow.com/comment/85450755
has text: 2 Mrt Actually, I wasn t much concrete. I have 6 sequences at the beginning and I need to break it smartly into subsequences and the problem is to find the borders of these subsequences. These borders are defined rather by crossing the same elements in each set (if I try to solve this task via set, of course, which could be a wrong way). In this contest such sequences which you mentioned couldn t appear here, because intersecton() and difference() don`t work like that.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49223147

http://stackoverflow.com/q/49136635
tagged with: sparql
tagged with: stardog
has comment: http://stackoverflow.com/comment/85282535
type: AnsweredQuestion
tagged with: rdflib
upvote count: 3
has comment: http://stackoverflow.com/comment/85298129
downvote count: 0
has comment: http://stackoverflow.com/comment/85280517
answer count: 1
has comment: http://stackoverflow.com/comment/85297716
has comment: http://stackoverflow.com/comment/85298528
tagged with: named-graphs
has body: I try to query a database like this: from rdflib import Graph, Literal, URIRef from rdflib.namespace import RDF, SKOS from rdflib.plugins.stores import sparqlstore # define endpoint according to https://www.stardog.com/docs/ endpoint = 'http://path/to/query' # http://&lt;server&gt;:&lt;port&gt;/{db}/query # create store store = sparqlstore.SPARQLUpdateStore() # I only want to query store.open(endpoint) store.setCredentials('me', 'my_pw') # What does this actually do? That runs through default_graph = URIRef('some:stuff') ng = Graph(store, identifier=default_graph) # # If identifier is not defined, it crashes # ng = Graph(store) rq = """ SELECT ?foo ?bar WHERE { ?something a &lt;http://path/to/data/.ttl#SomeValues&gt;. ?something &lt;http://path/to/data/.ttl#foo&gt; ?foo. ?something &lt;http://path/to/data/.ttl#bar&gt; ?bar. } """ query_res = ng.query(rq) for s, l in query_res: print(s, l) Unfortunately, I don't get any results at the moment: &lt;head&gt;&lt;variable name="foo"&gt;&lt;/variable&gt;&lt;variable name="bar"&gt;&lt;/variable&gt;&lt;/head&gt;&lt;results&gt;&lt;/results&gt;&lt;/sparql&gt; My question is, what the identifier in Graph is doing i.e. whether this is important and if so, how it should be defined. When I do not define it, the code crashes with: Response: b'{"message":"No separator character found in the URI: N53e412e0f3a74d6eab7ed6da163463bf"}' If I put in anything else that has a colon, or slash in it, it runs through (but the query still does not return anything). Could anyone briefly explain, what one should put in there and whether this might be the cause for the unsuccessful query (the query command itself is correct; when I call it from another tool, it works fine)?
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/85280692
has comment: http://stackoverflow.com/comment/85282433
has comment: http://stackoverflow.com/comment/85282084
has comment: http://stackoverflow.com/comment/85282431
linked to: http://stackoverflow.com/q/26403868
has answer: http://stackoverflow.com/a/49155203
accepted answer: http://stackoverflow.com/a/49155203
has title: What does the "identifier" in "Graph" do?
tagged with: python

http://stackoverflow.com/q/49277692
favorite count: 0
has body: When I type in MyFloatInput TextInput then text start from right side of TextInput,It's working perfect but I set value of MyFloatInput TextInput from .py then it start from left side.It doesn't show in right side. Can someone tell me what is wrong with code? test.py import kivy from kivy.uix.screenmanager import Screen from kivy.app import App from kivy.lang import Builder from kivy.core.window import Window from kivy.clock import Clock from kivy.uix.textinput import TextInput Window.clearcolor = (0.5, 0.5, 0.5, 1) Window.size = (400, 100) class MyFloatInput(TextInput): def __init__(self, **kwargs): super(MyFloatInput, self).__init__(**kwargs) self.multiline = False def right_adjust(self, text): max_width = self.width - self.padding[0] - self.padding[2] new_text = text text_width = self._get_text_width(new_text, self.tab_width, self._label_cached) while text_width &lt; max_width: new_text = ' ' + new_text text_width = self._get_text_width(new_text, self.tab_width, self._label_cached) while text_width &gt;= max_width: if new_text[0] != ' ': break else: new_text = new_text[1:] text_width = self._get_text_width(new_text, self.tab_width, self._label_cached) return new_text def delete_selection(self, from_undo=False): if not self._selection: return cr = self.cursor[1] initial_len = len(self._lines[cr]) a, b = self._selection_from, self._selection_to if a &gt; b: a, b = b, a super(MyFloatInput, self).delete_selection(from_undo=from_undo) cur_text = self._lines[cr] super(MyFloatInput, self)._refresh_text(self.right_adjust(cur_text)) final_len = len(self._lines[cr]) self.cursor = self.get_cursor_from_index(final_len - (initial_len - b)) def do_backspace(self, from_undo=False, mode='bkspc'): cc, cr = self.cursor initial_len = len(self._lines[cr]) super(MyFloatInput, self).do_backspace(from_undo=from_undo, mode=mode) cc, cr = self.cursor cur_text = self._lines[cr] super(MyFloatInput, self)._refresh_text(self.right_adjust(cur_text)) final_len = len(self._lines[cr]) self.curso…
accepted answer: http://stackoverflow.com/a/49467247
has title: Kivy : How to start text from right side in TextInput?
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49311450
has answer: http://stackoverflow.com/a/49467247
has answer: http://stackoverflow.com/a/49311450
tagged with: python
tagged with: kivy
has comment: http://stackoverflow.com/comment/85628065
type: Question
tagged with: python-2.7
tagged with: kivy-language
score: 0
answer count: 2
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/85335963
has text: Unlike your comment, your code returns true only when the answer is 'a' or 'a.'. You need to change that to match with the respective answers to your questions. But I have modified the code to ask the same question until the user gives a correct answer. You can add the score increment/decrement yourself based on how you evaluate the answers.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49165104
type: AnswerComment

http://stackoverflow.com/q/49129604
tagged with: class
type: AnsweredQuestion
has title: What is the best way to iteratively instantiate a class from a dictionary of lists/arrays?
score: 1
has body: I have dataset read from a textfile of many columns, each column of which corresponds to a dictionary key. As such, each dictionary key corresponds to a value that is an array. I would like to instantiate a class instance for all keys on a per index basis. The sample snippet below works, though I am wondering if there are better ways to do this (better in terms of speed, being pythonic, etc). First I initialize some sample data. import numpy as np ts = np.array([0, 2, 6, 10]) ss = np.array([100, 90, 120, 130]) ns = np.array(['A', 'C', 'G', 'K']) data = dict(time=ts, size=ss, name=ns) print(data) Which produces the following output: {'name': array(['A', 'C', 'G', 'K'], dtype='&lt;U1'), 'time': array([ 0, 2, 6, 10]), 'size': array([100, 90, 120, 130])} Then I create a sample class and instantiate per index of an arbitrary array (since they are all of the same size). class SampleProblem(): def __init__(self, time, size, name): self.time = time self.size = size self.name = name res = [] for idx in range(len(data['time'])): res.append(SampleProblem(data['time'][idx], data['size'][idx], data['name'][idx])) # not written as a list comprehension for readability purposes for idx in range(len(res)): print(res[idx].name) Which produces the following output: A C G K
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49129748
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49129748
tagged with: arrays
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/57265964
has body: In case anyone else comes across this using google as well. Since pandas version 0.23, you can pass the name of the level as an argument to sort_values: test.sort_values(['src','sum'], ascending=[1,0]) Result: sum count src dst 1 2 70 2 5 10 1 2 8 90 2 5 65 1
answers question: http://stackoverflow.com/q/49264510
upvote count: 9
score: 9
type: Answer
downvote count: 0

http://stackoverflow.com/q/49172201
has comment: http://stackoverflow.com/comment/86337074
accepted answer: http://stackoverflow.com/a/49178883
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49178883
score: 3
has comment: http://stackoverflow.com/comment/86337767
has body: There was the same question two years ago. It seemed that evey nth categorical tickers was not supported at that time. https://stackoverflow.com/questions/34949298/python-bokeh-show-only-every-second-categorical-ticker My bokeh version is 0.12.13. I wonder it is supported now. Simply setting p.xaxis.ticker = ['A', 'B, 'C'] does not work(error is thrown) In my dashbaord, the initial plot size is one quarter of browser view port and the x axis is crowded with many ticker and labels. So I want to show only 10 tickers and later show all of them when the plot is enlarged.
tagged with: ticker
has comment: http://stackoverflow.com/comment/86337602
upvote count: 3
answer count: 1
linked to: http://stackoverflow.com/q/34949298
has title: How to show only evey nth categorical tickers in Bokeh
tagged with: bokeh
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/49663952
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/85266422
comment on: http://stackoverflow.com/q/49130435
has text: @Anvesh `flag` field is working kind of `is_approved`. @NihalSharma your suggestion seems to work. I am inheriting from TimeStamp model which has `created_at` field, So I will try this. Thank you.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49202479
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: AnsweredQuestion
tagged with: mljar
has answer: http://stackoverflow.com/a/49202971
accepted answer: http://stackoverflow.com/a/49202971
has comment: http://stackoverflow.com/comment/116770667
tagged with: python
has body: I'm getting Ups, [Errno 2] No such file or directory error when I try to fit models using the python wrapper for the mljar api. Does anyone know how to fix this? The code: from sklearn import datasets iris = datasets.load_iris() X, y = iris.data, iris.target from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5) from mljar import Mljar models = Mljar( project='MLJAR api test', experiment='Iris', metric='logloss', validation_kfolds=5, # we will use 5-fold CV with stratify and shuffle validation_shuffle=True, validation_stratify=True, algorithms=['xgb', 'lgb', 'mlp'], # select Xgboost, LightGBM and Neural Network tuning_mode='Normal', # number of models to be checked for each algorithm single_algorithm_time_limit=5 ) models.fit(X_train, y_train) For some reason, there is no traceback. I just get the error: Ups, [Errno 2] No such file or directory: /tmp/dataset-002317be.csv
has comment: http://stackoverflow.com/comment/85410296
type: Question
has title: Mljar python wrapper api "no such file or directory" error
score: 0

http://stackoverflow.com/comment/85443280
score: 0
type: QuestionComment
has text: Negative exit codes are only possible on Windows I think, and could reflect a platform issue. Please [edit] your question to identify the precise environment.
type: Comment
comment on: http://stackoverflow.com/q/49219585

http://stackoverflow.com/comment/85317929
type: QuestionComment
has text: Can you post your setup.py file?
comment on: http://stackoverflow.com/q/49156529
score: 0
type: Comment

http://stackoverflow.com/q/49228666
has body: I have created a pseudorandom number generator and I am trying to pipe out the data similar to if someone ran "$ cat /dev/urandom/" Specifically, I am trying to pipe out the data to the dieharder RNG test suite. Typically, reading from urandom to dieharder looks like "$ cat /dev/urandom | dieharder -a -g 200" My program is designed to infinitely generate numbers and outputs them in main as: def main(): ... # setup and variables for _ in iter(int,1): # infinite loop PRNG_VAL = PRNG_FUNC(count_str,pad,1) # returns b'xx' PRNG_VAL = int(PRNG_VAL,16) # returns integer sys.stdout.write(chr(PRNG_VAL)) # integer to chr, similar to /dev/urandom type output Obviously, when I run something like "$ cat ./top.py | dieharder ..." the resulting output is just the reading of the contents of the file. How do I, instead of read the contents of 'top.py', run the file and pipe the output into dieharder similar to reading from /dev/urandom? Any help is appreciated!
has title: How to pipe out data from Python PRNG script similar to /dev/urandom into Dieharder
tagged with: python
has comment: http://stackoverflow.com/comment/85460811
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49228713
tagged with: random
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: testing
accepted answer: http://stackoverflow.com/a/49228713

http://stackoverflow.com/a/49246616
has body: You have a few issues. The main issue here is that your else clause has a return True inside the loop. What you'd want to do is finish iterating over the string before returning True. If you are familiar with boolean logic, this is the equivalent of short circuiting with AND. The other issue (not really an issue, more a nitpick) is that you can just use integer division //, instead of having to import math's floor function. So, def isPalindrome(string): for i in range(0, len(string) // 2): if string[i] != string[-(i + 1)]: return False return True Another way of handling this would be using all: def isPalindrome(string): return all(x == y for x, y in zip(string, reversed(string))) Or, taking advantage of python's convenient slice notation for the most concise solution possible, we have: def isPalindrome(string): return string == string[::-1]
accepted answer of: http://stackoverflow.com/q/49246587
upvote count: 2
has comment: http://stackoverflow.com/comment/85496972
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85496963
type: Answer
answers question: http://stackoverflow.com/q/49246587
score: 2

http://stackoverflow.com/a/49167155
answers question: http://stackoverflow.com/q/49166988
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49166988
score: 2
upvote count: 2
downvote count: 0
has body: You want to make sure your dates are in the index. Use pd.DataFrame.asfreq and pd.DataFrame.mean df.set_index('Pstng Date').asfreq('D').ffill().mean() DailyCustomerBalance 780359.246909 dtype: float64

http://stackoverflow.com/comment/86342982
comment on: http://stackoverflow.com/a/49164587
type: Comment
score: 2
type: AnswerComment
has text: @DaveX It's not only stored internally as `TEXT`, SQLite has no concept of it being anything else but `TEXT`. When you see things like `datetime.datetime` returned from `PARSE_DECLTYPES` that is because you are reading from Pandas which does have those types. They will always be stored as strings in SQLite as you've found. There is no solution on the SQLite side, your problem exists when reading SQLite back to Pandas, so the datatype conversion needs to happen on the Pandas side.

http://stackoverflow.com/q/49181661
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
score: 3
upvote count: 3
has body: I know that this is a very popular error, however, in my case, I was not able to figure out why that happening to me. I am getting: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy df['time'] = pd.to_datetime(df['time'], unit='ms') : SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead code: import pandas as pd from pandas import DataFrame def filter_df(df: DataFrame, symbol: str): return df.loc[(df['symbol'] == symbol)] def convert_time(df): df['time'] = pd.to_datetime(df['time'], unit='ms') return df df = pd.read_hdf(path_or_buf='/tmp/data/file.h5') df = filter(df, 'AAA') df = convert_time(df) Could you please help me to figure out why I am getting such warning?
tagged with: pandas
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49181703
has comment: http://stackoverflow.com/comment/85368950
has title: Pandas: SettingWithCopyWarning Try using .loc

http://stackoverflow.com/a/49212050
has comment: http://stackoverflow.com/comment/85429265
accepted answer of: http://stackoverflow.com/q/49211609
type: Answer
has comment: http://stackoverflow.com/comment/85429113
answers question: http://stackoverflow.com/q/49211609
score: 0
type: AcceptedAnswer
has body: The two input tensors don't have the shapes you think they have. According to the code sample, the shape of Wb is in fact (512, 512). However, by the title of your question I believe you've actually intended to initialize Wb as follows: Wb_intialization = np.random.randn(15, 512).astype(np.float32) * np.sqrt(2.0/(512)) (that is, (15, 512) instead of (512, 512)). Hence, the Wb tensor ends up with the shape (?, 15, 512). The shape of the V tensor is (?, 512, 196) (and not (512, 196)). Therefore, the shape of the tensor resulting from multiplying Wb and V is (?, 15, ?, 196). The reason the output shape is (?, 15, ?, 196) is because the "common" 512 dimension of the two input tensors ((?, 15, 512) and (?, 512, 196)) serves as the product axis. Hence, only the 512 dimension is absent from the result and the other three surrounding dimensions remain.

http://stackoverflow.com/q/49218782
tagged with: python
tagged with: httprequest
has body: When I post a string "\u062c\u0646\u062f\u064a\u0651\u0627" via an HTTP request it is received as the following '\\u062c\\u0646\\u062f\\u064a\\u0651\\u0627'. What are the extra backslashes added for? And how to strip them?
accepted answer: http://stackoverflow.com/a/65469492
downvote count: 0
has comment: http://stackoverflow.com/comment/85441350
upvote count: 1
has comment: http://stackoverflow.com/comment/85441393
answer count: 1
tagged with: string
tagged with: unicode
has title: Python string encoding: An extra backslash added to strings when sent over http
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65469492
score: 1

http://stackoverflow.com/comment/85399539
has text: Is it possible to make a decorator that returns a class instead of a function?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49197081
score: 0

http://stackoverflow.com/q/49200885
answer count: 1
has body: I am wondering how to create different output with one input statement in a for loop (see my code below). For instance, how should I make each input statement read Enter number 1:, Enter number 2: and so on. Should I have only one input statement or multiple? times = int(input("Enter how many numbers you want to sum")) sum = 0 for i in range(0, times): numInput = int(input("Enter number")) sum = sum + numInput print("The total is", sum)
favorite count: 0
type: Question
has title: How to create different output with one input statement in a for loop?
has comment: http://stackoverflow.com/comment/85407517
has comment: http://stackoverflow.com/comment/85407242
has comment: http://stackoverflow.com/comment/85407360
has comment: http://stackoverflow.com/comment/85406900
downvote count: 2
has comment: http://stackoverflow.com/comment/85407644
upvote count: 1
tagged with: python
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85407190
has comment: http://stackoverflow.com/comment/85407176
has answer: http://stackoverflow.com/a/49201113
accepted answer: http://stackoverflow.com/a/49201113

http://stackoverflow.com/a/49264275
score: 0
answers question: http://stackoverflow.com/q/49263926
has body: The % operator is string operator, more akin to C's sprintf than printf. It's not part of the print statement. What you've written is akin to print '#' * 25, print 'IMPLEMENTATION FOR %s', print '#' * 25 % initialize.ntw_device[index].hostname There is no format specifier in '#' # 25 for the hostname to fill, resulting in the error. You can write either print '#' * 25, \ 'IMPLEMENTATION FOR %s' % (initialize.ntw_device[index].hostname,) \ '#' * 25 or print ('#' * 25 + 'IMPLEMENTATION FOR %s' + '#' * 25) % (initialize.ntw_device[index].hostname,) It's considered good practice to always an explicit tuple instead of a single value as the right-hand argument, to guard against the possibility that the RHA evaluates to a tuple itself.
type: Answer

psycopg2
tags question: http://stackoverflow.com/q/49182172
tags question: http://stackoverflow.com/q/49161309
tags question: http://stackoverflow.com/q/49134178
type: Tag
tags question: http://stackoverflow.com/q/49177077
tags question: http://stackoverflow.com/q/49254588
tags question: http://stackoverflow.com/q/49249200
tag name: psycopg2
tags question: http://stackoverflow.com/q/49244643

http://stackoverflow.com/q/49267695
has title: Checking if Xpath Exists
type: AnsweredQuestion
score: 0
tagged with: http://stackoverflow.com/tag/html
answer count: 1
tagged with: selenium
upvote count: 1
has body: I'm currently using selenium, bs4 and python for scraping however I ran into a problem with regards to checking the Xpath if it exists or not, here's my code: def hasXpath(xpath): try: browser.get(quote_page) self.browser.find_element_by_xpath(xpath) return True except: return False # IF PRICELIST EXISTS CONDITION/ if hasXpath("(//div[@id='product-header h4']//span)[last()-2]") or hasXpath("(//div[@id='product-header']//span)[last()-1]") or hasXpath("(//div[@id='product-header']//span)[last()]"): #No. of Items Per Retail(NEED LOGIN) somthing = browser.find_element_by_xpath("(//div[@id='product-header']//td)[21]").get_attribute("innerText") print(somthing) #Retail Price(NEED LOGIN) browser.get(quote_page) somthing1 = browser.find_element_by_xpath("(//div[@id='product-header']//span)[last()]").get_attribute("innerText") print(somthing1) if hasXpath("(//div[@id='product-header']//span)[last()-1]"): #1No. of Items Per Retail(NEED LOGIN) something = browser.find_element_by_xpath("(//div[@id='product-header']//td)[19]").get_attribute("innerText") print(something) #1Retail Price(NEED LOGIN) browser.get(quote_page) something = browser.find_element_by_xpath("(//div[@id='product-header']//span)[last()-1]").get_attribute("innerText") print(something1) else: print("It didn't go inside") As you can see it has a simple function hasXpath() where I pass the xpaths for the condition in the IF statement below it. However when I test it, everything seems to be going to the else statement. I also tried doubling the True condition but no luck. What did I do wrong when implementing this?
has comment: http://stackoverflow.com/comment/85544623
downvote count: 1
favorite count: 0
type: Question
tagged with: beautifulsoup
tagged with: xpath
has comment: http://stackoverflow.com/comment/85539027
tagged with: python
accepted answer: http://stackoverflow.com/a/49268195
has answer: http://stackoverflow.com/a/49268195

http://stackoverflow.com/comment/90842393
score: 0
type: Comment
type: QuestionComment
has text: @user2957365 Alright, add me on Discord: Mr.Kwabs#9751
comment on: http://stackoverflow.com/q/49225456

http://stackoverflow.com/q/49204634
answer count: 1
linked to: http://stackoverflow.com/q/1373164
has title: Alias for this function or any other method to link url with flask
tagged with: flask
has body: I'm trying to understand how flask works. i have this code with other stuff @app.route("/") def profile(): for i in range(28): return render_template("profile.html",(data + str(i))=posts_to_chose[i]) i+=1 I want to rename data in data0, data1, data2.. So I can pass data to my html page: &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;body&gt; &lt;img src= {{data0}} title= "Title of image alt=" alt text here”&gt; &lt;img src= {{data1}} title= "Title of image alt=" alt text here”&gt; &lt;img src= {{data2}} title= "Title of image alt=" alt text here”&gt; ... &lt;img src= {{data_n}} title= "Title of image alt=" alt text here”&gt; &lt;/body&gt; &lt;/html&gt; But I keep get this error: return render_template("profile.html",(data + str(i))=posts_to_chose[i]) ^ SyntaxError: keyword can't be an expression I have 29 links and I know just this method to pass everything, if there is some other method please tell me Thankyou.
duplicate of: http://stackoverflow.com/q/1373164
type: Question
duplicate of: http://stackoverflow.com/q/334655
tagged with: http://stackoverflow.com/tag/html
tagged with: python
score: 0
has answer: http://stackoverflow.com/a/49204836
type: UnansweredQuestion

jupyter-notebook
tags question: http://stackoverflow.com/q/49177801
tags question: http://stackoverflow.com/q/49268918
tags question: http://stackoverflow.com/q/49218457
tags question: http://stackoverflow.com/q/49232939
tags question: http://stackoverflow.com/q/49219161
tags question: http://stackoverflow.com/q/49129817
tags question: http://stackoverflow.com/q/49253860
tags question: http://stackoverflow.com/q/49176373
tags question: http://stackoverflow.com/q/49175255
tags question: http://stackoverflow.com/q/49175406
tags question: http://stackoverflow.com/q/49182502
tags question: http://stackoverflow.com/q/49222299
tags question: http://stackoverflow.com/q/49196858
tags question: http://stackoverflow.com/q/49135963
tags question: http://stackoverflow.com/q/49131693
tags question: http://stackoverflow.com/q/49241799
tags question: http://stackoverflow.com/q/49251881
tags question: http://stackoverflow.com/q/49141525
tags question: http://stackoverflow.com/q/49141796
tags question: http://stackoverflow.com/q/49200465
tags question: http://stackoverflow.com/q/49128385
tags question: http://stackoverflow.com/q/49167705
tag name: jupyter-notebook
tags question: http://stackoverflow.com/q/49247530
tags question: http://stackoverflow.com/q/49233067
tags question: http://stackoverflow.com/q/49204803
tags question: http://stackoverflow.com/q/49200369
type: Tag
tags question: http://stackoverflow.com/q/49188966
tags question: http://stackoverflow.com/q/49235224
tags question: http://stackoverflow.com/q/49213056
tags question: http://stackoverflow.com/q/49228252
tags question: http://stackoverflow.com/q/49136246
tags question: http://stackoverflow.com/q/49216197
tags question: http://stackoverflow.com/q/49161749
tags question: http://stackoverflow.com/q/49136737
tags question: http://stackoverflow.com/q/49185419
tags question: http://stackoverflow.com/q/49174476

http://stackoverflow.com/q/49158493
has body: I'm getting an annoying error. You can find the C code in this temporary file: /tmp/theano_compilation_error_ppkcgkmi Traceback (most recent call last): File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/gof/lazylinker_c.py", line 75, in raise ImportError() ImportError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/gof/lazylinker_c.py", line 92, in raise ImportError() ImportError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/init.py", line 110, in from theano.compile import ( File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/compile/init.py", line 12, in from theano.compile.mode import * File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/compile/mode.py", line 11, in import theano.gof.vm File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/gof/vm.py", line 673, in from . import lazylinker_c File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/gof/lazylinker_c.py", line 127, in preargs=args) File "/home/ubuntu/my_project/venv/lib/python3.6/site-packages/theano/gof/cmodule.py", line 2359, in compile_str (status, compile_stderr.replace('\n', '. '))) Exception: Compilation failed (return status=1): /home/ubuntu/.theano/compiledir_Linux-4.4--aws-x86_64-with-Ubuntu-16.04-xenial-x86_64-3.6.4-64/lazylinker_ext/mod.cpp:1:20: fatal error: Python.h: No such file or directory. compilation terminated.. I'm using a P2 Instance from AWS where I installed Ubuntu 16.04. I'm just trying to import theano on python3.6.4 I've re-installed theano many times, also I installed MANY other stuff and it's not working. I have a virtual environment and I'm using the GPU. I assume my GPU-CUDA-CuNN is well installed &gt;&gt;&gt; sess = tf…
type: Question
upvote count: 2
tagged with: theano
has title: lazylinker_c import Error Theano
tagged with: python
type: UnansweredQuestion
tagged with: ubuntu
answer count: 1
has answer: http://stackoverflow.com/a/50236279
score: 2
tagged with: amazon-ec2
downvote count: 0
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/comment/85312185
type: Comment
has text: To one of those questions: Same reason `2.5 - 1.5` is a float, and not an int. Result is always the more complex type of the involved operands. In the case of `2**63 - 2**62` or any calculation invloving `int` and `long` the resulting type will be `long`
type: QuestionComment
comment on: http://stackoverflow.com/q/49153714
score: 5

http://stackoverflow.com/a/49174414
type: Answer
upvote count: 1
score: 1
has body: Slightly more bloated code than the early answers, but also slightly more readable: from collections import defaultdict list_of_words = ['deltas', 'retainers', 'desalt', 'pants', 'slated', 'generating', 'ternaries', 'smelters', 'termless', 'salted', 'staled', 'greatening', 'lasted', 'resmelts'] def getAnagrams(source): d = defaultdict(list) for word in source: key = "".join(sorted(word)) d[key].append(word) return d anagrams = getAnagrams(list_of_words) separated_list = list(anagrams.values())
answers question: http://stackoverflow.com/q/49173955
downvote count: 0

http://stackoverflow.com/comment/85496929
type: Comment
comment on: http://stackoverflow.com/q/49246354
type: QuestionComment
score: 0
has text: If you remove `b+` wouldn't it give desired output?

http://stackoverflow.com/comment/85266309
score: 0
type: QuestionComment
has text: I would like two integer values corresponding to the unique values of the index.
type: Comment
comment on: http://stackoverflow.com/q/49130834

http://stackoverflow.com/q/49185032
has answer: http://stackoverflow.com/a/49185162
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/49185162
tagged with: python
has answer: http://stackoverflow.com/a/49185158
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has title: Creating a column based on multiple conditions
downvote count: 0
tagged with: nested
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49185158
has body: I'm a longtime SAS user trying to get into Pandas. I'd like to set a column's value based on a variety of if conditions. I think I can do it using nested np.where commands but thought I'd check if there's a more elegant solution. For instance, if I set a left bound and right bound, and want to return a column of string values for if x is left, middle, or right of these boundaries, what is the best way to do it? Basically if x &lt; lbound return "left", else if lbound &lt; x &lt; rbound return "middle", else if x > rbound return "right". df lbound rbound x 0 -1 1 0 1 5 7 1 2 0 1 2 Can check for one condition by using np.where: df['area'] = np.where(df['x']&gt;df['rbound'],'right','somewhere else') But not sure what to do it I want to check multiple if-else ifs in a single line. Output should be: df lbound rbound x area 0 -1 1 0 middle 1 5 7 1 left 2 0 1 2 right
score: 5
upvote count: 5

http://stackoverflow.com/comment/85450093
comment on: http://stackoverflow.com/a/49194458
type: Comment
type: AnswerComment
has text: @mikuszefski I solved the issue with the transforms. I also added another solution which would update itself through callbacks, such that in both solutions new plots can be added and the plot can be zoomed etc.
score: 0

http://stackoverflow.com/q/49219335
has body: Question: How would I create code that basically compares the first number of each set with a given value? Code: I currently have this code: for pair in MAXTABLE distance, speed = pair if distance &gt; control_dist_km: time =+ control_dist_km / speed hour , min = divmod(time, 1) #seperate hours and min min = ((time%1)*60) #convert from decimal to minutes utc.shift(hour =+ hour, minute =+ min) #add hours and mi However the compiler says: "invalid syntax@ for pair in MAXTABLE (defined outside of function as maxTable > = [(1300,26), (1000,28), (600, 30), (400, 32), (200, 34)] )."
has comment: http://stackoverflow.com/comment/85442354
tagged with: data-structures
answer count: 1
type: Question
tagged with: python
type: UnansweredQuestion
has title: Need a table for pairs of ints in python (data structure help, possibly arrays)
tagged with: for-loop
score: 0
tagged with: arrays
has answer: http://stackoverflow.com/a/49219358

http://stackoverflow.com/q/49210445
answer count: 2
has body: How do I create a loop for naming label widget. I do not know how to set the widget name as a variable. from tkinter import * def dofunc(): v1.set("one") v2.set("two") v3.set("three") widget4.config(text="four") v1=StringVar() widget1=Label(root,width=10,textvariable=v1) widget1.pack() v2=StringVar() widget2=Label(root,width=10,textvariable=v2) widget2.pack() v3=StringVar() widget3=Label(root,width=10,textvariable=v3) widget3.pack() widget4=Label(root,width=10) widget4.pack() root.geometry("+50+50") root.after(500, dofunc) root.mainloop()
tagged with: python
has answer: http://stackoverflow.com/a/49215887
has comment: http://stackoverflow.com/comment/85435189
has comment: http://stackoverflow.com/comment/85426989
score: -1
accepted answer: http://stackoverflow.com/a/49210532
has title: Loop for setting a tkinter widget name
tagged with: tkinter
has answer: http://stackoverflow.com/a/49210532
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49215887
downvote count: 1
favorite count: 0
tagged with: python-3.x
type: Question
upvote count: 0

http://stackoverflow.com/comment/85366848
comment on: http://stackoverflow.com/a/49180630
type: Comment
type: AnswerComment
has text: I might be misunderstanding -- which executable?
score: 0

http://stackoverflow.com/q/49210719
linked to: http://stackoverflow.com/q/67631
tagged with: python-import
has comment: http://stackoverflow.com/comment/85425955
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85426747
linked to: http://stackoverflow.com/q/44268763
has comment: http://stackoverflow.com/comment/85426104
score: 1
has title: Python import folder never imports
has answer: http://stackoverflow.com/a/49210891
linked to: http://stackoverflow.com/q/25997185
tagged with: python
has comment: http://stackoverflow.com/comment/85426011
favorite count: 0
type: Question
has body: I am trying to import this library - https://github.com/abenassi/Google-Search-API I tried 1. Can not import module search from google module in python 2. Python / ImportError: Import by filename is not supported 3. How to import a module given the full path? I still can't import Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'google' is not defined even locally &gt;&gt;&gt; import imp &gt;&gt;&gt; google = imp.load_source('google', '/home/arjun/.local/lib/python2.7/site-packages/google/__init__.py') &gt;&gt;&gt; num_page = 3 &gt;&gt;&gt; search_results = google.search("This is my query", num_page) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'search' &gt;&gt;&gt; google &lt;module 'google' from '/home/arjun/.local/lib/python2.7/site-packages/google/__init__.pyc'&gt;

http://stackoverflow.com/comment/85453765
has text: I made some changes to the code, and I get the following exception now: Exception Value: '_TaggableManager' object is not iterable
type: AnswerComment
comment on: http://stackoverflow.com/a/49224874
score: 0
type: Comment

http://stackoverflow.com/a/49243865
downvote count: 0
has comment: http://stackoverflow.com/comment/109719854
has comment: http://stackoverflow.com/comment/85493223
answers question: http://stackoverflow.com/q/49243736
has comment: http://stackoverflow.com/comment/109719922
accepted answer of: http://stackoverflow.com/q/49243736
has comment: http://stackoverflow.com/comment/85492150
score: 10
has comment: http://stackoverflow.com/comment/85512598
upvote count: 10
type: Answer
has body: The Sheets API doesn't know what to do with a Python datetime/timestamp. You'll need to convert it - most likely to a str. For converting a pandas Series use pd.Series.dt.strftime() If it's just for a single value that needs to be converted then use datetime's strftime() Edit to answer your question in the comments: # To convert a datetime column to a str. df['date_column'] = df['date_column'].dt.strftime('%Y%m%d%H%M%S') To give a bit more info, strftime means "string format datetime". This allows you to format your datetime/timestamp value into a str. The '%Y%m%d%H%M%S' is what you want the output the be. In my example, the results would be "20180309152303" for your date. Another example would be '%m/%d/%Y %H:%M:%S' which would give you "03/09/2018 15:23:03". So replace 'date_column' in my example with the name of your date column and it'll be converted to a str that's compatible with the API as well as understood format-wise in Google Sheets.
has comment: http://stackoverflow.com/comment/85523791
type: AcceptedAnswer

http://stackoverflow.com/q/49168564
tagged with: python
has answer: http://stackoverflow.com/a/49172705
score: 0
tagged with: hybrid-mobile-app
answer count: 1
has body: I am writing automation testing for my hybrid android app created with ionic framework. But during running testing I am unable to start app using its activity. Here is error selenium.common.exceptions.WebDriverException: Message: An unknown server-side error occurred while processing the command. Original error: Error occured while starting App. Original error: Activity used to start app doesn't exist or cannot be launched! Make sure it exists and is a launchable activity Here is my desired capabilities code ........ class TestLoginLogout(unittest.TestCase): @classmethod def setUpClass(self): desired_caps = {} desired_caps['platformName'] = 'Android' desired_caps['platformVersion'] = '7.0' desired_caps['deviceName'] = 'ZY223XQMWZ' desired_caps['app'] = PATH('/home/martial/DYFO/dyfo.apk') desired_caps['appPackage'] = 'dyfolabs.automatioo' desired_caps['appActivity'] = "dyfolabs.automation.MainActivity" desired_caps['context'] = 'WEBVIEW' desired_caps['noReset'] = 'true' desired_caps['fullReset'] = 'false' self.driver = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps) Please help me I am stuck here. Thanks in advance..
has title: Automating hybrid app (android) with appium using python
type: Question
tagged with: automation
tagged with: appium
type: UnansweredQuestion

http://stackoverflow.com/q/49214241
type: AnsweredQuestion
score: 0
tagged with: foreign-keys
has title: Django Foreign key that could contain objects of different classes
has answer: http://stackoverflow.com/a/49215070
tagged with: django-models
type: Question
answer count: 1
tagged with: django
tagged with: python
has body: is there a way to be able to use a foreign key to reference objects of diffrent classes for example, this is what i'm doing : Class discussion(models.Model): id_discussion = models.CharField(db_column='id_Discussion', primary_key=True, max_length=100) id_worker = models.ForeignKey('Worker', models.CASCADE, db_column='id_user', blank=True, null=True) id_director = models.ForeignKey('Director', models.CASCADE, db_column='id_user', blank=True, null=True) Class Message(models.Model): #some other fields id_sender = models.CharField(db_column='id_Sender', max_length=100, blank=True, null=True) id_receiver = models.CharField(db_column='id_Receiver', max_length=100, blank=True, null=True) id_discussion = models.ForeignKey('discussion', models.CASCADE, db_column='id_Discussion', blank=True, null=True) I want to turn id_receiver and id_sender into foreign keys, my problem is that the sender could be an object of class "Worker" or of class "Director".
accepted answer: http://stackoverflow.com/a/49215070
tagged with: class

http://stackoverflow.com/comment/85450567
comment on: http://stackoverflow.com/q/49211358
type: Comment
score: 0
type: QuestionComment
has text: @hikerjobs the green or red light doesn't turn on after i press the button completing the reaction game

http://stackoverflow.com/comment/85519550
comment on: http://stackoverflow.com/q/49258019
type: Comment
type: QuestionComment
has text: Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackexchange.com/q/156810/204922). You might also want to learn about [Minimal, Complete, and Verifiable Examples](http://stackoverflow.com/help/mcve).
score: 0

http://stackoverflow.com/comment/85563846
has text: Thank you so much!
comment on: http://stackoverflow.com/a/49270114
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49140984
answers question: http://stackoverflow.com/q/49140878
score: 0
has body: Use if and elif statements. the correct usage for if statements is if then: elif you can have as many elif as you like ... then last, if nothing matches. else you can use either int or 'float` depending on the type of number to take in the user input, otherwise it will return a string. int is a whole number ie 1, 2, 3 and float can take in a decimal ie 1.5, 2.3, 3.5 for this answer i have used float. price = float(input('How much did your taxi ride cost?:')) if price &lt; 45: print('Processing') elif price &gt; 45: response = ('Your taxi cost over $45 you will be charged a $5.00 fee') print(response) response = input('Would you like to proceed:') if response == 'yes': print('Processing...') elif response == 'no': print('!Error!')
type: Answer

http://stackoverflow.com/q/49218181
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/85440216
tagged with: duplicates
tagged with: python
accepted answer: http://stackoverflow.com/a/49228149
favorite count: 0
type: Question
has body: After reading mostly all the questions related to pair duplicates, no question address the following issue: Given a Df: Letter 0 a 1 b 2 c 3 d 4 a 5 b 6 a 7 a 8 a Eliminate only pairs of duplicates. For example: as the Df have 5 a's, the solution is to eliminate the first two set of pairs of a's and leave the last a (order is important). The two b's are just eliminated because they are a set of pairs. The resulting Df would look like this: Letter 2 c 3 d 8 a I hope it was clear the issue. Thanks!
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85441600
upvote count: 1
score: 1
has title: How to eliminate just pair duplicates in a Pandas Dataframe?
has comment: http://stackoverflow.com/comment/85448979
has answer: http://stackoverflow.com/a/49228149

http://stackoverflow.com/a/49175554
answers question: http://stackoverflow.com/q/49175373
downvote count: 0
has body: This is possible with a list comprehension: my_dict = {'a':['e','f'],'b':['g'],'c':[]} res = [(k, w) for k, v in my_dict.items() for w in v] # [('a', 'e'), ('a', 'f'), ('b', 'g')] For academic purposes here is a slightly different algorithm: from itertools import zip_longest my_dict = {'a':['e','f'],'b':['g'],'c':[]} res = [(i, j) for k, v in my_dict.items() for i, j in zip_longest(k, v, fillvalue=k) if v] # [('a', 'e'), ('a', 'f'), ('b', 'g')]
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/q/49204505
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49204510
has body: I would like to open a new file like this: new_path = '/Users\KamilaLipman\Documents\Coding\PyCharm\venv\Learning_Python\Learning~Input+Output\the_week.txt' more_days = open(new_path, 'w') But the \n, \v and \t gets interpreted as escape codes. Because of this I get an error saying that the file does not exist: C:\Users\KamilaLipman\Documents\Coding\PyCharm\venv\Scripts\python.exe: can't open file 'C:/Users/KamilaLipman/Documents/Coding/PyCharm/PythonLearning.py': [Errno 2] No such file or directory How could I fix this without changing my file names? Could I use a forward slash(/)? (I am new to Python so sorry if this is a very easy problem)
has comment: http://stackoverflow.com/comment/85414508
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
has title: How to stop a '\n' or '\t' from working in a string?
downvote count: 0
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49204510

http://stackoverflow.com/q/49227337
has answer: http://stackoverflow.com/a/49227426
type: AnsweredQuestion
score: 2
tagged with: list
has answer: http://stackoverflow.com/a/49227380
has answer: http://stackoverflow.com/a/49227385
downvote count: 0
has title: Assigning values into dictionary from a list
tagged with: key
favorite count: 0
accepted answer: http://stackoverflow.com/a/49227380
type: Question
has answer: http://stackoverflow.com/a/49228583
has body: I want to create a dictionary that stores the full name of the 50 states in the word, and the abbreviations in the value, given a list of the names and abbreviations. I am expecting a dictionary like {'Alabama' : 'AK', 'Alaska': 'AL', ...}. I've tried state_to_abbrev = {} for word in states: for i in range(50): state_to_abbrev[word] = states[i] state_to_abbrev[word] = abbreviations[i] state_to_abbrev And I'm getting {'Alabama': 'WY', 'Alaska': 'WY', 'Arizona': 'WY', 'Arkansas': 'WY', 'California': 'WY', 'Colorado': 'WY', 'Connecticut': 'WY', 'Delaware': 'WY', 'Florida': 'WY', 'Georgia': 'WY', 'Hawaii': 'WY', .....}
has comment: http://stackoverflow.com/comment/85458483
has answer: http://stackoverflow.com/a/49227427
has comment: http://stackoverflow.com/comment/85458402
upvote count: 2
answer count: 5
possible better answer: http://stackoverflow.com/a/49227385
tagged with: python
tagged with: dictionary

http://stackoverflow.com/a/49168865
has comment: http://stackoverflow.com/comment/85343043
type: AcceptedAnswer
downvote count: 0
score: 19
has comment: http://stackoverflow.com/comment/85343222
upvote count: 19
has comment: http://stackoverflow.com/comment/85343909
answers question: http://stackoverflow.com/q/49168762
type: Answer
accepted answer of: http://stackoverflow.com/q/49168762
has comment: http://stackoverflow.com/comment/85343149
has body: You can use star unpacking to gather all additional return values into a list: x, *y = fun() x will contain the first return value. y will be a list of the remaining values. y will be empty if there is only one return value. This particular example will only work if the function returns a tuple, even if there is only one value. When fun always returns 1 or 2 values, you can just do if y: print(y[0]) else: print('only one value') If, on the other hand, you want to completely ignore the number of return values, do *x = fun() Now all the arguments will be gathered into the list. You can then print it with either print(x) or print(*x) The latter will pass each element as a separate argument, exactly as if you did x, y, z = fun() print(x, y, z) The reason to use *x = fun() instead of just x = fun() is to get an error immediately when a function returns something that isn't a tuple. Think of it as an assertion to remind you to write fun properly. Since this form of star unpacking only works in Python 3, your only option in Python 2 is to do x = fun() and to inspect the result manually.
has comment: http://stackoverflow.com/comment/85342775

http://stackoverflow.com/q/49187943
linked to: http://stackoverflow.com/q/24127601
score: 3
upvote count: 3
has title: python flask response using jsonify
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/85382119
has comment: http://stackoverflow.com/comment/85382034
favorite count: 0
has comment: http://stackoverflow.com/comment/85381319
type: Question
type: UnansweredQuestion
answer count: 1
has body: Two applications built with flask API, trying to receive a response with huge JSON response fails with Error 10054, 'An existing connection was forcibly closed by the remote host' I could narrow the issue that when response is huge it fails @api.route('/endpoint', methods=['POST']) def endpoint(): result = {small / huge dict} return jsonify({'result': result}), 200 caller side: result = requests.post(url, params=data['args'], json=data['payload']) return result.json()['result'] Error log: File "C:\Program Files (x86)\Python36-32\lib\http\client.py", line 1331, in getresponse response.begin() File "C:\Program Files (x86)\Python36-32\lib\http\client.py", line 321, in begin self.headers = self.msg = parse_headers(self.fp) File "C:\Program Files (x86)\Python36-32\lib\http\client.py", line 206, in parse_headers line = fp.readline(_MAXLINE + 1) File "C:\Program Files (x86)\Python36-32\lib\socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host Update: tried to yield response as plan text and failures where much less, but still once in a while the issue appears. def response(output): return Response(response_generator(output), mimetype='text/plain') def response_generator(result): result_str = json.dumps(result) for row in [result_str[i:i + 1024*1024] for i in range(0, len(result_str), 1024*1024)]: yield row
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49188438
tagged with: flask

http://stackoverflow.com/comment/85534653
comment on: http://stackoverflow.com/q/49265404
has text: This is not the place to give you a tutorial on data frames. Once you're familiar with the concept, I suggest that you convert these dicts to data frames. The present keys become your column headings. Simple filters will allow you to access corresponding data as needed, or to import that data into a new column.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85418378
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49206672
type: Comment
has text: Possible duplicate of [How to create an HTML button that acts like a link?](https://stackoverflow.com/questions/2906582/how-to-create-an-html-button-that-acts-like-a-link)

http://stackoverflow.com/q/49239270
downvote count: 0
has answer: http://stackoverflow.com/a/49241695
favorite count: 0
has title: Select between values in 2 columns based on a conditional in third column in pandas
type: Question
has body: How do I select between 2 columns based on a conditional in third column using pandas ? In excel I would use something like : NEW_COLUMN = IF (CONDITION == TRUE , COLUMN 1 , COLUMN 2). I am not able to use lambda function.
upvote count: 2
tagged with: if-statement
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49239306
tagged with: python
tagged with: lambda
answer count: 3
tagged with: pandas
score: 2
has answer: http://stackoverflow.com/a/49239601

http://stackoverflow.com/comment/85547784
type: Comment
has text: true!, I'm sorry.
comment on: http://stackoverflow.com/a/49272409
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85478403
has text: That's my question!
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49237498

http://stackoverflow.com/a/49176398
type: Answer
has comment: http://stackoverflow.com/comment/85358183
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/49176095
upvote count: 1
has body: The comports() method return ListPortInfo object. Then, you can access a bunch of attributes of this class to get the desired results: name: Short device name, e.g. ttyUSB0 device: Full device name/path, e.g. /dev/ttyUSB0 See the docs. An general solution for this, could be: from serial.tools.list_ports import comports ports = [p.name for p in comports()] print(ports)
has comment: http://stackoverflow.com/comment/85358129

http://stackoverflow.com/comment/85441824
has text: @jason there's no hard-coded date here... it's just generating example data... as long as your date column has your required date in it - it doesn't matter...
type: Comment
comment on: http://stackoverflow.com/a/49219028
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85653082
comment on: http://stackoverflow.com/a/49227659
score: 0
has text: One of the best answers I've ever received on SO. Thank you!
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85449231
has text: Thanks for the input. Just a point to clarify: Isn't using `exec_results['x']` in the 3rd solution just as cumbersome as using `locals`? I unfortunately also am not knowledgeable enough to clearly grasp the difference between the two.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49221715
type: Comment

http://stackoverflow.com/comment/85326144
comment on: http://stackoverflow.com/q/49160081
score: 0
type: Comment
type: QuestionComment
has text: In Python, proper indentation is necessary to execute code, the indentation in this code needs to be fixed so the code runs before we can provide any help

http://stackoverflow.com/q/49205526
has comment: http://stackoverflow.com/comment/85416464
has comment: http://stackoverflow.com/comment/85416348
has comment: http://stackoverflow.com/comment/85416351
score: 2
has answer: http://stackoverflow.com/a/49205849
tagged with: pandas
has body: start = pd.to_datetime("2017-02-21 22:32:41",infer_datetime_format=True) end = pd.to_datetime("2017-02-22 01:32:41",infer_datetime_format=True) rng = pd.date_range(start.floor('h'), end.floor('h'), freq='h') left = pd.Series(rng, index=rng ).clip_lower(start) right = pd.Series(rng + 1, index=rng).clip_upper(end) s = right - left I get result as 2017-02-21 22:00:00 00:27:19 2017-02-21 23:00:00 01:00:00 2017-02-22 00:00:00 01:00:00 2017-02-22 01:00:00 00:32:41 I want to convert the result pandas.Series to dataframe to make my result shown below id |hour|day|minute| +-----+----+---+------+ |10001| 22|Wed| 27| |10001| 23|Thu| 60| |10001| 00|Thu| 60| |10001| 01|Thu| 32| Any direct conversion option or should I have to loop through it ?
tagged with: python
has title: Converting Pandas Series into Dataframe customized values
favorite count: 0
has comment: http://stackoverflow.com/comment/85416705
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49206281
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85416711
downvote count: 0

http://stackoverflow.com/q/49223493
tagged with: excel
has answer: http://stackoverflow.com/a/49225433
tagged with: xlrd
has comment: http://stackoverflow.com/comment/85463720
answer count: 1
tagged with: vba
has body: HI I am new managing excel files, I would like to know if there is any variable in xlutils, xlrd, xlm, etc libraries that give true or false in case Macros are activated or now? Is there any way to know it from metadata before open? Wat is the best approach for know it? Thanks a lot in advance.
score: 1
favorite count: 0
type: Question
has title: How to know if excel file has macros using python?
upvote count: 2
type: UnansweredQuestion
tagged with: openpyxl
tagged with: python
downvote count: 1

http://stackoverflow.com/q/49221839
type: Question
has answer: http://stackoverflow.com/a/49229356
type: UnansweredQuestion
tagged with: python
has body: QUESTION How can I determine how to decode stream video data with unknown properties? PROBLEM: For weeks I've been trying to get my camera (HC-V770) to stream to YouTube. After a lot of wireshark and determining the camera's abilities I managed to have the camera send video data to my computer. It comes in the form of UDP data but I can't seem to figure out what that data actually is. The camera will start sending UDP this stream data to requester's device on a specified port after sending it an HTTP request. eg: calling http://CAMERAIP/cam.cgi?mode=startstream&amp;value=49152 will cause the camera to send video data to my device on port 49152 ATTEMPTED SOLUTIONS: VLC won't detect it. using udp://@0.0.0.0:49152 it detects some incoming data but it doesn't seem to know what to do with it. I've found this script (shown below &amp; slightly modified), which supposedly works for other/older Panasonic cameras but not this one. The script displays a black window and is responsive to "some incoming data" but doesn't seem to know what to do with it. It will also stop functioning when the data stream stops, confirming that it is in fact picking up something ## the following also needs to be updated. figure it out on your own. MY_IP = "192.168.0.149" ## THIS IS YOUR LOCAL IP ADDRESS THEIR_IP = "192.168.0.163" ## THIS IS THE IP ADDRESS OF THE CAMERA RTMP_OUT = "rtmp://a.rtmp.youtube.com/live2/KEYHERE import gi gi.require_version('Gst', '1.0') from gi.repository import GObject, Gst import numpy as np import socket import cv2 import binascii import threading import time import sys ## HHTP req's dont work for dick #do this to start stram #http://192.168.0.163/cam.cgi?mode=startstream&amp;value=49152 #do this to refresh &amp; check status #http://192.168.0.163/cam.cgi?mode=getstate # then run progrem GObject.threads_init() Gst.init(None) UDP_PORT = 49152 start = binascii.unhexlify(''.join('FF D8'.split())) end = binascii.unhexlify(''.join('FF D9'.split())) sock = socket.socket(soc…
has title: Determine format of incoming video stream
tagged with: gstreamer
score: 0
tagged with: udp
tagged with: stream
answer count: 1
tagged with: wireshark

http://stackoverflow.com/q/49160456
score: 0
has answer: http://stackoverflow.com/a/49160487
has title: What itertools returns i.e. powerSet
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/5176232
type: Question
has comment: http://stackoverflow.com/comment/85326459
linked to: http://stackoverflow.com/q/5176232
tagged with: python-itertools
type: UnansweredQuestion
has body: import itertools def powerSet(items): ''' items : a list returns all possible combinations of the items ''' return itertools.chain.from_iterable(itertools.combinations(items,r) for r in range(len(items)+1)) items = [1,2,3] If I try print(powerSet(items)) it returns &lt;itertools.chain object at 0x113e43588&gt; but if I try print(list(powerSet(items))) it gives me the list of all subsets. Why is that?
tagged with: python
has comment: http://stackoverflow.com/comment/85326368
tagged with: powerset

http://stackoverflow.com/comment/85354477
type: AnswerComment
has text: but `wrapper` still calls `fun`, doesn't it? also, why would `x = name("jeff")(f)` work but not `f = name("jeff")(f)`, i replace `fun` in both cases
comment on: http://stackoverflow.com/a/49174722
type: Comment
score: 0

http://stackoverflow.com/q/49213383
type: Question
tagged with: python
has body: I'm using the python-levenshtein module to analyse Irish language text over a large period of time; over time there are a number of orthographic changes to text e.g. bí -> ḃí -> bhí, the diacritic over the 'b' and the 'h' following the b both represent the same grammatical form of lenition (which is unshown in the first period). Between all these forms I would want a fairly low distance, but using the python-levenshtein distance as it is gives the same distance between Levenshtein.ratio(u'ḃí', u'bí') = 0.5 and Levenshtein.ratio(u'xí', u'bí') = 0.5, obviously a minor orthographic change to the character 'b' and it's outright substitution with 'x' (a foreign borrowing to boot) shouldn't have the same score. So is there a way to modify the values of specific characacter changes e.g. reduce the distance of bí to ḃí but up the distance between bí and xí? Or will I need to produce my own implementation?
type: AnsweredQuestion
has title: Customising python-levenshtein character values
answer count: 1
accepted answer: http://stackoverflow.com/a/49213542
downvote count: 0
score: 1
upvote count: 1
tagged with: levenshtein-distance
has answer: http://stackoverflow.com/a/49213542
favorite count: 0

http://stackoverflow.com/a/49158693
answers question: http://stackoverflow.com/q/49158646
score: 8
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49158646
type: AcceptedAnswer
upvote count: 8
has body: Generally in Python, double-underscore methods should not be called directly; you should use the global functions or operators that correspond to them. In this case, you would do if 'FOO' in i.
has comment: http://stackoverflow.com/comment/85324306
type: Answer

http://stackoverflow.com/q/49260118
tagged with: pyscard
tagged with: python
accepted answer: http://stackoverflow.com/a/49268820
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49268820
score: 1
answer count: 1
tagged with: usb
has body: I'm capturing USB traffic using Wireshark on a smart card reader. When I connect to the reader using PyScard, some packets are sent back and forth using bulk operations before I send any APDU just by establishing the connection. I have read here that there is an initial handshake between a USB device and the host and I wonder if that is what I see while sniffing. Using wireshark, I get the following: Bulk out (host to device): Bulk out (device to host): Bulk in (host to device): Bulk in (device to host): These four packets are sent 2-3 times and then I can sniff the messages I send using PyScard. My goal here is to reproduce the communication between the reader and the host by using only USB communications. So: Is there an initial handshake in USB communications? Is that what I'm capturing? How can I reproduce this USB communications? Thanks <3 Edit 14/03/2018 - Additional information following David Grayson's answer What I am capturing here is not the part of "Get Device Descriptor", etc. This happens when I try to print the device's details and Wireshark recognises and labels the packets as so. I'm aware of the weird operations but it is what I'm getting from wireshark. The interpretation I've been doing is that they're request-response pairs: the host sends something using bulk out endpoint and then asks to read the answer by using bulk in endpoint when it is ready to do so. I have absolutely no idea, it's just what it looks to me. >> lsusb -v Bus 001 Device 002: ID 0bda:0165 Realtek Semiconductor Corp. Couldn't open device, some information will be missing Device Descriptor: bLength bDescriptorType 1 bcdUSB 2.00 bDeviceClass 0 (Defined at Interface level) bDeviceSubClass 0 bDeviceProtocol 0 bMaxPacketSize0 64 idVendor 0x0bda Realtek Semiconductor Corp. idProduct 0x0165 bcdDevice 61.23 iManufacturer 1 iProduct 6 iSerial 3 bNumConfigurations 1 Configuration Descriptor: bLength 9 bDescriptorType 2 wTotalLength 93 bNumInterfaces 1 bConfigurationValue 1 iConfiguratio…
has title: USB - Is there an initial handshake between host and device?
tagged with: pyusb
downvote count: 1
tagged with: wireshark
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/85476161
type: AnswerComment
has text: Thank you and nice explanation.
type: Comment
comment on: http://stackoverflow.com/a/49236119
score: 0

http://stackoverflow.com/a/49231744
answers question: http://stackoverflow.com/q/49231589
has comment: http://stackoverflow.com/comment/85489623
score: 3
type: Answer
has body: sleep will mark the process (thread) for being inactive until the given time is up. During this time the kernel will simply not schedule this process (thread). It will not waste resources. Hard disks typically have spin-down policies based solely on their usage. If they aren't accessed for a specific time, they will spin down. They will spin up as soon as some process (thread) is accessing them again. This means that letting a process (thread) sleep for some time gives the hard disk a chance to spin down (especially if the sleep duration is large, say, more than some minutes).
upvote count: 3
downvote count: 0

http://stackoverflow.com/a/49276056
type: Answer
answers question: http://stackoverflow.com/q/49260442
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
has body: Well It was an additional change to the configuration in Flower and I changed the approach a bit! The required config property was db I updated the service to /etc/systemd/system/flower.service [Unit] Description=Flower Celery Service [Service] User=vagrant Group=vagrant WorkingDirectory=/home/vagrant/ ExecStart=/usr/bin/flower --/var/log/supervisord.log Restart=on-failure Type=simple [Install] WantedBy=multi-user.target /home/vagrant/flowerconfig.py port = 5000 broker = 'redis://:&lt;password&gt;@192.168.100.20:6379/0' broker_api = 'redis://:&lt;password&gt;@192.168.100.20:6379/0' basic_auth = ['sun:flower'] persistent = True db = '/home/vagrant/flower.db' After providing the db property, it was all fine. Except for one issue.. the Flower Dashboard was not showing data but the Tasks page was loading the tasks list prior to the refresh! Learnt from http://flower.readthedocs.io/en/latest/config.html#db A database file to use if persistent mode is enabled (by default, db=flower) I've submitted the same as issue / observation in flower -- https://github.com/mher/flower/issues/787 Hope this helps to other facing similar issue!!
accepted answer of: http://stackoverflow.com/q/49260442

http://stackoverflow.com/comment/85289890
type: Comment
comment on: http://stackoverflow.com/a/49142069
type: AnswerComment
has text: Just a thought, what if the api was `def a(x, _)` and `def b(x, y)` (obviously meaning `a` ignores `y`). Wouldn't that be so much nicer? :)
score: 0

http://stackoverflow.com/comment/85376639
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49185065
has text: His question like how to use `2dsphere` index with pymongo not how to save `2dsphere` with pymongo.

http://stackoverflow.com/q/49273261
score: -3
tagged with: python
has body: my question is, how I can write data to an existing Excel-Worksheet using Python. I've tried a few ways so far, but nothing worked out, yet. For example it would be enough to have like 3 columns were I want add data to the 1st and the 3rd column in that specific empty row. That's one try to simply write to an existing file so far: from openpyxl import Workbook wb = Workbook("example.xlsx") ws = wb.active ws["A4"] = 5
has title: How to write into an existing Excel-Worksheet to the first empty row with python
tagged with: excel
accepted answer: http://stackoverflow.com/a/49273514
downvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85561233
has answer: http://stackoverflow.com/a/49273514
has comment: http://stackoverflow.com/comment/85549164
upvote count: 3
has comment: http://stackoverflow.com/comment/85549217
tagged with: openpyxl
answer count: 1
has comment: http://stackoverflow.com/comment/85549173
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85549098

http://stackoverflow.com/q/49236464
type: Question
has comment: http://stackoverflow.com/comment/85476341
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49236633
tagged with: missing-data
upvote count: 1
tagged with: dataframe
tagged with: python
has title: Python Pandas fillna()
has comment: http://stackoverflow.com/comment/85476511
has body: I have a large dataframe with values like: Name A B C D E F G # Coulmns Matt 1 n n n 5 n 5 # rows Jake n n 2 n 3 n n Paul 2 n 3 n n 8 n I just want to fill NA values with preceding values: This is achieved by df.fillna(method='ffill') This is forward fill method which gives me an output of: Name A B C D E F G # Coulmns Matt 1 1 1 1 5 5 5 # rows Jake n n 2 2 3 3 3 Paul 2 2 3 3 3 8 8 The problem is that i don't want it to go till end, just stop if there are no more values in the back. See Row 2, Jake it must stop at E since it doesn't have any value in the last column. Desired output: Name A B C D E F G # Coulmns Matt 1 1 1 1 5 5 5 # rows Jake n n 2 2 3 n n Paul 2 2 3 3 8 8 n Is there anyway to do this with pandas? Code: for i in range(len(df)): df.loc[i][1:].fillna(method='ffill',inplace=True)
type: AnsweredQuestion
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/49236633
favorite count: 0

http://stackoverflow.com/a/49182403
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49180476
has comment: http://stackoverflow.com/comment/85405148
has body: Try this: print "End time: ", print datetime.datetime.now()
has comment: http://stackoverflow.com/comment/85405100

http://stackoverflow.com/q/49247204
tagged with: selenium-chromedriver
answer count: 0
score: 1
downvote count: 0
tagged with: selenium
upvote count: 1
has comment: http://stackoverflow.com/comment/85498267
favorite count: 0
type: Question
has title: Selenium Python crashes when running on Ubuntu VPS
has body: Hi I have a script that scraps info from 11880.com. The script works perfectly when is executed in my computer but always crashes after a few records in a Digital Ocean droplet. Here are my computer specs: OS: macOS High Sierra Version 10.13.3 chromedriver 2.36 VPS specs: OS: Linux 4.4.0-112-generic chromedriver 2.36 Here's a screenshot of the error that the terminal outputs: By the way, I already have this in my chromedriver options (cause I've already googled a lot about the issue and found this to be a solution but did not work for me): chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument('--no-sandbox') driver = webdriver.Chrome("/root/Downloads/chromedriver", chrome_options=chrome_options)
tagged with: vps
type: UnansweredQuestion
tagged with: python
tagged with: ubuntu

http://stackoverflow.com/comment/85277393
comment on: http://stackoverflow.com/a/49136036
score: 0
type: Comment
type: AnswerComment
has text: Add some code to make your suggestion as an answer.

http://stackoverflow.com/comment/85478230
score: 0
has text: Yes, it's installed. But a few minutes ago my admin upgrade pandas to 0.22 and still remain the same.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49234026

http://stackoverflow.com/comment/85639880
comment on: http://stackoverflow.com/a/49259698
type: AnswerComment
score: 0
has text: Not sure about that error. But I have corrected my previous post as I should have used 'or' (`|`) instead of 'and' (`&`) as there is no situation when values are `<68 & >72` so the returned `df` would always be empty. It should read: `df_OutOfRange=df[(df['Column']<68) | (df['Column']>72)]`. This runs on the dataframe you gave in your example.
type: Comment

http://stackoverflow.com/q/49131888
tagged with: urllib2
has comment: http://stackoverflow.com/comment/85268511
tagged with: python
has comment: http://stackoverflow.com/comment/85269261
has body: I am attemping to use Matplotlib and arcgisimage to download and plot an image using the arcgis REST API service. A snippet error I'm running into is below. I suspect I can't connect to this arcgis server, because I'm being blocked by the firewall at my organization. Typically when I want to download something, say using pip, I have to enter a proxy, i.e. proxy.**.gov:8080. How would I go about getting around this firewall? I've tested my code at home without a firewall, and the arcgisimage works fine, which is why I suspect it's a firewall issue. Thanks. /opt/antelope/python2.7.8/lib/python2.7/urllib2.pyc in do_open(self, http_class, req) 1182 except socket.error, err: # XXX what error? 1183 h.close() -&gt; 1184 raise URLError(err) 1185 else: 1186 try: URLError: &lt;urlopen error [Errno 110] Connection timed out&gt;
has comment: http://stackoverflow.com/comment/85269354
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85269108
score: 0
has title: URLError: <urlopen error [Errno 110] Connection timed out> Proxy Error
answer count: 1
has comment: http://stackoverflow.com/comment/85268664
accepted answer: http://stackoverflow.com/a/49132577
type: Question
has answer: http://stackoverflow.com/a/49132577
linked to: http://stackoverflow.com/q/3168171

http://stackoverflow.com/q/49245963
tagged with: numpy
possible better answer: http://stackoverflow.com/a/49246373
type: AnsweredQuestion
upvote count: 3
linked to: http://stackoverflow.com/q/10710328
answer count: 2
tagged with: arrays
downvote count: 0
has body: I need to compare if two numpy arrays are equal to a desired precision ignoring nan values. For example: a = [1,nan,3,nan] b = [1,0.2,3,4.1] Should pass the test. I have tried using numpy.all function but i understand that it expects two array identical and i need to have some tolerance because float values may differ a little. How can i achieve this?
favorite count: 0
duplicate of: http://stackoverflow.com/q/10710328
type: Question
has answer: http://stackoverflow.com/a/49246373
has answer: http://stackoverflow.com/a/49247453
score: 3
accepted answer: http://stackoverflow.com/a/49247453
tagged with: python
tagged with: comparison
has title: How to compare numpy arrays ignoring nans?

http://stackoverflow.com/comment/85487348
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49239463
has text: The colours are only black (0,0,0) or white (255,255,255)

http://stackoverflow.com/comment/85359157
type: QuestionComment
score: 0
has text: Im looking at this link: https://docs.python.org/3/tutorial/venv.html. I get how to create a virtual environment and add packages to it, but the official docs only show how to add one package at a time. It doesn't address the problem that I have here, where two packages need the same third package, only different versions of it...
comment on: http://stackoverflow.com/q/49176543
type: Comment

http://stackoverflow.com/comment/85370363
type: Comment
type: QuestionComment
has text: This is not valid python syntax. Can you please double-check that you copy-pasted your code exactly?
comment on: http://stackoverflow.com/q/49182304
score: 0

http://stackoverflow.com/q/49191954
has comment: http://stackoverflow.com/comment/85389208
favorite count: 0
has body: I am trying to scrap this website but having issues extracting the right values. The website is on the prices of Sliver, gold, palladium and platinum. http://www.lbma.org.uk/precious-metal-prices The html of the website is below. Gold Price AM: $ 1325.40 Updated: 08/03 10:31:00 PM: $ 1321.00 Updated: 08/03 15:02:00 I am interested to obtain the daily_gold_am_usd of 1325.40 and the daily_gold_pm_usd of 1321.00 from the html data structure below. However the code I attempted after consulting from past posts can't seems to return these values. #Import packages import pandas as pd import numpy as np import requests from bs4 import BeautifulSoup #define url and get html url = "http://www.lbma.org.uk/precious-metal-prices" r=requests.get(url) data=r.text soup = BeautifulSoup(data,"html.parser") #Find the object of interest gold_am_price = soup.find("span", {"id": "daily_gold_am_usd"}) Au_price_am = gold_am_price.text.strip() gold_pm_price = soup.find("span", {"id": "daily_gold_pm_usd"}) Au_price_pm = gold_pm_price.text.strip() Appreciate any help. Thanks guys.
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/49192327
accepted answer: http://stackoverflow.com/a/49192327
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: Question
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: Empty value from web scraping with python beautiful soup
tagged with: web-scraping
tagged with: python-requests

http://stackoverflow.com/a/68890654
score: 1
upvote count: 1
type: Answer
has body: There is a builtin utility function to convert an iterable of tensors into a tensor: torch.nn.utils.parameters_to_vector, then combine with torch.numel: torch.nn.utils.parameters_to_vector(model.parameters()).numel() Or shorter with a named import (from torch.nn.utils import parameters_to_vector): parameters_to_vector(model.parameters()).numel()
answers question: http://stackoverflow.com/q/49201236
downvote count: 0

http://stackoverflow.com/q/49271413
has title: uploading files via GUI and selenium in python
has comment: http://stackoverflow.com/comment/85559826
favorite count: 0
type: Question
tagged with: robotframework
answer count: 0
type: UnansweredQuestion
tagged with: selenium
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85557576
score: 0
has body: I'm having trouble uploading a file into a website. I've tried using the following code and it doesn't seem to be working. driver.find_element_by_xpath(x_path).send_keys(full/path/of/file) The next step would be to interact directly with the GUI below but I have no idea how to even begin doing so. Any help would be appreciated.
has comment: http://stackoverflow.com/comment/85549327
tagged with: python

http://stackoverflow.com/comment/85461389
type: Comment
score: 0
type: QuestionComment
has text: Also, it might help to give the intermediate values useful names instead of calling them all `steinhart`, and track the units for each step (maybe even with a real units-and-quantities library, but probably just comments are fine); then it'll be easier to verify that you're doing each step right (and, if you get stuck somewhere, easier for us to understand what the step you're stuck on is supposed to accomplish).
comment on: http://stackoverflow.com/q/49228676

http://stackoverflow.com/q/49222073
answer count: 1
has answer: http://stackoverflow.com/a/49224716
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python
type: AnsweredQuestion
score: 0
has title: How to call main-window method from a dialog
has body: I have the following dialog with my new keyword "stackoverflow": After pressing the "hinzufügen" button the following method is called: keywords = self.wort_neue_woerter.toPlainText() try: with open("files/schluesselwoerter.txt", 'r') as file: output = file.read() self.keywords += output except: print("Datei nicht gefunden") with open("files/schluesselwoerter.txt", 'w') as file: file.write(self.keywords) print("Ausgeführt") Every keyword is written in the "schlüsselwoerter.txt" file: The method from the first dialog uses this textfile to populate the ListWidget. with open('files/schluesselwoerter.txt', 'r') as file: output = file.read() output_list = output.split(',') for element in output_list: item = QtWidgets.QListWidgetItem(element.strip()) self.wort_uebersicht.addItem(item) I want to call the Dialog 1 method populate_listWidget right after pressing on the button in Dialog 2. How can i do this? Here is the full code: Main Class: import sys import main_window from PyQt5 import QtWidgets class GUI(QtWidgets.QMainWindow, main_window.Ui_MainWindow): def __init__(self): super().__init__() self.setupUi(self) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) gui = GUI() gui.show() sys.exit(app.exec_()) Main_Window: from PyQt5 import QtCore, QtGui, QtWidgets import dialog class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(800, 600) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget) self.horizontalLayout.setObjectName("horizontalLayout") self.listWidget = QtWidgets.QListWidget(self.centralwidget) self.listWidget.setObjectName("listWidget") self.horizontalLayout.addWidget(self.listWidget) self.main_insert_btn = QtWidgets.QPushButton(self.centralwidget) self.main_insert_btn.setObjectName("main_insert_btn") self.horizontalLayout.addWidget(self.main_insert_btn) MainWindow.setCentr…
accepted answer: http://stackoverflow.com/a/49224716
tagged with: pyqt

http://stackoverflow.com/comment/85477886
score: 0
comment on: http://stackoverflow.com/a/49236844
type: Comment
type: AnswerComment
has text: The code inside that loop calls `temp.add_edge` and `temp.remove_edge` (also `MineDeltaGraphletTransitionsFromDynamicNetwork` which is not included so I don't know what it does). Since `temp` is mutated (perhaps a lot) inside the `for u in range(0,n):` loops it doesn't seem obviously parallelizable. What happens if the iteration where `u=1` runs before the iteration where `u=0`? That can happen if you parallelize at this level without further refactoring. If you _know_ that is safe for your algorithm, great, you can do it. It doesn't look safe to me but I don't know the goal of this function.

http://stackoverflow.com/comment/85351005
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49172608
has text: Considering that you have no explicit loops in your code and that the documentation for `asarray` says *No copy is performed if the input is already an ndarray.*, I would think there is no faster way.
score: 1

http://stackoverflow.com/q/49194147
has comment: http://stackoverflow.com/comment/85393117
has answer: http://stackoverflow.com/a/49194433
downvote count: 1
possible better answer: http://stackoverflow.com/a/52553285
tagged with: click
favorite count: 0
type: Question
has body: I'm using the click module. pip install click This gives me red text import click click.secho('Error: This error is ...xx', fg='red') Now I want that only 'Error:' is shown in red. How can I do this using click.secho?
accepted answer: http://stackoverflow.com/a/55541231
upvote count: 12
has comment: http://stackoverflow.com/comment/85392958
tagged with: python
score: 11
has title: How to set only one word in a specific color using Click.secho
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52553285
answer count: 3
has comment: http://stackoverflow.com/comment/85393216
has answer: http://stackoverflow.com/a/55541231

http://stackoverflow.com/comment/85366220
comment on: http://stackoverflow.com/a/49180235
score: 0
type: AnswerComment
type: Comment
has text: @Tad if this is what you need , can you consider accept it ?

http://stackoverflow.com/comment/85313465
type: QuestionComment
comment on: http://stackoverflow.com/q/49152082
has text: @gal242 oh I see... my apologies, as well as coding I'm still fairly new to this site as well, I'll remember that in future!
score: 0
type: Comment

http://stackoverflow.com/q/49196780
downvote count: 0
has comment: http://stackoverflow.com/comment/85400327
has body: I'm trying to load a .csv of 4 GB of size with 125 Millions of rows and 5 types of data on my computer that have this feautures: CPU: Intel Core 2 Duo E7200 @ 2.53 GHz RAM: 8 GB DDR3 @ 1833 MHz HD:500 GB 7200 rpm OS: Ubuntu 16.04 When I run this code: import dask.dataframe as dd import numpy as np dtypes = {'item_nbr':'int32', 'store_nbr':'int8', 'onpromotion':'bool' } df_train = dd.read_csv('data/train.csv', dtype=dtypes, parse_dates=["date"], converters={'unit_sales': lambda u: np.log1p(float(u)) if float(u) &gt; 0 else 0}, usecols=[1, 2, 3, 4, 5]).compute() My PC just freeze and I need to restart it, Is there any solution to this problem? Thanks! Edition: Currently I'm trying to run: df_train.unit_sales.map_partitions(np.log1p).compute() And my PC still freezing, So,How Can I calculate the logaritm of all 125 Million of rows without freezing my PC? and, How do I check to see if it's safe to call compute?
has title: Dask load and apply funtion on read_csv
has comment: http://stackoverflow.com/comment/85398614
has answer: http://stackoverflow.com/a/49198136
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/85398507
has comment: http://stackoverflow.com/comment/85398945
tagged with: python
accepted answer: http://stackoverflow.com/a/49198136
has comment: http://stackoverflow.com/comment/85400782
favorite count: 0
type: Question
tagged with: dask
upvote count: 2
has comment: http://stackoverflow.com/comment/85399510
answer count: 1

http://stackoverflow.com/a/49213542
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49213383
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49213383
has body: Levenshtein algorithm ("edit distance") doesn't allow different distances between characters, but there's a generalization - the Needleman-Wunsch algorithm - that does. I'm not aware of a Python implementation, but would recommend to look for one before implementing your own - it's possible but non-trivial.
has comment: http://stackoverflow.com/comment/85574745
score: 1

http://stackoverflow.com/q/49190887
downvote count: 0
tagged with: scikit-learn
tagged with: parameter-passing
favorite count: 0
type: Question
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/27810855
tagged with: python
has title: passing arguments to featureUnion transformer_list
duplicate of: http://stackoverflow.com/q/27810855
score: 2
upvote count: 2
tagged with: pipeline
answer count: 0
has body: I am building a sklearn Pipeline including a FeatureUnion MyPip= Pipeline([ # other steps ('myunion', FeatureUnion( transformer_list=[ # Pipeline for pulling features from the post's subject line ('my_transform1', my_transform()), ('my_transform2', my_transform_alt()) ])) )), ]) Normally, I could inject parameters into my pipeline using: Params={} Params.update({'my_step__my_param_name':'my_param_value'}) MyPip.set_params(**Params) But how do I set the parametrs of the feature union transformer_list? I have tried Params.update({'transform1__my_param_name':'my_param_value'}) Params.update({'myunion__my_transform1__my_param_name':'my_param_value'}) Params.update({'myunion__transformer_list__my_transform1__my_param_name':'my_param_value'}) MyPip.set_params(**Params) but none of them worked.

http://stackoverflow.com/comment/85504258
has text: Hi! It can print out successfully, but after this, I need to write them into csv and it won't work in this case.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49250305
type: Comment

http://stackoverflow.com/comment/85564569
type: Comment
type: QuestionComment
has text: I edited the question to make it more clear. After I removed the GetData function and copied its body to main after initializations of all processes, I keep getting the same error but now at line 'w.start()'.
comment on: http://stackoverflow.com/q/49279366
score: 0

http://stackoverflow.com/comment/85403531
has text: OpenCV is really not the right tool for this kind of stuff...
type: Comment
comment on: http://stackoverflow.com/q/49199066
type: QuestionComment
score: 0

http://stackoverflow.com/q/49136230
has body: Hi in IntelliJ I can run python programs fine, but the imports such as "import pandas as pd" are not recognised by IntelliJ in that it displays a red squiggly line underneath. Does anyone know how to resolve these symbols? I have tried looking at project structure but cannot change anything that resolves the issue. It is pretty frustrating to have these red lines everywhere.
tagged with: python
tagged with: module
has title: IntelliJ not recognising python import
has comment: http://stackoverflow.com/comment/85363684
score: 0
answer count: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85277344
tagged with: import
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85850907
type: UnansweredQuestion
tagged with: intellij-idea

http://stackoverflow.com/comment/85906717
has text: yes. Because index 0 of row is just the first position in the list, and the first position in the list is the index number from the data.
comment on: http://stackoverflow.com/a/49366510
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49194292
has body: Don't use call; its only purpose is to block until the command exits. Use Popen directly: import subprocess p = subprocess.Popen("path/to/script.sh") Now script.sh runs in the forked process while your Python script continues. Use p.wait() when you are ready to check if the script has completed.
accepted answer of: http://stackoverflow.com/q/49191379
answers question: http://stackoverflow.com/q/49191379
type: AcceptedAnswer
type: Answer
score: 0

http://stackoverflow.com/comment/85430131
score: 0
type: AnswerComment
type: Comment
has text: And when I use inspect.stack(), as expected, the function name is still foo.
comment on: http://stackoverflow.com/a/49212750

http://stackoverflow.com/q/49131451
score: 0
has comment: http://stackoverflow.com/comment/85276101
has comment: http://stackoverflow.com/comment/85277705
has comment: http://stackoverflow.com/comment/85277853
type: Question
has comment: http://stackoverflow.com/comment/85281458
has comment: http://stackoverflow.com/comment/85272413
has comment: http://stackoverflow.com/comment/85270435
answer count: 0
has body: My graph is constructed from a db query where the result has following columns: source, target, weight, param The graph s constructed like this: graph = igraph.Graph.DictList(vertices=None, edges=result, edge_foreign_keys=('source', 'target')) I can find the shortest path without problem by using dist = graph.shortest_paths_dijkstra(source='5501362', target='5514175', weights='weight') also I can list all nodes composing my path by path = graph.get_shortest_paths('5501362', to='5514175', weights='weight') But I have to add a condition where I only select edges which correspond to param=10 How to add this condition to my shortest paths queries? Edit: Here is the code I'm using: most = time.time() with pyodbc.connect(connstr) as db: cr = db.cursor() rows = cr.execute(_sql).fetchall() db_cols = [column[0] for column in cr.description] result = [] for row in rows: result.append(dict(zip(db_cols, row))) print(f"DB query time: {time.time()-most}") most = time.time() graph = igraph.Graph.DictList(vertices=None, edges=result, edge_foreign_keys=('source', 'target')) print(f"graph construction time: {time.time()-most}") most = time.time() dist = graph.shortest_paths_dijkstra(source='5501362', target='5514175', weights='weight') print(dist) print(f"shortest_paths_dijkstra time: {time.time()-most}") most = time.time() path = graph.get_shortest_paths('5501362', to='5514175', weights='weight') print(f"get_shortest_paths time: {time.time()-most}")
has comment: http://stackoverflow.com/comment/85279865
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85281794
has comment: http://stackoverflow.com/comment/85278264
tagged with: igraph
has comment: http://stackoverflow.com/comment/85279083
has title: python-igraph find shortest path only if attributes corresponds to a condition

http://stackoverflow.com/comment/85282135
type: Comment
comment on: http://stackoverflow.com/q/49138516
type: QuestionComment
has text: ordinary `dict`s in Python have no order, so you cannot sort them. You must use [`OrderedDict`](https://docs.python.org/3/library/collections.html#collections.OrderedDict)
score: 1

http://stackoverflow.com/comment/130316013
score: 0
type: AnswerComment
has text: why do you transfer output of chcp to powershell? maybe you meant && instead of | ?
type: Comment
comment on: http://stackoverflow.com/a/49630797

http://stackoverflow.com/comment/85362274
has text: I expect a compiler will read the sources faster than your Python-tool. (mine reads nearly 100MB/sec) And it will even create executable code, too! And gprof will create a (reduced) call-graph for you, based on sampling the instruction pointer. Any significant recursion will show up. But if you want static analisys: just produce the call-graph. Beware of conditioal compilation/execution and dead code!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49175624

http://stackoverflow.com/comment/85365060
comment on: http://stackoverflow.com/q/49179568
has text: Oh ... so the tasks do *not* consume 100% of a critical system resource? 2 tasks can complete in less than the sum of their individual times?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49208378
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85421587
has answer: http://stackoverflow.com/a/49208592
type: Question
tagged with: python
tagged with: pygame
has body: I am currently trying to write a program that creates 20 random dots on the screen and times how long it takes you to click them in succession (they shouldn't appear all at once). Clearly, my code isn't finished but I keep getting an error message saying that "Particle object isn't iterable." Could anyone help me out? Thanks! (I know my particle list is a bit ridiculous too, but what can you do? :-)) import pygame import random import math import sys background_colour = (255,255,255) (width, height) = 600,500 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('DBS Test') circle1 = (pygame.draw.circle(screen, (255, 255, 255), (300, 250), 25, 25)) def addVectors(angle1, length1, angle2, length2): x = math.sin(angle1) * length1 + math.sin(angle2) * length2 y = math.cos(angle1) * length1 + math.cos(angle2) * length2 angle = 0.5 * math.pi - math.atan2(y, x) length = math.hypot(x, y) return (angle, length) def findParticle(particles, x, y): for p in particles: if math.hypot(p.x-x, p.y-y) &lt;= p.size: return p return None class Particle: def __init__(self, position, size): self.x, self.y = position self.size = size self.colour = (255, 0, 0) self.thickness = 20 def display(self): pygame.draw.circle(screen, self.colour, (self.x, self.y), self.size, self.thickness) particle_one = Particle((random.randint(0,600), random.randint(0,500)), 20) particle_two = Particle((random.randint(0,600), random.randint(0,500)), 20) particle_three = Particle((random.randint(0,600), random.randint(0,500)), 20) particle_four = Particle((random.randint(0,600), random.randint(0,500)), 20) particle_five = Particle((random.randint(0,600), random.randint(0,500)), 20) particle_six = Particle((random.randint(0,600), random.randint(0,500)), 20) particle_seven = Particle((random.randint(0,600), random.randint(0,500)), 20) particle_eight = Particle((random.randint(0,600), random.randint(0,500)), 20) particle_nine = Particle((random.randint(0,600), random.randint(0,500)), 20) part…
has comment: http://stackoverflow.com/comment/85421671
has title: "Particle Object Not Defined" Error Message
tagged with: particles
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49208592

http://stackoverflow.com/a/49147237
has comment: http://stackoverflow.com/comment/85308028
answers question: http://stackoverflow.com/q/49145584
has comment: http://stackoverflow.com/comment/85303319
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85303173
has comment: http://stackoverflow.com/comment/85307526
has comment: http://stackoverflow.com/comment/85304982
has comment: http://stackoverflow.com/comment/85307964
has comment: http://stackoverflow.com/comment/85308128
has comment: http://stackoverflow.com/comment/85306694
accepted answer of: http://stackoverflow.com/q/49145584
has comment: http://stackoverflow.com/comment/85309298
has comment: http://stackoverflow.com/comment/85305672
has comment: http://stackoverflow.com/comment/85305995
has comment: http://stackoverflow.com/comment/85306340
has comment: http://stackoverflow.com/comment/85309255
has body: Use: #specify columns to sum cols = ["Delivered Impressions", "Clicks", "Conversion", "Spend"] #replace NaNs by forward filling df['Placement# Name'] = df['Placement# Name'].ffill() #count grand total grand = df[cols].sum() grand.loc['Placement# Name'] = 'Grand total' print (grand) #get subtotal by aggregation sum df1 = df.groupby('Placement# Name')[cols].sum() #change sum for correct order df1.index = df1.index + '____' #join to original, sort by second level of MultiIndex df = (pd.concat([df.set_index('Placement# Name'), df1], keys=('a', 'b')) .sort_index(level=1) .reset_index()) #change values to total df['Placement# Name'] = np.where(df['level_0'] == 'a', df['Placement# Name'], 'Total') #remove column df = df.drop('level_0', axis=1) #add grand total df.loc[len(df.index)] = grand print (df) Placement# Name Adsize CTR \ 0 13.iab units (mobile only) + non-expanding adh... 320x50 0.0119683 1 Total NaN NaN 2 15.iab units (mobile only) + non-expanding adh... 320x50 0.0138741 3 15.iab units (mobile only) + non-expanding adh... 768x90 0.0271041 4 Total NaN NaN 5 18.iab units - desktop + mobile 160x600 0.00155927 6 18.iab units - desktop + mobile 300x250 0.00797965 7 18.iab units - desktop + mobile 300x600 0.00275059 8 18.iab units - desktop + mobile 728x90 0.00496391 9 Total NaN NaN 10 4.iab units (mobile only) + non-expanding adhe... 320x50 0.0141497 11 Total NaN NaN 12 5.iab units (mobile only) + non-expanding adhe... 320x50 0.0111654 13 5.iab units (mobile only) + non-expanding adhe... 768x90 0.0253428 14 Total NaN NaN 15 6.iab units - desktop + mobile 160x600 7.41895e-05 16 6.iab units - desktop + mobile 300x250 0.011838 17 6.iab units - desktop + mobile 300x600 0.000259538 18 6.iab units - desktop + mobile 728x90 0.00538178 19 Total NaN NaN 20 Grand total NaN NaN Clicks Conversion Conversion Rate Delivered Impressions Spend eCPA 0 1888 4 2.53566e-05 157750 1126.79 281.696 1 1888 4 NaN 157750 1126.79 NaN 2 2121 17 0.000111202 152875 1091.96 64.2332 3 152 2 0.0003566…
type: Answer
has comment: http://stackoverflow.com/comment/85306474
has comment: http://stackoverflow.com/comment/85308008
has comment: http://stackoverflow.com/comment/85304808
has comment: http://stackoverflow.com/comment/85308208
has comment: http://stackoverflow.com/comment/85309157
downvote count: 0

http://stackoverflow.com/q/49221539
has comment: http://stackoverflow.com/comment/85447780
has comment: http://stackoverflow.com/comment/85463840
type: UnansweredQuestion
tagged with: python
tagged with: flask
score: 0
has title: Multiple flask processes with a shared resource
answer count: 0
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
type: Question
has comment: http://stackoverflow.com/comment/85446848
tagged with: microservices
has body: Multiple flask processes (managed by gunicorn) serve the frontend and have to use a shared resource: A data structure that allows reads and updates and therefore needs to be protected by a simple (or RW) lock. What options do I have regarding the communication between web frontend and data structure? I already had a look at the following libraries: pyZMQ. I'm held back by the problem that arises when the service is restarting while the client is expecting data. Also I would need to implement method calling, de-/serialization and the like. https://github.com/0rpc/zerorpc-python This is an additional layer around pyZMQ and works around this issue but seems not very actively developed and I don't want to be forced to use gevent. Pyro. Seems to provide the functionality I need (using a single instance or python threads for the service). Might be a bit heavyweight for my needs. socketserver. Pretty lowlevel but might also do what I want as long as I implement method calling, de-/serialization, ... Are there better options?

http://stackoverflow.com/comment/85278578
comment on: http://stackoverflow.com/q/49133234
score: 0
has text: @Dockstar I considered CMD but the problem there is when you give a command line arg, it bashes all of the previous arguments, whereas I want to append. It seems the fundamental problem is that the array form of ENTRYPOINT does not do variable expansion.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49188701
score: 1
favorite count: 0
type: Question
has body: I am very new to Pandas and Python, so pardon me if this is a basic question. In an effort to solve my problem: Load multiple csv files, look for missing merchandiseID in subsequent files, calculate the date sold based on it, I made some changes to how I clean these files. I have the following columns in the data frame loaded from multiple csv files. store_id stock_number merchandise_id date_acquired color price MSRP csv_date 12973 7382 UISN78008 04/11/2017 Red $3200 $3650 01/31/2017 45973 9889 YHAN79807 08/09/2017 White $3600 $3650 01/31/2017 ... 45973 9889 YHAN79807 08/09/2017 White $3600 $3650 03/31/2017 The last column is the last occurrence of the item with merchandise_id 'YHAN79807'. I was able to find the last occurrence, by following How to identify the first occurence of duplicate rows in Python pandas Dataframe and modifying it a bit. I used df1['dup_index'] = df1.index.map(lambda ind: g.indices[ind][len(g.indices[ind])-1]) However, I want to set this value for the column 'dup_index' only for the last occurrence of 'YHAN79807' as merchandiseID. I do not want the rest of the rows with duplicated data for 'YHAN79807' as merchandiseID to have this value. They should be blank. Only the last occurrence should have this ID. I have not been able to do that yet. I tried a few things, one was: group = df1.groupby(['merchandiseID']) df1_index = df1.set_index(['merchandiseID']) df1[ (((len(group.indices[ind])-1)==group.indices[df1.merchandiseID])]['dup_index'] = 'succeed' I tried adding 'succeed' as a first step to see if the column comparison will give me result, but it gave me the following error: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison result = getattr(x, name)(y) ... raise TypeError('Could not compare %s type with Series' % I am at my wits end. What am I missing? Any pointers are appreciated. best, Alice
has comment: http://stackoverflow.com/comment/85385960
has comment: http://stackoverflow.com/comment/85401293
downvote count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49188800
linked to: http://stackoverflow.com/q/49103097
has title: How to identify and set a column value for only the last occurrence of a duplicate row
linked to: http://stackoverflow.com/q/14952957
answer count: 1
has answer: http://stackoverflow.com/a/49188800

http://stackoverflow.com/q/49144141
type: Question
has comment: http://stackoverflow.com/comment/85293562
type: UnansweredQuestion
tagged with: python
has title: How can I parallize my Python program to clean a dataset with 2000 csv files using Pandas dataframes?
has answer: http://stackoverflow.com/a/49150073
score: 0
tagged with: pandas
has body: This is the code for processing one file. import pandas as pd import numpy as npimport pandas as pd inputfile = open('dataset1.csv', 'r') df = pd.read_csv("cleaning/semicleaned1.csv", sep=",", names["press", "gph", "temp","wspd"]) df = df.drop(['gph'], axis=1) df.to_csv("cleaning/FINAL.csv", sep=',', index=False)
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
tagged with: multiprocessing

http://stackoverflow.com/a/49260003
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85540349
has body: You appear to be using a service account. In order for the service account to access your sperad sheet it needs to have access to it. Make sure that you share the sheet with the service account email address you can do that though google drive web page
type: Answer
answers question: http://stackoverflow.com/q/49258566

http://stackoverflow.com/q/49183806
tagged with: arrays
has answer: http://stackoverflow.com/a/49183882
has comment: http://stackoverflow.com/comment/85373621
has body: I've been playing with Python grabbing and parsing data from JSON API's. Specifically, I am working with the CTA (Chicago Transit Authority) Train Tracker API. I periodically receive a TypeError: string indices must be integers that I tracked down to a when an array of multiple 'train' runs exists versus a single 'train' run. The single run is not in an array of runs. {'ctatt': {'tmst': '2018-03-05T01:59:10', 'errCd': '0', 'errNm': None, 'route': [{'@name': 'g'}, {'@name': 'y', 'train': {'rn': '030', ..... 'heading': '302'}, {'@name': 'blue', 'train': [{'rn': '125', ..... 'heading': '302'}, {'rn': '127', ..... 'heading': '278'}, The 'g' route has no instances of runs. The 'y' route has 1 run. 'train': {'rn':} the 'blue' route has multiple runs. 'train': [{'rn': ...},{'rn': ...},{'rn': ...}] The code I'm using to parse through handles the lack of runs and multiple runs. It hits the TypeError with 1 run. for train_rt in trains_data['ctatt']['route']: line_name = train_rt['@name'] if train_rt.get('train', 'None') != 'None': for train_run in train_rt['train']: What is the best way to handle just a single run that's not in the array? 2 Yellow Line Runs in Chrome: Dev Tools: Network: Preview 1 Yellow Line Run in Chrome: Dev Tools: Network: Preview An inconsistency I noticed is, if I query a single route, the routes still are in an array of 1 route.
answer count: 1
has comment: http://stackoverflow.com/comment/85373691
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has title: Coding Python to handle JSON array inconsistencies
has comment: http://stackoverflow.com/comment/85373500
tagged with: jagged-arrays
type: Question
tagged with: api
accepted answer: http://stackoverflow.com/a/49183882
score: 0

http://stackoverflow.com/comment/85541674
score: 0
type: Comment
has text: `'{:.2f}'.format(Decimal(Decimal('0.00225') * Decimal('100')))` yields the same result
type: AnswerComment
comment on: http://stackoverflow.com/a/49269076

http://stackoverflow.com/q/49257503
tagged with: python
has answer: http://stackoverflow.com/a/49257542
has comment: http://stackoverflow.com/comment/85518061
has title: merging 2 partially matching rows python
type: AnsweredQuestion
tagged with: pandas
score: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49257542
favorite count: 0
type: Question
upvote count: 2
has body: I am currently trying to construct a dataframe from multiple sources using pandas. I am having the issue that I am unable to merge two rows within a dataframe that are partially matching. The example: input: |String | A | B | C | |--------------------------| |Hey | 1 | NaN | 2 | |Bye | 1 | 2 | 3 | |Hey | NaN | 5 | NaN | wanted output: |String | A | B | C | |--------------------------| |Hey | 1 | 5 | 2 | |Bye | 1 | 2 | 3 | Any Help would be greatly appreciated.
answer count: 1

http://stackoverflow.com/comment/85447891
comment on: http://stackoverflow.com/a/49221989
score: 0
type: AnswerComment
type: Comment
has text: That is true. You'd have to load all the objects from the database into memory to know which IDs are already taken.

http://stackoverflow.com/a/49122691
score: 1
downvote count: 0
upvote count: 1
type: Answer
has body: \033 is the octal code for esc and \x1b is the same in hex Check man ascii
answers question: http://stackoverflow.com/q/49122658

http://stackoverflow.com/comment/85459513
type: Comment
has text: Even if this is in a function, this has bad syntax in it.
type: AnswerComment
comment on: http://stackoverflow.com/a/49228000
score: 0

http://stackoverflow.com/q/49182790
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85371304
score: 0
answer count: 0
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/85371968
has body: I should preface that I am very new to Python and am completely lost as to how I would go about coding the solution to my problem. I have a text file that contains the following html code for example: Builders: Ingalls Shipbuilding Bath Iron Works </ul Operators: <img alt="" class="thumbborder" data-file-height="650" data-file-width="1235" height="12" src="//upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/22px-Flag_of_the_United_States.svg.png" srcset="//upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/33px-Flag_of_the_United_States.svg.png 1.5x, //upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/44px-Flag_of_the_United_States.svg.png 2x" width="22"/> United States Navy What I am trying to accomplish is iterating through each line and looking for tags that do not equal or contain <table, <td, <tr, , , and then finding the ">" and removing everything between or replacing with an empty string. The goal is to just keep the table tags with the raw text. From what I've read there's the soup.meta() or other functions that isolate tags but I'm not sure about it's implementation. I understand the logic should be something like this: for the length of the file if the first so many characters do not equal the tags listed above then find the > and replace everything in between < and > with "" else leave it alone Any help is appreciated.
has comment: http://stackoverflow.com/comment/85371457
has title: Python 3.6: Iterating through the length of a file and only keeping html table tags
type: Question

http://stackoverflow.com/a/49253273
answers question: http://stackoverflow.com/q/49252946
has body: Sleeping, to wait for the "desired" message will not work, because it's still the same connection and there is data on the stream that piled up. Option 1: One way is to call conn.recv(1024) (you may use any other value, 1024 works well for most cases) in a while loop, until the stream is "empty" and discard the 8 message blocks that you're not interested in (use a counter variable for that). Option 2: If you know exactly how much bits have piled up, you can also use conn.recv(13) to receive your first message, then sleep and then call conn.recv(13*8) (read 8 times your 13 bits messages - this is the data 1-9, that you do not want) and the next time you read from the stream it will contain your 9th message. However, this relies heavily on knowlegde how many bits exactly the client will send, so the first option would be better.
has comment: http://stackoverflow.com/comment/85516483
has comment: http://stackoverflow.com/comment/85511043
type: Answer
score: 0

http://stackoverflow.com/comment/85438936
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49214674
type: AnswerComment
has text: This seems to solve the problem of saving the data. A csv file of size 116MB got generated. This one csv has all currencies, but I need to save every currency in a different csv. Can you also suggest how do I save every scraped URL into a different csv file?

http://stackoverflow.com/q/49216443
type: Question
upvote count: 0
has title: why aren't these while if statements behaving how I want?
type: UnansweredQuestion
answer count: 1
downvote count: 1
favorite count: 0
has body: I'm learning python right now and I just wrote up this code for an assignment and it isn't behaving the way I expected or want it to. while(number != 0): def sumList(myList): myList.append(number) return myList Sum = (Sum + number) number = int(input("plese enter a number: ")) if(number == 0): def printList(myList): for number in myList: print(number, " + ") def main(): myList = createList() sumList(myList) printList(myList) main() print(Sum, " ") it should print out the sumList and the Sum when 0 is inputted but it's not and I don't know why.
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49216622

http://stackoverflow.com/comment/85432462
has text: Thank you! To add to this answer: When using python3, You don't need to use `codecs` (as the encoding parameter is provided in `open` as well. You also don't need to mark the string with a `u`. Therefore you only need to provide `encoding` on every file-opening operation.
type: AnswerComment
comment on: http://stackoverflow.com/a/49213908
score: 1
type: Comment

http://stackoverflow.com/comment/85266387
comment on: http://stackoverflow.com/q/49130476
type: QuestionComment
has text: Possible duplicate of [How do I get list of methods in a Python class?](https://stackoverflow.com/questions/1911281/how-do-i-get-list-of-methods-in-a-python-class)
type: Comment
score: 0

http://stackoverflow.com/comment/85312688
type: Comment
score: 0
has text: Seems like you don't have python setup correctly for your project. Set the correct python path and it will list modules you had installed
comment on: http://stackoverflow.com/q/49153985
type: QuestionComment

dataframe
tags question: http://stackoverflow.com/q/49178331
tags question: http://stackoverflow.com/q/49263257
tags question: http://stackoverflow.com/q/49137031
tags question: http://stackoverflow.com/q/49274161
tags question: http://stackoverflow.com/q/49257478
tags question: http://stackoverflow.com/q/49206879
tags question: http://stackoverflow.com/q/49197204
tags question: http://stackoverflow.com/q/49210113
tags question: http://stackoverflow.com/q/49126118
tags question: http://stackoverflow.com/q/49148768
tags question: http://stackoverflow.com/q/49263247
tags question: http://stackoverflow.com/q/49202052
tags question: http://stackoverflow.com/q/49270242
tags question: http://stackoverflow.com/q/49241026
tags question: http://stackoverflow.com/q/49129020
tags question: http://stackoverflow.com/q/49189175
tags question: http://stackoverflow.com/q/49252574
tags question: http://stackoverflow.com/q/49142429
tags question: http://stackoverflow.com/q/49174191
tags question: http://stackoverflow.com/q/49195022
tags question: http://stackoverflow.com/q/49156546
tags question: http://stackoverflow.com/q/49255247
tags question: http://stackoverflow.com/q/49179198
tags question: http://stackoverflow.com/q/49160944
tags question: http://stackoverflow.com/q/49147128
tags question: http://stackoverflow.com/q/49133004
tags question: http://stackoverflow.com/q/49136544
tags question: http://stackoverflow.com/q/49228728
tags question: http://stackoverflow.com/q/49150025
tags question: http://stackoverflow.com/q/49123132
tags question: http://stackoverflow.com/q/49243870
tags question: http://stackoverflow.com/q/49275330
tags question: http://stackoverflow.com/q/49250225
tags question: http://stackoverflow.com/q/49239875
tags question: http://stackoverflow.com/q/49201814
tags question: http://stackoverflow.com/q/49268116
tags question: http://stackoverflow.com/q/49182170
tags question: http://stackoverflow.com/q/49255374
tags question: http://stackoverflow.com/q/49214189
tags question: http://stackoverflow.com/q/49245258
tags question: http://stackoverflow.com/q/49142307
tags question: http://stackoverflow.com/q/49202420
tags question: http://stackoverflow.com/q/49248488
tags question: http://stackoverflow.com/q/49256838
tags question: http://stackoverflow.com/q/49242741
tags question: http://stackoverflow.com/q/49159764
tags question: http://stackoverflow.com/q/49147996
tags question: http://stackoverflow.com/q/49172914
tags question: http://stackoverflow.com/q/49199430
tags question: http://stackoverflow.com/q/49136106
tags question: http://stackoverflow.com/q/49201194
tags question: http://stackoverflow.com/q/49189903
tags question: http://stackoverflow.com/q/49253303
tags question: http://stackoverflow.com/q/49154800
tags question: http://stackoverflow.com/q/49138119
tags question: http://stackoverflow.com/q/49235092
tags question: http://stackoverflow.com/q/49188960
tags question: http://stackoverflow.com/q/49154375
tags question: http://stackoverflow.com/q/49266390
tags question: http://stackoverflow.com/q/49268554
tags question: http://stackoverflow.com/q/49148647
tags question: http://stackoverflow.com/q/49132889
tags question: http://stackoverflow.com/q/49271132
tags question: http://stackoverflow.com/q/49148098
tags question: http://stackoverflow.com/q/49189052
tags question: http://stackoverflow.com/q/49130752
tags question: http://stackoverflow.com/q/49122917
tags question: http://stackoverflow.com/q/49193536
tags question: http://stackoverflow.com/q/49223511
tags question: http://stackoverflow.com/q/49179006
tags question: http://stackoverflow.com/q/49136939
tags question: http://stackoverflow.com/q/49174367
tags question: http://stackoverflow.com/q/49198078
tags question: http://stackoverflow.com/q/49140675
tags question: http://stackoverflow.com/q/49133764
tags question: http://stackoverflow.com/q/49247174
tags question: http://stackoverflow.com/q/49123501
tags question: http://stackoverflow.com/q/49236619
tags question: http://stackoverflow.com/q/49185419
tags question: http://stackoverflow.com/q/49197793

http://stackoverflow.com/comment/85453471
type: QuestionComment
has text: Take a look at https://stackoverflow.com/questions/5453267/is-it-possible-to-modify-lines-in-a-file-in-place
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49224917

http://stackoverflow.com/comment/85419720
type: QuestionComment
comment on: http://stackoverflow.com/q/49206726
type: Comment
has text: In my experience the paypal sandbox can be pretty slow sometimes. How long were you waiting for the signal? Also In case you didn't know you can also check the recieved ipn calls in django admin which is pretty usesful
score: 0

http://stackoverflow.com/a/49201719
type: Answer
has comment: http://stackoverflow.com/comment/85409304
has comment: http://stackoverflow.com/comment/85408757
has body: The logic of your function is sound, you just need to handle the base case when the function is called so that you return the total rather than a tuple of (min, max, total). This can be achieved through the use of a helper function, or through the use of an optional parameter. Below, I have implemented the use of an optional parameter (mm) which signals whether to return the (min, max) tuple (with no total). So by default, this is False, but when calling the function recursively, we set this to True. def sum_min_max(lst, mm=False): if len(lst) == 1: if mm: return lst[0], lst[0] else: return lst[0] + lst[0] else: min_val, max_val = sum_min_max(lst[1:], True) if lst[0] &lt; min_val: min_val = lst[0] if lst[0] &gt; max_val: max_val = lst[0] if mm: return min_val, max_val else: return min_val + max_val and some tests: &gt;&gt;&gt; sum_min_max([1, 2, 3, 4, 5, 6]) 7 &gt;&gt;&gt; sum_min_max([5, 2, 1, 3, 4, 2]) 6 Although personally I would use the above, here is the helper function solution that achieves the same effect (in more lines): def _min_max_rec(l): if len(l) == 1: return l[0], l[0] else: min_val, max_val = _min_max_rec(l[1:]) if l[0] &lt; min_val: min_val = l[0] if l[0] &gt; max_val: max_val = l[0] return min_val, max_val def sum_min_max(lst): r = _min_max_rec(lst) return r[0] + r[1]
answers question: http://stackoverflow.com/q/49201573
has comment: http://stackoverflow.com/comment/85408912
has comment: http://stackoverflow.com/comment/85408930
has comment: http://stackoverflow.com/comment/85408985
score: 0
has comment: http://stackoverflow.com/comment/85409107
has comment: http://stackoverflow.com/comment/85409195

http://stackoverflow.com/a/53180290
type: Answer
has body: The rio functions like rasterio.rio.clip.clip cannot be called as Python functions, since they already have a command-line interface attached to them (all those decorators) and are optimized for getting their parameters from there. You can instead look into the code of the clip function to see how it achieves the clipping and mimick that. It basically creates a window from the bounds of your geometry and reads from the source raster with that window (windowed read). Or you can follow the example from the docs that uses rasterio.mask.mask(..., crop=True) and not only clips to the bounds but also masks pixels outside your geometry, which might be even closer to what you want to do.
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49189749
downvote count: 0

ms-word
tag name: ms-word
type: Tag
tags question: http://stackoverflow.com/q/49158107

http://stackoverflow.com/a/49180028
has comment: http://stackoverflow.com/comment/85372282
score: 1
type: Answer
downvote count: 0
upvote count: 1
has body: The reason you are getting the error is because you are trying to open a file encoded in 'UTF-16' in UTF-8. UTF-16 allows a Byte Order Mark (BOM), a code point with the value U+FEFF, to precede the first actual coded value. The byte order mark (BOM) is a Unicode character, U+FEFF byte order mark (BOM), whose appearance as a magic number at the start of a text stream can signal several things to a program consuming the text: What byte order, or endianness, the text stream is stored in; The fact that the text stream is Unicode, to a high level of confidence; Which of several Unicode encodings that text stream is encoded as. BOM use is optional, and, if used, should appear at the start of the text stream. If you open the file as "rb" i.e with the intention to read it as a byte stream this should be the first line of the output:- b'\xff\xfe\r\x00\n' This is the BOM I was talking about. If you run the following code:- with open("myfile.txt", "r", encoding="utf-16") as file: for line in file.readlines(): print(line) your output will have no errors. If you need to use UTF-8 for a some specific reason try to update the input file in byte format and removing the first line i.e. b'\xff\xfe\r\x00\n' Though I am not sure about the specifics. For more refer:-] BOM UTF-16
answers question: http://stackoverflow.com/q/49179633

http://stackoverflow.com/comment/85349233
score: 1
type: Comment
type: AnswerComment
has text: @vishnuprashanth is just a logical negation: you first get True for every line where condition is satisfied and, as you actually want to exclude them, you put a `NOT` in front
comment on: http://stackoverflow.com/a/49172083

http://stackoverflow.com/a/49197159
type: Answer
has comment: http://stackoverflow.com/comment/85399471
has comment: http://stackoverflow.com/comment/85399258
has body: This should work: &gt;&gt; string1 = 'value1 = "this_is_value1"' &gt;&gt; exec(string1) &gt;&gt; print(value1) "this_is_value1"
answers question: http://stackoverflow.com/q/49196889
has comment: http://stackoverflow.com/comment/85399305
score: 0

http://stackoverflow.com/q/49218044
has comment: http://stackoverflow.com/comment/85440178
type: Question
has comment: http://stackoverflow.com/comment/85440241
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85440107
tagged with: module
has title: Installing GEM in Python3 - The Graphic Embedding Module
linked to: http://stackoverflow.com/q/4495120
score: 0
tagged with: installation
answer count: 0
has body: I am trying to install the module GEM, but the installation keeps failing with following error: As you see, I'd cloned the repository on my local path ~/. The module page says as "In case of Python 3, make sure it was compiled with ./configure --enable-shared, and that you have /usr/local/bin/python in your LD_LIBRARY_PATH", but I don't know what compiled with ./configure --enabled-shared means and what LD_LIBRARY_PATH is. Can anyone help me?

pepper
tags question: http://stackoverflow.com/q/49155151
tag name: pepper
type: Tag

http://stackoverflow.com/q/49239346
answer count: 1
tagged with: django
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85514065
type: Question
has title: Django Error While Submitting Forms
accepted answer: http://stackoverflow.com/a/49240199
tagged with: python
score: -1
has body: Performing system checks... Unhandled exception in thread started by .wrapper at 0x75abfcd8> Traceback (most recent call last): File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/pi/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/home/pi/.venv/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/pi/.venv/lib/python3.5/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/home/pi/.venv/lib/python3.5/site-packages/django/urls/resolvers.py", line 529, in urlconf_module return import_module(self.urlconf_name) File "/home/pi/.venv/lib/python3.5/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 986, in _gcd_import File "", line 969, in _find_and…
has answer: http://stackoverflow.com/a/49240199
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/a/79472892
has body: import fastgif import matplotlib.pyplot as plt import numpy as np def get_fig(idx): x_space = np.linspace(0, 10, 30) + (idx / 20) fig, ax = plt.subplots(dpi=150) ax.plot(x_space, np.sin(x_space)) ax.grid() ax.set_ylim(-1.2, 1.2) ax.set_xlabel('x') ax.set_ylabel('sin(x)') fig.suptitle(f'Sine wave gif') return fig
has comment: http://stackoverflow.com/comment/140159103
answers question: http://stackoverflow.com/q/49279202
score: 0
type: Answer

http://stackoverflow.com/a/49216294
has body: If you will only use Linux you can consider using something based on inotify, specifically pyinotify. inotify is hooked into the operating system so as the os makes file changes it triggers notify events into your application. However, you may potentially find challenges if you need to use a platform other than Linux and may need to use a different library. Here is more information about how inotify works. If you need something that will work on Mac OS, Linux, and Windows you can also consider Watchdog. This uses the platform specific file watching facility: Windows: FindFirstChangeNotification API Mac OS: FS Events Linux: inotify This discussion may be similar to your question as well.
has comment: http://stackoverflow.com/comment/85437140
has comment: http://stackoverflow.com/comment/85437158
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/85437387
answers question: http://stackoverflow.com/q/49215996
score: 1
has comment: http://stackoverflow.com/comment/85437435
has comment: http://stackoverflow.com/comment/85437032

http://stackoverflow.com/a/49259637
answers question: http://stackoverflow.com/q/49234974
score: 0
has body: The problem is located at the begging of your fight() function: def fight(): Character = NewCharacter() while int(Character[0])&gt;0: NewCharacter is a function that does not return anything, and so that's the same as doing: def fight(): Character = None while int(Character[0])&gt;0: You can just call the function NewCharacter() without saving the return value and then check the Character global.
type: Answer

http://stackoverflow.com/comment/85503253
comment on: http://stackoverflow.com/a/49249813
has text: I don't see that in your example but if all you want is change utils it's even easier, see edit.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85280510
has text: Your SHIFT_TRAFFIC_OFF function prints a string it doesn't return a string. You need to return a string so that f.write can write it to your file. Change your SHIFT_TRAFFIC_OFF to return """ router ospf 1... """
score: 0
comment on: http://stackoverflow.com/q/49137673
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49162994
has answer: http://stackoverflow.com/a/55198799
answer count: 2
downvote count: 0
upvote count: 1
score: 1
tagged with: ocr
has title: PyOCR - get_availables_tools() returns an empty list / Can access tesseract from the command line
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: path
tagged with: python
has answer: http://stackoverflow.com/a/53648961
tagged with: tesseract
has body: I am attempting to install PyOCR on my computer running Windows 7. I have installed Tesseract-OCR 3.05 for Windows and have added the directory containing Tesseract (C:\Program Files (x86)\Tesseract-OCR) to the PATH user variable, the Path System Variable, and created the new system variable TESSDATA_PREFIX with the Tesseract directory. I am able to use Tesseract directly from the command line to process images, so I am confident that Tesseract was correctly installed. I also made sure to installed Tesseract with the C/C++ library files. I know this question has been posed before, but since I have added the directories to the environmental variables, I am unsure what to try next. Below is the output of the "get_available_tools()" method. Python 3.6.3 |Anaconda custom (64-bit)| (default, Oct 15 2017, 03:27:45) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pyocr &gt;&gt;&gt; import pyocr.builders &gt;&gt;&gt; pyocr.get_available_tools() [] &gt;&gt;&gt;

http://stackoverflow.com/comment/85328042
has text: I have updated the answer to show how this can be done.
type: Comment
comment on: http://stackoverflow.com/a/49159264
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85257991
type: Comment
has text: p.run() makes the processes run sequentially. And does not make use of the multiprocessing capabilities.
comment on: http://stackoverflow.com/a/49125482
type: AnswerComment
score: 0

constraints
type: Tag
tag name: constraints
tags question: http://stackoverflow.com/q/49256752

http://stackoverflow.com/comment/85554940
score: 0
type: AnswerComment
type: Comment
has text: Just figured it might not be obvious to the question asker :)
comment on: http://stackoverflow.com/a/49276053

http://stackoverflow.com/q/49141186
has comment: http://stackoverflow.com/comment/85287810
type: Question
accepted answer: http://stackoverflow.com/a/49141302
has comment: http://stackoverflow.com/comment/85287842
has title: Django view not recognizing request
tagged with: django
has comment: http://stackoverflow.com/comment/85287850
tagged with: python
has comment: http://stackoverflow.com/comment/85287882
tagged with: request
type: AnsweredQuestion
has body: I have a form that is filled out on a webpage. The goal of the form is to gather some basic info, and then save the IP of the sender to the DB too. The form submits a POST request to my Django view, but Django gives me the error: if request.method() == 'POST': TypeError: 'str' object is not callable Here is the view: from .form import SignUpForm from django.shortcuts import render from django.http import HttpResponseRedirect def index(request): if request.method() == 'POST': form = SignUpForm(request.POST) if form.is.valid(): signup_item = form.save(commit=False) signup_item.ip_address = request.META['HTTP_X_FORWARDED_FOR'] signup_item.save() return HttpResponseRedirect(request.path) else: form = SignUpForm() return render(request, 'index.html', {'form': form}) Here is the urls.py from django.conf.urls.import url from django.contrib import admin from form import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', views.index, name='home') ]
score: 0
has answer: http://stackoverflow.com/a/49141302
answer count: 1

http://stackoverflow.com/comment/85487488
score: 0
type: Comment
has text: Sry, the collision between `a` and `c` was causing only `c`'s value to come out in the final dictionary. Fixed it to better reflect your sample output (by tweaking your sample input slightly)
type: AnswerComment
comment on: http://stackoverflow.com/a/49241875

http://stackoverflow.com/q/49270277
favorite count: 0
answer count: 19
has comment: http://stackoverflow.com/comment/85543923
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/78053339
has answer: http://stackoverflow.com/a/69458121
has body: Consider: I am trying to find the area of an n-interesting polygon, where (n=1, A=1, n=2, A=5, n=3, A=13, n=4, A=25, and so on). So the formula for an n-interesting polygon is the area of an (n-1)-interesting polygon+(n-1)*4. When running the program, a hidden test shows that the code is wrong. What is wrong with my code? def shapeArea(n): if n == 0: return 0 if n == 1: return 1 for i in range(2, n+1): return (shapeArea(n-1) + (n-1)*4)
has answer: http://stackoverflow.com/a/68232560
has answer: http://stackoverflow.com/a/67119316
has comment: http://stackoverflow.com/comment/125754137
has answer: http://stackoverflow.com/a/71164826
has answer: http://stackoverflow.com/a/55662614
tagged with: python
accepted answer: http://stackoverflow.com/a/49271087
has answer: http://stackoverflow.com/a/67260848
has answer: http://stackoverflow.com/a/49271087
type: Question
has answer: http://stackoverflow.com/a/70130298
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/110301075
has title: Find the area of an n-interesting polygon
has answer: http://stackoverflow.com/a/65593972
upvote count: 25
possible better answer: http://stackoverflow.com/a/67119316
downvote count: 4
has comment: http://stackoverflow.com/comment/85544432
has comment: http://stackoverflow.com/comment/85544960
has comment: http://stackoverflow.com/comment/85543739
has answer: http://stackoverflow.com/a/63559936
has answer: http://stackoverflow.com/a/67984378
has answer: http://stackoverflow.com/a/72090287
score: 21
has answer: http://stackoverflow.com/a/71162092
has answer: http://stackoverflow.com/a/69484511
has answer: http://stackoverflow.com/a/64472017
has answer: http://stackoverflow.com/a/70727805
has answer: http://stackoverflow.com/a/55977819
has answer: http://stackoverflow.com/a/66931885

http://stackoverflow.com/comment/85262576
comment on: http://stackoverflow.com/a/49128845
has text: have you installed tesseract?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49183590
has comment: http://stackoverflow.com/comment/85859954
accepted answer of: http://stackoverflow.com/q/49183568
has comment: http://stackoverflow.com/comment/85858832
score: 7
has body: You may remove a (...) substring with a leading whitespace at the end of the string only: \s*\([^()]*\)$ See the regex demo. Details \s* - 0+ whitespace chars \( - a ( [^()]* - 0+ chars other than ( and ) \) - a ) $ - end of string. See the Python demo: import re bracketedString = '*AWL* (GREATER) MINDS LIMITED (CLOSED)' nonBracketedString = re.sub(r"\s*\([^()]*\)$", '', bracketedString) print(nonBracketedString) # =&gt; *AWL* (GREATER) MINDS LIMITED With PyPi regex module you may also remove nested parentheses at the end of the string: import regex s = "*AWL* (GREATER) MINDS LIMITED (CLOSED(Jan))" # =&gt; *AWL* (GREATER) MINDS LIMITED res = regex.sub(r'\s*(\((?&gt;[^()]+|(?1))*\))$', '', s) print(res) See the Python demo. Details \s* - 0+ whitespaces (\((?&gt;[^()]+|(?1))*\)) - Group 1: \( - a ( (?&gt;[^()]+|(?1))* - zero or more repetitions of 1+ chars other than ( and ) or the whole Group 1 pattern \) - a ) $ - end of string.
type: Answer
answers question: http://stackoverflow.com/q/49183568
type: AcceptedAnswer
downvote count: 0
upvote count: 7

http://stackoverflow.com/comment/85459463
type: AnswerComment
has text: Have you actually tried what you suggested? Because it gives `<type 'set'>`, not `<str set>`. And of course `set()` doesn't return the same thing as `type(set())`; the set type is a type, not a set. And meanwhile, why would the name of the type control which operators it supports? It's the dunder methods (or type slots, for builtins) that control that.
comment on: http://stackoverflow.com/a/49227937
type: Comment
score: 0

http://stackoverflow.com/a/49121550
has comment: http://stackoverflow.com/comment/85248903
score: 0
type: Answer
has body: Do not call plt.show() if you want to show your figure inside a tk GUI. Best do not use pyplot at all when embedding. On the other hand, you probably want to start the mainloop, tk.mainloop(), at some point. Refer to the matplotlib example on how to embedd a matplotlib figure into tk.
has comment: http://stackoverflow.com/comment/85248846
has comment: http://stackoverflow.com/comment/85248824
answers question: http://stackoverflow.com/q/49121492
has comment: http://stackoverflow.com/comment/85248707
accepted answer of: http://stackoverflow.com/q/49121492
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85248682
has comment: http://stackoverflow.com/comment/85248764

http://stackoverflow.com/q/49166412
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: request
has body: Im having abit of issue downloading an xlsx file over https. Here my code to scrape the sight to get the download url, but its seems to redirect me to a new site. but when i put the link in my browswer, it downloads the file straight away. Is there something im doing wrong? here is the code i used for scraping the site: import contextlib import OpenSSL.crypto import os import requests import ssl import tempfile import http.client import shutil from OpenSSL import crypto import pem import html2text url = "https://signonssl.site.com" base_url = "basedownloadurl" p12_cert = "cert_path" password = "password" @contextlib.contextmanager def pfx_to_pem(p12_path, pfx_password): ''' Decrypts the .p12 file to be used with requests. ''' with tempfile.NamedTemporaryFile(suffix='.pem') as t_pem: f_pem = open(t_pem.name, 'wb') pfx = open(p12_path, 'rb').read() p12 = OpenSSL.crypto.load_pkcs12(pfx, pfx_password) f_pem.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, p12.get_privatekey())) f_pem.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, p12.get_certificate())) ca = p12.get_ca_certificates() f_pem.close() yield t_pem.name with pfx_to_pem(p12_cert, password) as cert: html_response = requests.get(url, cert=cert).content.decode("utf-8") htmlconv = html2text.html2text(html_response).split("name")[1] dl_link = htmlconv.split(")")[0].split("(")[1] dl = requests.get(dl_link, cert=cert, stream=True, allow_redirects=False) output = open('test.xlsx', 'wb') output.write(dl.content) output.close() Any guidance is much appreciated. Thanks! Pon
tagged with: openssl
score: 0
has title: Download xlsx with request w/pem cert
tagged with: https
has comment: http://stackoverflow.com/comment/85338094
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85338636
type: Question

http://stackoverflow.com/q/49227851
tagged with: pygame
has title: Stencil test does not clip Texture
score: 2
type: AnsweredQuestion
tagged with: stencil-buffer
accepted answer: http://stackoverflow.com/a/49229445
has body: I'm trying to clip a texture using a Stencil Test. The idea is to create a surface (in this example a simple rectangle) to select a region of the texture to be shown (as the image bellow) I created a simple code to do so, where I first perform an ALWAYS stencil test to set all the bits on the stencil buffer to 2, and then change the test to KEEP, which I thought would output the desired result, but nothing happens import pygame import sys from OpenGL.GL import * from pygame.locals import * # set pygame screen pygame.display.set_mode((1000, 500), OPENGL | DOUBLEBUF) info = pygame.display.Info() # basic opengl configuration glViewport(0, 0, info.current_w, info.current_h) glClearColor(0.0, 0.0, 0.0, 1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() # set up texturing glEnable(GL_TEXTURE_2D) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # load texture surf = pygame.image.load('Player1.png') s = pygame.image.tostring(surf, 'RGBA') texID = glGenTextures(1) glBindTexture(GL_TEXTURE_2D, texID) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surf.get_width(), surf.get_height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, s) glGenerateMipmap(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, 0) # create pygame clock MAINCLOCK = pygame.time.Clock() # init screen pygame.display.init() while True: # get quit event for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() # prepare to render screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT) glMatrixMode(GL_MODELVIEW) glLoadIdentity() # Enable stencil test glEnable(GL_STENCIL_TEST) glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE) glStencilFunc(GL_ALWAYS, 2, ~0) glStencilOp(GL_REPLA…
tagged with: opengl
has answer: http://stackoverflow.com/a/49229445
downvote count: 0
answer count: 1
tagged with: pyopengl
favorite count: 0
type: Question
upvote count: 2
tagged with: python

http://stackoverflow.com/comment/134878912
score: 0
type: AnswerComment
has text: @PlaceReporter99: That's not safe either. It just recursively reruns the entire program, ignoring the fact that the program's data structures may now be in an inconsistent state, or the fact that doing this repeatedly will lead to a stack overflow, or the fact that restarting the program is rarely what anyone wants to happen on KeyboardInterrupt. Writing KeyboardInterrupt-safe code is *way* harder than that.
comment on: http://stackoverflow.com/a/49262664
type: Comment

http://stackoverflow.com/q/49186622
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85378708
tagged with: arrays
has comment: http://stackoverflow.com/comment/85378735
has title: Convert 2D Array rows to dictionary in Python
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85378657
tagged with: python
has comment: http://stackoverflow.com/comment/85378697
tagged with: generator
has body: I have 2D Array. i want to convert the each row as dictionary with value 0 in Python. Array format is P T P T P T T T P used the below Dictionary Comprehensions logic, dic = {y: 0 for y in x} to get output like, {'P': 0, 'T': 0, 'P': 0} {'T': 0, 'P': 0, 'T': 0} {'T': 0, 'T': 0, 'P': 0} But i'm getting below output {'P': 0, 'T': 0} {'T': 0, 'P': 0} {'T': 0, 'P': 0} Could you help me to solve this.

http://stackoverflow.com/q/49246815
tagged with: image
downvote count: 1
favorite count: 0
type: Question
answer count: 2
upvote count: 0
has answer: http://stackoverflow.com/a/56705165
has body: I have a folder of several images, and I would like to choose one randomly and add it to a subplot (using offsetbox for example). How can I do this?
type: UnansweredQuestion
tagged with: python
score: -1
tagged with: plot
has answer: http://stackoverflow.com/a/49246871
has title: Choose a random image from a folder to add to a subplot | Python

http://stackoverflow.com/a/49238066
answers question: http://stackoverflow.com/q/49155728
score: 0
type: AcceptedAnswer
has body: After some more testing, I ended up with the following code. The above code from the question still had some bugs. import numpy as np def maximal_elements(input_list): """Given a list of np.array, compute the maximal elements. Call: maximal = maximal_elements(input_list) Input: input_list: list of np.array, all need to have the same length. Output: maximal: list of np.array, which contains the maximal elements of input_list, the order used is elementwise "&lt;=" """ l = input_list.copy() l.sort(reverse=True, key=np.sum) maximal = [l[0]] for e in l[1:]: i = 0 replaced = False while i &lt; len(maximal): if (maximal[i] &lt;= e).all(): if replaced: maximal.pop(i) i -= 1 else: maximal[i] = e.copy() replaced = True if (e &lt;= maximal[i]).all(): if not (e == maximal[i]).all(): break i += 1 if i == len(maximal) and not replaced: maximal.append(e.copy()) return maximal import itertools import random random.seed(2) l = [np.array(e) for e in random.sample(list(itertools.product([0,1], repeat=5)), 9)] maximal_elements(l) returns [array([1, 1, 1, 1, 0]), array([1, 0, 1, 1, 1]), array([0, 1, 0, 1, 1])]
type: Answer
accepted answer of: http://stackoverflow.com/q/49155728

http://stackoverflow.com/a/49238515
score: 0
answers question: http://stackoverflow.com/q/49237298
has body: I agree with what @Martin Sand Christensen told you but if you don't have any idea of how to do it, here is an idea that you can develop on your own. Considering that you need to find the closest name to the first at each iteration: char &lt;- c("John Doe", "JohnDoe", "JohnDoe2", "JohnDoe 84302") for(i in 2:length(char)){ if(!anyNA(str_match(char[2],str_split(char[1]," ")[[1]]))){ char[i] &lt;- char[1] print(char) } } We define char vector. Then we iterate over all other names. If we detect a name which contains separately "John" and "Doe", we set it to "John Doe". If there is only "John" or only "Doe" in the name, we don't touch it.
type: Answer

http://stackoverflow.com/a/49143680
has comment: http://stackoverflow.com/comment/85301776
type: Answer
has body: The first time through the loop, list is just a name for matrix[0]. Mutating the object that list names, as in CODE 2, obviously mutates the object that matrix[0] names, because they're naming the same object. But just rebinding list to some different object, as in CODE 1, doesn't change matrix[0] in any way. If you think about it, that makes sense. After all, the next time through the loop, list is going to get rebound to matrix[1], and you certainly wouldn't want that to change what's in matrix[0], right? In C terms (and this is literally true, if you're using the normal CPython implementation), being names for the same object means being pointers to the same object. If list is a List *, assigning to list doesn't do anything to whatever was in *list. So, why does CODE 4 work? Well, in code 4, you're still not mutating the list—but you're rebinding matrix[0], instead of list, and of course that rebinds matrix[0]. I'm guessing that, despite talking about "Java/C", you're really thinking in C++ terms. In C++, = is an operator, which can be overloaded. Plus, you don't just have pointers, but references, which sort of magically work without needing to explicitly dereference them. So, if list is a reference to a list object, rather than a pointer, list = isn't changing it into a reference to another list object, it's calling a special method, ListType::operator=. That's actually pretty weird. There's nothing like that in Java. or C. any more than there is in Python. For more detail on what happens under the covers: If you want to think of it in C terms, the actual C API used by the main (CPython) implementation may make things clear here. Your function's locals are just an array of pointers to Python objects. That matrix is locals[0], list is locals[1], etc. What's in *locals[0] is a PyListObject struct, which contains, among other things, a pointer to an array of Python objects. Each of which is pointing to another PyListObject struct. But inside those inner lists' arr…
answers question: http://stackoverflow.com/q/49143433
score: 2
has comment: http://stackoverflow.com/comment/85293609
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/49211079
downvote count: 0
favorite count: 0
type: Question
has title: Firebase Auth + Python backend
tagged with: firebase
score: 3
type: UnansweredQuestion
tagged with: firebase-admin
tagged with: python
has answer: http://stackoverflow.com/a/49224768
tagged with: bottle
has body: I am going to use Firebase Auth and Database modules to create my web app. However, not all things that I want my app to do is possible to achieve on only front end. So I want to also use backend with Python's Bottle framework to handle requests and Pyrebase to get access to Firebase Database. Let's say that after logging in I need to go to mainpage and see personalized content, for example my notes. They are structured this way in DB: { "notes": [{ "id": "1", "title": "X", "author": "user1" }, { "id": "2", "title": "Y", "author": "user2" } and so on... ] } So how it's possible to implement showing only my articles on main page? I understand that I need to filter my notes based on author value, but how to let Bottle understand who is currently logged in? I've read there, that I should somehow send unique token to backend server to authenticate current user, but how to do that? Inserting Token in every link as GET parameter seems to be silly, but I see no other way to implement that.
upvote count: 3
answer count: 1

http://stackoverflow.com/comment/85500945
type: AnswerComment
score: 0
has text: Thank you very much, small and neat solution!!
type: Comment
comment on: http://stackoverflow.com/a/49246466

http://stackoverflow.com/q/49182694
score: -3
has answer: http://stackoverflow.com/a/49182815
has body: i want the code to ask for the radius and length then the program will calculate piradiusradius*length from the definition area the print out the radius for example if at asks me the radius i put 5 same with the length it should say the volume is 392.75 def calculate_volume(radius, length): pi=3.142 vol=pi*radius*radius*length #main program radius = int(input("enter radius: ")) length = int(input("enter length: ")) volume = calculate_volume(radius, length) print("the volume: ",volume)
has comment: http://stackoverflow.com/comment/85371086
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85371099
has answer: http://stackoverflow.com/a/49182727
answer count: 3
downvote count: 3
possible better answer: http://stackoverflow.com/a/49182772
tagged with: python
favorite count: 0
accepted answer: http://stackoverflow.com/a/49182727
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/85371219
has title: im trying to find the volume of a shape but the definition is not working
has comment: http://stackoverflow.com/comment/85371149
has answer: http://stackoverflow.com/a/49182772

http://stackoverflow.com/q/49234974
score: -2
downvote count: 2
answer count: 1
has title: I am having an error I cannot seem to fix on my microbit (line 55 type error 'none type' object is not subscriptable)
has comment: http://stackoverflow.com/comment/85473493
favorite count: 0
tagged with: bbc-microbit
has body: My code is for a game I am attempting to create, but the bottom of the code is continuously bringing up an error. I have left a copy of the code here, could you please help? The error is on line 55 [display.scroll ("You were slain...")] from microbit import* import random Character = [] Enemy = [] def RollDice(): Diceroll1 = random.randint(1,6) Diceroll2 = random.randint(1,6) Total = Diceroll1 + Diceroll2 return Total def NewCharacter(): Health = 100 Strength = random.randint(30,80) Defence = random.randint(20,60) Character.append(Health) Character.append(Strength) Character.append(Defence) #display.scroll("You have 100 health, your strength is" + str(Strength) + " and you have" + str(Defence) + "defence.") def NewEnemy(): sleep(1000) MonsterTypes = ["Basilisk","Banshee","Behemoth"] Names = ["Ben","Bethany","Bobby", "Bella"] Enemy = [] n1 = (random.choice(Names)) n2 = (random.choice(MonsterTypes)) Enemy.append(n1+ " the " +n2) Enemy.append(random.randint(30,70)) Enemy.append(random.randint(35,70)) Enemy.append(random.randint(25,70)) return Enemy def fight(): Character = NewCharacter() while int(Character[0])&gt;0: Enemy = NewEnemy() display.scroll (str(Enemy[0]) + "is here to fight!") while int(Enemy[1]&gt;0) and int(Character[0])&gt;0: display.scroll("A(Attack) or B(Block)") if button_a.is_pressed(): Total = RollDice() + int(Character[1]) - int(Enemy[3]) if Total &lt; 1: Total = 1 Enemy[1] -= Total if int(Enemy[1]) &lt; 0: Enemy[1] = 0 display.scroll (str(Enemy[0]) + "'s health is" + str(Enemy[1]) + ".") if int(Enemy[1]) &lt; 1: display.scroll ("You have slain" + str(Enemy[0]) + "!") else: display.scroll (str(Enemy[0]) + "is attacking you!") Total = RollDice() + int(Enemy[2]) - int(Character[2]) Character[0] -= Total if int(Character[0]) &lt; 0: Character[0] = 0 display.scroll ("Your health is" + str(Character[0]) + ".") if int(Character[0]) &lt; 1: display.scroll ("You were slain...") fight()
has answer: http://stackoverflow.com/a/49259637
has comment: http://stackoverflow.com/comment/85473534
tagged with: python
has comment: http://stackoverflow.com/comment/85473449
has comment: http://stackoverflow.com/comment/85473047
type: Question
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85331106
comment on: http://stackoverflow.com/a/49162357
score: 0
has text: `{1}` is an effectively meaningless quantifier.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49200254
tagged with: robobrowser
tagged with: asp.net
type: Question
has body: I have been working on this for couple days now. Can not really find how to make this work. I am fairly new to aspx websites and fetching information out of them. I am trying to login/authenticate on a website that uses aspx pages. So I followed this thread which really helped me get this in motion. (Last Answer) Following those directions, I write: url = "http://samplewebsite/Main/Index.aspx" # Logon page username = "user" password = "password" browser = RoboBrowser(history=True) # This retrieves __VIEWSTATE and friends browser.open(url) signin = browser.get_form(id='form1') print(signin) This is the outcome of that print statement: &lt;RoboForm __VIEWSTATE=/wEPDwULLTE5ODM2NTU1MzJkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQlidG5TdWJtaXRriD1xvrfrHuJ/0xbQM08yEjyoUg==, __VIEWSTATEGENERATOR=E78488FE, adminid=, btnSubmit=, pswd=&gt; So it is obvious that I am retrieving the information correctly. Now I have 3 input fields: adminid btnSubmit pswd Which I can use in the following manner: signin["adminid"].value = username signin["pswd"].value = password signin["btnSubmit"].value = "btnSubmit.x=29&amp;btnSubmit.y=22" My only problem is the last field btnSubmit which I do not know how to input a value since this is of the following type: &lt;input type="image" name="btnSubmit" id="btnSubmit" tabindex="3" src="../image/login_btn.gif" style="height:41px;width:57px;border-width:0px;" /&gt; when I submit on the website, using the Chrome Tools I get the following outcome: __VIEWSTATE:/wEPDwULLTE5ODM2NTU1MzJkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBQlidG5TdWJtaXRriD1xvrfrHuJ/0xbQM08yEjyoUg== __VIEWSTATEGENERATOR:E78488FE adminid:user btnSubmit.x:23 btnSubmit.y:15 pswd:password Where basically the x,y positions are where I clicked on the page. Really do not know how to do this request through Python. Used this to no avail.
accepted answer: http://stackoverflow.com/a/49200317
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/49200317
tagged with: python
type: AnsweredQuestion
score: 0
has title: Using robobrowser on ASP.net website
answer count: 1
linked to: http://stackoverflow.com/q/25996921
tagged with: python-requests

http://stackoverflow.com/comment/85279716
type: Comment
type: AnswerComment
has text: @AnonX An interesting takeaway from our last Q&A exchange is that groupby slows down horribly for series (df.eq(..) generates a series). Very interesting.
comment on: http://stackoverflow.com/a/49137073
score: 0

http://stackoverflow.com/comment/85546918
comment on: http://stackoverflow.com/q/49271613
has text: @Shadkhan example: `SEMESTER | 24 | 18 | | 0 | 74 | 28 | 0 | 74 | VISU`
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85374167
type: QuestionComment
score: 0
has text: Possible duplicate of [Replace duplicate values across columns in Pandas](https://stackoverflow.com/questions/39907315/replace-duplicate-values-across-columns-in-pandas)
comment on: http://stackoverflow.com/q/49184147
type: Comment

http://stackoverflow.com/q/49209689
accepted answer: http://stackoverflow.com/a/49209781
tagged with: arguments
tagged with: python
tagged with: module
has body: I built the following module for identifying if a file exists in a directory based on its size and name, all so I can use it in a different part of a project. When I try to use the function for the first time, it works great. But when I call it again, different variables with different parameters return the first answer. What am I missing? Module: import os from stat import * import math CORRECT_PATH = '' FLAG = 1 def check_matching(pathname, desired_file_name): global FLAG if desired_file_name in pathname: FLAG = 0 return pathname def walktree(dirz, desired_file_name, size): global CORRECT_PATH global FLAG for f in os.listdir(dirz): try: if FLAG: pathname = os.path.join(dirz, f) mode = os.stat(pathname)[ST_MODE] if S_ISDIR(mode): # It's a directory, recourse into it walktree(pathname, desired_file_name, size) elif S_ISREG(mode): # It's a file, call the callback function new_size = int(os.path.getsize(pathname)) if (new_size - int(size)) &lt; math.fabs(0.95*int(size)): CORRECT_PATH = check_matching(pathname, desired_file_name) else: # Unknown file type, print a message print 'Skipping %s' % pathname else: try: CORRECT_PATH = CORRECT_PATH.replace('\\', '/') return True, CORRECT_PATH except WindowsError as w: #print w if w[0] == 5: return True, CORRECT_PATH except WindowsError as e: pass # print e # if e[0] == 5: # return True, CORRECT_PATH # add correct path now return False, '' Now when I call the this code (This is an example, I'm using two different text files, with different sizes and different names which are saved on my local computer): import LS_FINAL_FOUR ans = LS_FINAL_FOUR.walktree("C:/", "a_test", 38) print ans # (True, 'C:/a_test.txt') ans1 = LS_FINAL_FOUR.walktree("C:/", "a_sample", 1000000) print ans1 # (True, 'C:/a_test.txt') Both return the same output. Very frustrating. Does anyone know the reason behind this and how to solve it? Edit: I'm almost certain it's a problem with the module, but I just can't lay my finger on it.
type: AnsweredQuestion
score: 0
answer count: 1
has title: Using a Function From a Module I Built Returns The First Value Despite Calling it Again With Different Arguments
type: Question
has answer: http://stackoverflow.com/a/49209781

symfony
tags question: http://stackoverflow.com/q/49127554
tag name: symfony
type: Tag

http://stackoverflow.com/q/49225394
has body: I have a dictionary with missing values (the key is there, but the associated value is empty). For example I want the dictionary below: dct = {'ID':'', 'gender':'male', 'age':'20', 'weight':'', 'height':'5.7'} to be changed to this form: dct = {'ID':NaN, 'gender':'male', 'age':'20', 'weight':NaN, 'height':'5.7'} How can I write that in the most time-efficient way?
has answer: http://stackoverflow.com/a/49225425
tagged with: missing-data
has comment: http://stackoverflow.com/comment/85455371
has comment: http://stackoverflow.com/comment/85454977
tagged with: python
score: 11
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85454467
has comment: http://stackoverflow.com/comment/85454813
answer count: 4
upvote count: 11
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49227597
has answer: http://stackoverflow.com/a/49226492
has answer: http://stackoverflow.com/a/49225687
downvote count: 0
has title: Replace empty values of a dictionary with NaN
accepted answer: http://stackoverflow.com/a/49225425
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85454500
possible better answer: http://stackoverflow.com/a/49225687

http://stackoverflow.com/comment/85391206
type: AnswerComment
score: 0
has text: wich i did. my biggest problem is no matter what i do the data never becomes float so i cant square any of it.
comment on: http://stackoverflow.com/a/49192610
type: Comment

routes
type: Tag
tags question: http://stackoverflow.com/q/49226626
tag name: routes

http://stackoverflow.com/comment/85508823
comment on: http://stackoverflow.com/a/49240977
type: Comment
type: AnswerComment
has text: The first program is 256 characters, its working if i push the path first like: Z:\Clients\xxx\2. RAW Export\ Then the file names like: "2nd (1).fls" "2nd (10).fls" "2nd (11).fls" "2nd (12).fls" "2nd (13).fls" "2nd (14).fls" "2nd (15).fls", but im gona struggle cause it only takes 256, any other ideas
score: 0

http://stackoverflow.com/q/49185572
has comment: http://stackoverflow.com/comment/85376801
has comment: http://stackoverflow.com/comment/85377355
has comment: http://stackoverflow.com/comment/85376998
tagged with: python
has body: I have 10 files datasets 10mb to 8gb, and I am trying to read a dataset txt with size 8gb that I cannot read because of the "¦" (Broken pipe)... Almost all that have size highest than 200mb have this same problem and the smallest files have the "normal" pipe( | ). The code is: p = 0.001 # % of lines df = pd.read_csv("protectedSearch_GPRS.txt", sep='¦', skiprows= lambda i: i&gt;0 and random.random() &gt; p) ParserWarning: Falling back to the 'python' engine because the separator encoded in utf-8 is &gt; 1 char long, and the 'c' engine does not support such separators; you can avoid this warning by specifying engine='python'. after removing the cwd from sys.path. So What exactly is it? Is it a bug? How to handle with this problem? I am trying to solve this have 2 days and I really don't know what to do more. Thank you very much and sorry for any language error.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85377341
has comment: http://stackoverflow.com/comment/85377375
has comment: http://stackoverflow.com/comment/85376908
has title: How to use read_csv in dataset with broken pipe "¦" as seprator???
tagged with: pandas
score: 1
tagged with: broken-pipe
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49185740
upvote count: 1
has answer: http://stackoverflow.com/a/49185740
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85376883
has comment: http://stackoverflow.com/comment/85378440
has comment: http://stackoverflow.com/comment/85377373

http://stackoverflow.com/a/49255167
has comment: http://stackoverflow.com/comment/85523430
has comment: http://stackoverflow.com/comment/85552456
accepted answer of: http://stackoverflow.com/q/49251306
upvote count: 2
has comment: http://stackoverflow.com/comment/85513669
has body: Here is my attempted solution to your problem. I'm making the assumption that the user can only select one row at a time. index.html Create a pretty table Number of rows Number of columns get a pretty table send selected data Result Number of elements: Hallo Here should be a table app.py from flask import Flask, render_template, request, jsonify import pandas as pd import numpy as np import json # just for reproducibility np.random.seed(0) # Initialize the Flask application app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/_get_table') def get_table(): a = request.args.get('a', type=int) b = request.args.get('b', type=int) df = pd.DataFrame(np.random.randint(0, 100, size=(a, b)), columns=['C1', 'C2']) return jsonify(number_elements=a * b, my_table=json.loads(df.to_json(orient="split"))["data"], columns=[{"title": str(col)} for col in json.loads(df.to_json(orient="split"))["columns"]]) @app.route('/_selected_data') def get_selected_data(): sel_data = request.args.get('sel_data') df_list = pd.read_html(" " + sel_data + " ") df = pd.concat(df_list) print(df) return jsonify(dummy_data=1) if __name__ == '__main__': app.run(debug=True) So basically what happens is that after a table is randomly generated, I have to create a couple of variables (drawn_table and selected) to track the table and its selected row. As of now, there's no visual change to when a row is selected but it's up to you if you want to make any CSS modifications to denote when a row is selected. When a user does click a row, the row gets a class assignment of "selected", and any other row gets deselected. This is so that JQuery will know what row is selected when sending it back to the server. Then in the send_data link, I'll find the tr (table row) element that has the "selected" class (tr.selected) and grab the html code inside this element. If the element exists, then I will send the html along with the table header info as JSON to flask. If there is…
type: Answer
has comment: http://stackoverflow.com/comment/85552291
has comment: http://stackoverflow.com/comment/85521564
has comment: http://stackoverflow.com/comment/85514958
has comment: http://stackoverflow.com/comment/85522072
has comment: http://stackoverflow.com/comment/85553011
score: 2
has comment: http://stackoverflow.com/comment/85520041
answers question: http://stackoverflow.com/q/49251306
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49182153
downvote count: 0
has body: The approach I've taken is to build a temp dictionary using update to merge dicts based on their key. I then create an output dictionary and then print that, to return to the list formatting. You could directly print {'entry': [tmpdict]} on each loop if you wanted to skip that step. I've used pprint to make the output clear, but it's obviously optional. import pprint my_data= {'id_1': [{'er': {'ip': 'myhost', 'port': 80}}, {'ef': {'ip': 'myhost', 'port': 80}}, {'er': {'app': 'falsk', 'port1': 81}}, {'ef': {'app': 'django', 'port1': 85}}], 'id_2': [{'er': {'ip': 'myhost', 'port': 80}}, {'ef': {'ip': 'myhost', 'port': 80}}, {'er': {'app': 'falsk', 'port1': 81}}, {'ef': {'app': 'django', 'port1': 85}}]} output = {} for entry, data in my_data.items(): tmpdict = {} for item in data: for k,v in item.items(): if not k in tmpdict: tmpdict[k] = {} tmpdict[k].update(v) output[entry] = [tmpdict] pprint.pprint(output)
type: Answer
has comment: http://stackoverflow.com/comment/85403635
score: 2
has comment: http://stackoverflow.com/comment/85403708
upvote count: 2
answers question: http://stackoverflow.com/q/49181337

http://stackoverflow.com/q/49248076
has answer: http://stackoverflow.com/a/49248523
accepted answer: http://stackoverflow.com/a/49248523
favorite count: 0
type: AnsweredQuestion
score: 3
upvote count: 3
has body: I'm working on a python exercise that requires getting the string return values of function. Here is the sample code that is related to the one I'm currently working on. def main(): x = 'the quick' y = 'brown fox' return x, y def function1(x, y): if x == 'the quick' and y == 'brown fox': return 'jump' else: return 'lazy' def function2(): if a == 'jump': print('good boy') else: print('bad boy') function2(*function1(*main())) I'm getting positional argument error. How to return the string properly for other function?
has answer: http://stackoverflow.com/a/49248091
possible better answer: http://stackoverflow.com/a/49248091
tagged with: python
has comment: http://stackoverflow.com/comment/85500791
has comment: http://stackoverflow.com/comment/85499802
has title: How to get the return values of function with arguments?
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85501149
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/85545739
type: Comment
comment on: http://stackoverflow.com/a/49269918
score: 0
type: AnswerComment
has text: I think your first answer is I am looking for @abarnert . I am new in this, and just know there are way like that beside general array. Thank you very much

http://stackoverflow.com/q/49142169
type: UnansweredQuestion
score: 1
tagged with: python
tagged with: c++
tagged with: ctypes
answer count: 0
has body: Is there a simple way to use a python script as a proxy for testing a C++ program? I'm currently trying to do it with ctypes, but no clue of how to make it work. As a proxy I mean a script capable of providing the program inputs and evaluating its outputs.
has title: How do I simulate inputs and outputs in a C++ code from a Python script using ctypes?
downvote count: 0
upvote count: 1
tagged with: c++11
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85290014
tagged with: python-3.x

http://stackoverflow.com/a/49221620
answers question: http://stackoverflow.com/q/49221269
type: Answer
score: -1
has body: Thanks for your comments: Indeed I have to yield request it, rather return request. Now it is working.
upvote count: 0
downvote count: 1

http://stackoverflow.com/q/49219862
type: UnansweredQuestion
answer count: 1
tagged with: django
has body: I am working on library website in which I want to display data from database which is Book name and description. But I'm not able to do that. Here is my code views.py from django.shortcuts import render from .models import * def index(request): book_list = Book.objects.all() return render(request,template_name='index.html', context={'book_list':book_list}) index.html {% extends "base_generic.html" %} {% block new_books %} {% for b in book_list %} {{ book_list }} Hello this is card text View this book {% endfor %} {% endblock %}
has title: Can't display database data in Django
tagged with: python
type: Question
score: 0
has answer: http://stackoverflow.com/a/49219881

http://stackoverflow.com/q/49208617
tagged with: python
has comment: http://stackoverflow.com/comment/85424921
tagged with: data-science
has body: I am training 3 lists of data L1, L2, L3. First i train all one them with SGDClassifier fit() and later instance by instance with partial_fit(). I I test the data with L4, L5. [The data in lists is image data and L4, L5 images are same as L2]. The predictions with fit() is correct and it is what i am expecting with partial_fit(). However the output of below code shows that both behave differently irrespective of 10,000 number of iterations for partial_fit(). Output: fit [1] #Tested L1. Predicts label as 1 correctly [2] #Tested L2. Predicts label as 2 correctly [3] #Tested L3. Predicts label as 3 correctly [2] #Tested L4. Predicts label as 2 correctly [Data close to L2] [2] #Tested L5. Predicts label as 2 correctly [Data close to L2] partial_fit [3] #Tested L1. Predicts label as 3 incorrectly [3] #Tested L2. Predicts label as 3 incorrectly [3] #Tested L3. Predicts label as 3 incorrectly [3] #Tested L4. Predicts label as 3 incorrectly [3] #Tested L5. Predicts label as 3 incorrectly Code: from sklearn import linear_model, neighbors import numpy as np L1 = [-1.98257446e-01, 1.02612168e-01, 1.06458694e-01, -4.44016755e-02, -1.25126377e-01, -1.03119195e-01, -1.89867821e-02, -5.70720285e-02, 1.65993825e-01, -4.91751768e-02, 1.35020703e-01, 5.58929071e-02, -1.79934561e-01, -1.61055699e-02, -3.67883481e-02, 7.28202313e-02, -8.59514326e-02, -1.19364798e-01, -6.03461489e-02, -9.60081592e-02, 9.60884690e-02, 7.37309158e-02, -4.95407730e-02, -2.30211094e-02, -1.59170195e-01, -3.23998809e-01, -8.31042454e-02, -7.68149048e-02, 3.26708518e-03, -5.57898730e-02, 3.65743786e-02, 3.37894261e-02, -1.61165833e-01, -9.21991318e-02, 3.83259654e-02, 1.30853474e-01, 2.16114409e-02, 1.56024918e-02, 1.63483590e-01, 3.55638564e-04, -1.01068482e-01, 3.11988778e-02, 2.79297493e-02, 3.43645960e-01, 7.68225491e-02, 7.39665255e-02, 9.03626233e-02, -4.77984771e-02, 1.46613032e-01, -2.24640951e-01, 9.37603638e-02, 1.30618230e-01, 5.41394278e-02, 3.57956365e-02, 9.59608406e-02, -1.01410612e-01, 1.15592…
has comment: http://stackoverflow.com/comment/85430677
has comment: http://stackoverflow.com/comment/85430199
has answer: http://stackoverflow.com/a/51027226
has comment: http://stackoverflow.com/comment/85430028
has comment: http://stackoverflow.com/comment/85422024
answer count: 1
downvote count: 0
upvote count: 1
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/85430291
score: 1
has comment: http://stackoverflow.com/comment/85430593
tagged with: scikit-learn
has title: sklearn partial_fit() not showing accurate results as fit()
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85430219
has comment: http://stackoverflow.com/comment/85425223
has comment: http://stackoverflow.com/comment/85428491
has comment: http://stackoverflow.com/comment/85430764
linked to: http://stackoverflow.com/q/49133188
has comment: http://stackoverflow.com/comment/85430649
linked to: http://stackoverflow.com/q/24617356
has comment: http://stackoverflow.com/comment/85422169
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85430457
has comment: http://stackoverflow.com/comment/85422214
has comment: http://stackoverflow.com/comment/85422240
has comment: http://stackoverflow.com/comment/85422081
has comment: http://stackoverflow.com/comment/85425248

timezone
tags question: http://stackoverflow.com/q/49279067
type: Tag
tag name: timezone
tags question: http://stackoverflow.com/q/49198068
tags question: http://stackoverflow.com/q/49132090
tags question: http://stackoverflow.com/q/49259661
tags question: http://stackoverflow.com/q/49238359

http://stackoverflow.com/comment/85379816
score: 0
comment on: http://stackoverflow.com/q/49187150
type: Comment
type: QuestionComment
has text: It is tick marked for everything

http://stackoverflow.com/comment/85409190
comment on: http://stackoverflow.com/q/49177228
has text: No, I would only need one, which would work for every method in the class which changes cluster allocations. The checker will always perform the same checks.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49196024
has comment: http://stackoverflow.com/comment/85397271
has comment: http://stackoverflow.com/comment/85396906
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/85397413
accepted answer of: http://stackoverflow.com/q/49195959
upvote count: 3
answers question: http://stackoverflow.com/q/49195959
type: AcceptedAnswer
downvote count: 0
has body: zip the two iterators before passing them to the template rendering engine: {% for parent, child in parents_and_childs %} where parents_and_childs = zip(all_parents, all_childs) Update You can provide the context manually (I'm guessing here what your actual parents and children should be): class SomeViewUsingBoth: template_name = '...' def get_context_data(self, **kwargs): return { 'parents_and_childs': zip(BackendModule.objects.all(), BackendNodes.objects.all()) }

http://stackoverflow.com/q/49229415
answer count: 4
has answer: http://stackoverflow.com/a/56054533
score: 7
has body: for example, csv file is as below ,(1,2,3) is header! 1,2,3 0,0,0 I read csv file using pd.read_csv and print import pandas as pd df = pd.read_csv('./test.csv') print(df[1]) it occur error key error:1 it seems like that read_csv parse header as string.. is there any way using integer type in dataframe column?
has answer: http://stackoverflow.com/a/49229800
has title: pandas read_csv parse header as string type but i want integer
downvote count: 1
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 8
accepted answer: http://stackoverflow.com/a/49229428
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49229452
has answer: http://stackoverflow.com/a/49229428
tagged with: python
has answer: http://stackoverflow.com/a/49229452

http://stackoverflow.com/comment/85522225
type: Comment
score: 0
type: QuestionComment
has text: Thanks. Yeah, ended up doing that. I asked the question as I was wondering if there was a way in the library to do this and I missed it in the docs.
comment on: http://stackoverflow.com/q/49259169

http://stackoverflow.com/q/49253249
has title: What's the time complexity for max heap?
type: AnsweredQuestion
has body: I'm trying to figure out the time complexity for this whole algorithm. Isit O(nlogn) or O(n)? I've been searching online and some says max heap it's O(nlogn) and some are O(n). I am trying to get the time complexity O(n). def max_heapify(A, i): left = 2 * i + 1 right = 2 * i + 2 largest = i if left &lt; len(A) and A[left] &gt; A[largest]: largest = left if right &lt; len(A) and A[right] &gt; A[largest]: largest = right if largest != i: A[i], A[largest] = A[largest], A[i] max_heapify(A, largest) def build_max_heap(A): for i in range(len(A) // 2, -1, -1): max_heapify(A, i) return A
tagged with: time-complexity
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85509884
possible better answer: http://stackoverflow.com/a/49254185
type: Question
accepted answer: http://stackoverflow.com/a/49263298
has answer: http://stackoverflow.com/a/49254185
tagged with: heap
has answer: http://stackoverflow.com/a/49263298
tagged with: python

http://stackoverflow.com/comment/85517902
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49254329
score: 0
has text: Possible duplicate of [How to redirect output of systemd service to a file](https://stackoverflow.com/questions/37585758/how-to-redirect-output-of-systemd-service-to-a-file)

http://stackoverflow.com/q/49133225
upvote count: 2
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85271117
tagged with: python
has answer: http://stackoverflow.com/a/49195297
tagged with: amazon-web-services
tagged with: aws-lambda
favorite count: 0
has comment: http://stackoverflow.com/comment/85359180
has comment: http://stackoverflow.com/comment/85331326
score: 2
has comment: http://stackoverflow.com/comment/85294681
has body: I would like to know about a more efficient way than renewing sts role for a cross account role when it run on lambda. By definition those roles last for 1h per default, but so far i'm doing it this way: def aws_session(role_arn, session_name): _ = boto3.client('sts') resp = _.assume_role(RoleArn=role_arn, RoleSessionName=session_name) session = boto3.Session( aws_access_key_id=response['Credentials']['AccessKeyId'], aws_secret_access_key=response['Credentials']['SecretAccessKey'], aws_session_token=response['Credentials']['SessionToken'], region_name='us-east-1') return session def lambda_handler(event, context): session = aws_session(role_arn=ARN, session_name='CrossAccountLambdaRole') s3_sts = session.resource('s3') But it terribly inefficient because instead of ~300ms, renewing credentials take more than ~1500 ms each time and as we all know, we are charged on the duration execution. Anyone could help me on how to refresh this only when the token expire ? Coz between execution, we are not sure to endup using the same "container", so how to make global variable? Thx a lot
has answer: http://stackoverflow.com/a/56061541
has comment: http://stackoverflow.com/comment/85393231
has comment: http://stackoverflow.com/comment/85271796
has comment: http://stackoverflow.com/comment/85361782
has title: AWS lambda to renew sts role at each invocation is time consuming
type: Question
has comment: http://stackoverflow.com/comment/85271818
answer count: 2
has comment: http://stackoverflow.com/comment/85373198
has comment: http://stackoverflow.com/comment/85355089
has comment: http://stackoverflow.com/comment/85271091
has comment: http://stackoverflow.com/comment/85271543

http://stackoverflow.com/comment/85405244
has text: Fantastic!! Thank you COLDSPEED!
comment on: http://stackoverflow.com/a/49199385
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49131562
score: 0
answers question: http://stackoverflow.com/q/49131510
has body: I think need: df = pd.DataFrame({0:list('abcdef'), 1:[4,1,4,5,5,4], 2:[7,0,9,4,2,3], 3:[1,0,1,0,1,0], 4:[5,3,6,0,2,4], 5:list('aaabbb')}) print (df) 0 1 2 3 4 5 0 a 4 7 1 5 a 1 b 1 0 0 3 a 2 c 4 9 1 6 a 3 d 5 4 0 0 b 4 e 5 2 1 2 b 5 f 4 3 0 4 b If want check if for some columns are 0 and 1 values only: b = ((df.values == 0) | (df.values == 1)).all(axis=0).astype(int) print (b) [0 0 0 1 0 0] If want check if for some columns are 0 and 1 values at least once: c = ((df.values == 0) | (df.values == 1)).any(axis=0).astype(int) print (c) [0 1 1 1 1 0] c = df.isin([0, 1]).any().astype(int) print (c) 0 0 1 1 2 1 3 1 4 1 5 0 dtype: int32 Timings: np.random.seed(456) df = pd.DataFrame(np.random.randint(3, size=(68,300000))) #print (df) In [272]: %timeit df.columns[df.isin([0, 1]).any()] 1 loop, best of 3: 323 ms per loop In [273]: %timeit df.columns.values[((df.values == 0) | (df.values == 1)).any(axis=0)] 10 loops, best of 3: 48.8 ms per loop
type: Answer

http://stackoverflow.com/a/49271887
has body: Change def _init_(self): to def __init__(self):(two underscore). Because this method is a constructor method, it must be writen in this form.
accepted answer of: http://stackoverflow.com/q/49271771
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49271771
upvote count: 4
type: AcceptedAnswer
downvote count: 0

phpmyadmin
tags question: http://stackoverflow.com/q/49229570
tags question: http://stackoverflow.com/q/49235332
type: Tag
tag name: phpmyadmin

http://stackoverflow.com/comment/85438229
comment on: http://stackoverflow.com/q/49213686
score: 0
has text: Have been using it for long time now. I guess VMWare free desktop version doesnt support 64-Bit Ubuntu OS.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85590877
comment on: http://stackoverflow.com/q/49253871
type: QuestionComment
has text: Thanks for confirming @Tushortz! I'll rephrase my question as an answer, in case other people get confused by this.
type: Comment
score: 0

http://stackoverflow.com/a/49222309
type: Answer
has body: This should return NaN as the default value if the key is not present: obj.__dict__.get(feature_name, float('NaN')) For Python 3.5+, NaN is available as a constant in the math package, so this would work obj.__dict__.get(feature_name, math.nan)
score: 0
answers question: http://stackoverflow.com/q/49222198

http://stackoverflow.com/a/49158859
has comment: http://stackoverflow.com/comment/85323155
has comment: http://stackoverflow.com/comment/85323013
has comment: http://stackoverflow.com/comment/85323103
has comment: http://stackoverflow.com/comment/85322639
type: Answer
has body: The code from corpcrawl's documentation page is broken: Missing : Wrong indentation Illegal characters (such as “ instead of ") Here is what it should look like (Python 2): from corpcrawl.crawler import CorpCrawl from corpcrawl.backend import Backend class MyBackend(Backend): def get_company(self, name): pass def add_company(self, comp): print "Adding %s" % str(comp) def main(): my_backend = MyBackend() crawler = CorpCrawl(cache_path = '/an/absolute/path/to/some/dir', backend = my_backend) c.crawl(years = [2011, 2012], quarters = [1, 2, 3, 4])
answers question: http://stackoverflow.com/q/49158730
has comment: http://stackoverflow.com/comment/85323189
score: 0
has comment: http://stackoverflow.com/comment/85324051

http://stackoverflow.com/q/49158145
score: 2
has body: Let's say I have a NumPy array: x = np.array([1, 2, 3, 4, 5]). How do I convert this array into the integer 12345?
upvote count: 2
answer count: 5
type: UnansweredQuestion
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/49158194
tagged with: python
has answer: http://stackoverflow.com/a/49158224
has answer: http://stackoverflow.com/a/49158389
linked to: http://stackoverflow.com/q/489999
has answer: http://stackoverflow.com/a/49158310
has answer: http://stackoverflow.com/a/49158203
has title: How to convert the elements of an array into a number ? Python
duplicate of: http://stackoverflow.com/q/489999
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/q/49234227
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: python-applymap
downvote count: 0
tagged with: pandas
answer count: 1
tagged with: dataframe
has answer: http://stackoverflow.com/a/49234290
has body: So i am reading a .xlsx file and i need to check how many variables in the xlsx file belong to each datatype in pandas and finally export it to excel. So here is the code : sheet = pd.read_excel(r"D:\Users\850034535\AnacondaProjects\Jupyter Project\Sample.xlsx",sheetname=2) alldtypes = sheet.dtypes.value_counts() alldtypes_df = list_of_all_variables.to_frame() alldtypes_df.to_excel('123.xlsx') This code gives an error: " TypeError: float() argument must be a string or a number, not 'numpy.dtype' " So then i converted the dataframe to str type, so now an additional line of code was added : alldtypes_df = alldtypes_df.applymap(str) But still it is showing me the same error and the error given in the title. Any suggestions would be much appreciated.
favorite count: 0
type: Question
has title: TypeError: Unsupported type <class 'numpy.dtype'> in write()
tagged with: python
accepted answer: http://stackoverflow.com/a/49234290
tagged with: excel

http://stackoverflow.com/comment/85279653
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49132036
has text: @DreX if the answer resolved your issue, kindly accept it (answers take up valuable time for respondents)
score: 0

http://stackoverflow.com/comment/134730305
comment on: http://stackoverflow.com/a/63448723
score: 4
has text: That project appears to be abandoned, as of 2023, there is an updated fork here: https://github.com/TylerYep/torchinfo
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49157323
upvote count: 1
tagged with: python
tagged with: dictionary
tagged with: pandas
has body: I have a list of dictionaries of dictionaries like this: d = [{'c1': {'ignore1': 'me1', 'use': 'me'}, 'c2': {'ignore2': 5., 'use': 12}}, {'c1': {'ign': 2, 'use': 'me2', 'foo': 123}, 'c2': {'ignore2': 5., 'use': 14}} ] and want to build a dataframe like this: c1 c2 0 me 12 1 me2 14 So I want to use only the key use from the nested dictionaries and the keys of the main dictionaries serve as column names. When I do pd.DataFrame.from_records(d) I receive c1 c2 0 {u'use': u'me', u'ignore1': u'me1'} {u'use': 12, u'ignore2': 5.0} 1 {u'ign': 2, u'use': u'me2', u'foo': 123} {u'use': 14, u'ignore2': 5.0} A possible solution could look like this: df2 = pd.io.json.json_normalize(d).filter(regex='.use$') df2.columns = df2.columns.str.replace('.use', "") which gives me the desired outcome. Is there a direct way to filter the desired key e.g. by using the .from_records in a different way?
has title: Create dataframe from dictionary of dictionaries using only a certain key
score: 1
has answer: http://stackoverflow.com/a/49157690
favorite count: 0
type: Question
type: UnansweredQuestion
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85480562
score: 0
has text: Have you considered using pandas? It generates the index column and does grouping for you.
type: QuestionComment
comment on: http://stackoverflow.com/q/49238332
type: Comment

http://stackoverflow.com/q/49158184
tagged with: encoding
tagged with: tweets
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85322404
has comment: http://stackoverflow.com/comment/85322468
has comment: http://stackoverflow.com/comment/85321402
tagged with: python
tagged with: text
has comment: http://stackoverflow.com/comment/85321858
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85326455
has comment: http://stackoverflow.com/comment/85321318
has answer: http://stackoverflow.com/a/50933466
tagged with: http://stackoverflow.com/tag/json
has title: json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 2)
upvote count: 1
has answer: http://stackoverflow.com/a/49158306
has comment: http://stackoverflow.com/comment/85324681
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85321302
has body: I am trying to extract the text from a .json file which i extracted. The problem is, that every time I am trying I am getting the aforementioned error(title). Here is my code: import json with open('grtwe.json.json', 'r') as f: line = f.readline() tweet = json.loads(line) print(json.dumps(tweet, indent=4)) Also tweets are greek. The first line of my .json file is this {"place": null, "geo": null, "source": "Twitter Lite", "id_str": "967369573505921024", "favorite_count": 0, "in_reply_to_status_id": null, "favorited": false, "in_reply_to_user_id": null, "in_reply_to_status_id_str": null, "contributors": null, "is_quote_status": false, "full_text": "RT @documentonews:#Novartis_gate Αποκάλυψη-σοκ: Και τρίτος νεκρός στο δρόμο της Novartis, στο Documento που κυκλοφορεί την Κυριακή | https…", "truncated": false, "user": {"notifications": false, "is_translator": false, "profile_image_url": "", "profile_background_tile": false, "id_str": "387685829", "geo_enabled": false, "profile_image_url_https":"", "statuses_count": 47093, "screen_name": "satrapis21", "is_translation_enabled": false, "followers_count": 1692, "has_extended_profile": false, "profile_background_image_url_https": "", "url": null, "follow_request_sent": false, "profile_sidebar_border_color": "FFFFFF", "profile_use_background_image": true, "profile_link_color": "D02B55", "profile_text_color": "3E4415", "description":"ξενοδοχος γκουλαγκ επενδυτης", "profile_background_color": "352726", "id": 387685829, "friends_count": 1689, "favourites_count": 3380, "created_at": "Sun Oct 09 14:01:48 +0000 2011", "default_profile": false, "translator_type": "none", "entities": {"description": {"urls": []}}, "profile_sidebar_fill_color": "99CC33", "default_profile_image": false, "listed_count": 39, "profile_banner_url": "","following": false, "utc_offset": 7200, "protected": false, "verified": false, "name": "κουληςsatrapis", "profile_background_image_url":"", "time_zone": "Vilnius", "lang": "el", "contributors_enabled": false,…
has comment: http://stackoverflow.com/comment/85329829

http://stackoverflow.com/a/49136770
has body: Use itemgetter from the operator module. from operator import itemgetter keyfunc = itemgetter(1, 0) # sort by index 1, then index 0 sorted(l, key=keyfunc) # [(11, 1), (7, 2), (12, 2), (14, 2), (13, 4)]
score: 3
upvote count: 3
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49136697
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49136697
has comment: http://stackoverflow.com/comment/85279006
type: Answer

http://stackoverflow.com/a/54717411
has body: SerpApi does not support yet knowledge graph direct answers. But you can use directly the knowledge graph in your case: $ curl https://serpapi.com/search.json?q=When+trum+was+born+? ... "knowledge_graph": { "title": "Donald Trump", "description": "Donald John Trump is the 45th and current President of the United States. Before entering politics, he was a businessman and television personality.\nTrump was born and raised in the New York City borough of Queens.", "source": { "name": "Wikipedia", "link": "https://en.wikipedia.org/wiki/Donald_Trump" }, "born": "June 14, 1946 (age 72 years), Jamaica Hospital Medical Center, New York City, NY", "height": "6′ 3″ Trending", "full_name": "Donald John Trump", "net_worth": "3.1 billion USD (2019)", "parents": "Fred Trump, Mary Anne MacLeod Trump", "education": "Fordham University (1964–1966), New York Military Academy (1964), The Kew-Forest School" }, ...
upvote count: 0
score: -3
has comment: http://stackoverflow.com/comment/113817629
answers question: http://stackoverflow.com/q/49268359
downvote count: 3
type: Answer

http://stackoverflow.com/comment/85552074
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49274280
type: AnswerComment
has text: Yes I am able to do it manually. and only a few milliseconds. As the page is already loaded, but all the data is collapsed.

http://stackoverflow.com/q/49277758
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/49278140
tagged with: user-interface
answer count: 1
tagged with: tkinter-entry
tagged with: python
has title: How can I get a Tkinter entry widget to work the same as a normal python input
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49278140
has body: I am trying to get the Tkinter entry, 'data' to work with all the variables I have set up. right now I am using a normal python input but I am trying to convert my project to a GUI project. so when I take out the input for data and attempt to use the Entry for data I get errors saying that there is no split or sort attribute and such. i would like for the GUI version of my program to work the same as the terminal version. is this possible? this is all the code that should be needed to answer the question: # imports from statistics import mode from statistics import median from tkinter import * # The Code For The GUI # class that makes the window class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.init_window() def init_window(self): self.master.title("Data Analyzer To Go") self.pack(fill=BOTH, expand=1) analyzeButton = Button(self, text="Analyze Data") dataPrompt = Label(self, text="Please enter your data") global data data = Entry(self) analyzeButton.place(x=150, y=150) data.place(x=125, y=125) dataPrompt.place(x=125, y=100) root = Tk() root.geometry("400x300") app = Window(root) root.mainloop() # variables data = input("please enter your data set: ") data = [int(n) for n in data.split(' ')] data.sort() dataLength = len(data) dataInt = list(map(int, data)) dataTotal = sum(dataInt) dataMean = dataTotal / dataLength highNumber = max(data) lowNumber = min(data) dataRange = highNumber - lowNumber Again my goal is to have the Entry do the same thing as the Input would. Any help is greatly appreciated! Thanks!
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/49163584
has body: Assuming Python 3.6. The way I usually do this is to wrap the bytes content in a BytesIO wrapper to create a file like object. And, per the boto3 docs you can use the-transfer-manager for a managed transfer: from io import BytesIO import boto3 s3 = boto3.client('s3') fileobj = BytesIO(response.content) s3.upload_fileobj(fileobj, 'mybucket', 'mykey') If that doesn't work I'd double check all IAM permissions are correct.
answers question: http://stackoverflow.com/q/49163099
has comment: http://stackoverflow.com/comment/122190032
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/122160606
upvote count: 6
score: 6

http://stackoverflow.com/a/49164090
type: Answer
has comment: http://stackoverflow.com/comment/85334239
has comment: http://stackoverflow.com/comment/85334104
answers question: http://stackoverflow.com/q/49163978
has body: Try this: checklist = ['def', 'if', 'elif'] for x in checklist: if x in line: print("",x,""," ") EDIT: try this for the case you described below import re re.compile(r'(((if|elif|else|in)\s*?)+)', re.I).sub(r'\1 ', line) ONE MORE EDIT: Try this then: checklist = ['def', 'if', 'elif'] array = line.split(' ') output = [] for x in array: if x in checklist: output.append("%s " % x) else: output.append(x) print(' '.join(output))
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85334373
has comment: http://stackoverflow.com/comment/85334465
has comment: http://stackoverflow.com/comment/85334161
score: 1
has comment: http://stackoverflow.com/comment/85333893

http://stackoverflow.com/q/49157794
answer count: 2
has answer: http://stackoverflow.com/a/49157932
type: Question
has comment: http://stackoverflow.com/comment/85320545
has answer: http://stackoverflow.com/a/49158642
type: UnansweredQuestion
tagged with: python
has body: I am trying to replace a largish if-elif block in python with something a bit more like java switch. My understanding is this should be a bit faster and we are parsing lots of data so if I can get speed improvement I will take it. However, what is happening is the code is always acting as if the key is 'deposits' even for entries that are not. The "func =" line is there to validate I am getting things correctly. I will probably not return a result to func since my goal is to fill a list with results. What am I doing wrong that the switcher.get always finds a match even when one does not exist? `def parsePollFile(thisFile): line = '' switcher = { 'deposits': deposits(line) } try: reader = csv.reader(open(thisFile, 'r')) for line in reader: try: if line[2] == "D": func = switcher.get(line[0], lambda: 'invalid key') print('key: {} -- {}\n'.format(line[0],func)) except IndexError: continue except Exception as e: print("exception {}\n".format(e)) `
has comment: http://stackoverflow.com/comment/85320660
score: 0
has title: python switch code always matches even when it should not do so

http://stackoverflow.com/a/60622928
has body: I had the same problem when attempting to sort customtreectrl items according to an arbitrary field, rather than only alphabetically as originally implemented. I don't want to duplicate the comments above, except to say a fix now exists (here, as given in @Humbalan's edit to their own question). It's probably not worth providing a full example, as @Humbalan's question has plenty of detail, but in my case I create the tree items with something like this: ctc_item = self.tree_ctc.AppendItem(ctc_parent, text = ctc_text, data = {'id_': ctc_id}) where self.tree_ctc = MyCustomTreeCtrl(self, style = some_style). My tree control and (overridden) OnCompareItems() method are: class MyCustomTreeCtrl(ctc.CustomTreeCtrl): def __init__(self, parent, style): ctc.CustomTreeCtrl.__init__(self, parent, agwStyle = style) def OnCompareItems(self, item1, item2): t1 = self.GetPyData(item1)['id_'] t2 = self.GetPyData(item2)['id_'] if t1 &lt; t2: return -1 if t1 == t2: return 0 return 1 I realise the question is a couple of years old, but this is hopefully useful.
score: 0
accepted answer of: http://stackoverflow.com/q/49135355
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49135355

http://stackoverflow.com/a/49233780
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49226358
has body: Interesting question and I am not an expert but I think you would need to do one of the following Interpolate missing features based on other features that are present Average over all possible values the missing feature might have Perhaps assume a likely range for each feature and then run prediction with all possible values of the feature. You do get combinatorial explosion in the number of models you have to fit. Whether you can live with that depends on how many missing features you want to handle and how long each prediction takes
answers question: http://stackoverflow.com/q/49226358
type: Answer
has comment: http://stackoverflow.com/comment/94533800
score: 1

group-by
tags question: http://stackoverflow.com/q/49197937
tags question: http://stackoverflow.com/q/49138119
tags question: http://stackoverflow.com/q/49141005
tags question: http://stackoverflow.com/q/49179006
tags question: http://stackoverflow.com/q/49216865
tags question: http://stackoverflow.com/q/49135821
tags question: http://stackoverflow.com/q/49272452
tags question: http://stackoverflow.com/q/49132761
tags question: http://stackoverflow.com/q/49277417
tag name: group-by
tags question: http://stackoverflow.com/q/49127387
type: Tag

http://stackoverflow.com/q/49185916
type: UnansweredQuestion
tagged with: python
answer count: 0
has body: I'm trying to find the total number of prime factors of a number using recursion. I've already implemented the code in scheme and it works fine. I am just curious what I'm doing wrong in python. It always returns none for some reason. def findFactors(n,num,counter): if(n == 1): return counter elif (n % num == 0): findFactors(n / num, 2, counter + 1) else: findFactors(n,num+1,counter) findFactors(4,2,0) should return 2 for example. Just another reminder that this works in scheme.
score: 0
linked to: http://stackoverflow.com/q/17778372
has title: Python recursive total prime factors
type: Question
tagged with: factors
tagged with: python-3.x
tagged with: recursion
has comment: http://stackoverflow.com/comment/85377414
duplicate of: http://stackoverflow.com/q/17778372
has comment: http://stackoverflow.com/comment/85378326

http://stackoverflow.com/q/49227504
has body: file 'input' (wrong columns, which is why I use header =0 in read_csv) meter overnight breakfast daytime evening std-year season-score week-score 0 1002.0 0.56 1.16 1.14 1.32 5.04 0.5 1.26 1 1003.0 0.74 0.96 0.87 1.44 2.62 0.19 1.08 2 1004.0 0.65 0.53 0.85 1.71 3.32 0.48 0.36 3 1005.0 0.49 1.22 1.09 1.42 3.57 0.56 2.54 4 1008.0 0.87 0.76 0.95 1.28 3.36 0.42 1.69 code toc = time.time() #header = 0 replaces the headers with names specified read = pd.read_csv('input', sep='\t', index_col= 0, header =0, names =['meter', 'overn_PR', 'breakf_PR', 'day_PR', 'evng_PR', 'std_year', 'week_score', 'season_score'], encoding= 'utf-8') read.drop('meter', 1, inplace=True) read['std_year'] = round(read['std_year']/4, 2) print(read.columns.values.tolist()) input = read.as_matrix() sns.tsplot(data=input, err_style='unit_traces',\ value = 'energy use [kWh]',\ time = read.columns.values.tolist()) plt.show() tic = time.time() print(tic-toc) Currently the plot only shows numbers in sequence along the x axis. It's not entirely correct to label y axis as what's shown currently as the values corresponding to x = 4, 5, 6 are standard deviations.. but leaving that aside, is there a way to label x axis with strings? I noticed it is possible to do so with date/times. Following are the error I receive at the moment. It is odd that the ValueError would be incurred at the 6th item of the read.columns.values.tolist() list..but nonetheless this is not working. Has anyone got insight into the matter? I'd deeply value, thanks. Traceback (most recent call last): File "/Users/hsl/work_dir/eclipse/ISSDA/src/GMM_ppr.py", line 32, in &lt;module&gt; time = read.columns.values.tolist()) File "/anaconda/lib/python3.5/site-packages/seaborn/timeseries.py", line 280, in tsplot x = df_c.columns.values.astype(np.float) ValueError: could not convert string to float: 'week_score'
tagged with: time-series
tagged with: seaborn
has title: ValueError: could not convert string to float - sns.tsplot, time - using strings to label x axis
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85459223
type: AnsweredQuestion
downvote count: 0
tagged with: axis-labels
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85462384
accepted answer: http://stackoverflow.com/a/49230729
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49230729

http://stackoverflow.com/comment/85553560
type: Comment
score: 0
has text: can you change this line logging.basicConfig( stream=sys.stdout )?
type: QuestionComment
comment on: http://stackoverflow.com/q/49275403

http://stackoverflow.com/q/49266926
linked to: http://stackoverflow.com/q/6663272
has answer: http://stackoverflow.com/a/49327618
has body: I'm developing some number-crunching code in the Spyder 3.2.4 IDE and as I check the results, I'm perplexed. The function code is def dictWords(dataLength): maxLength = 1. sumLengths = 2. totalWords = 2. while sumLengths &lt; dataLength: maxLength += 1 sumLengths = 2*(maxLength*2**maxLength - 2**maxLength + 1) extraLength = sumLengths - dataLength totalWords = 2**(maxLength+1) - 2 extraWords = np.ceil(extraLength/maxLength) finalWords = totalWords - extraWords return finalWords When I call it from the IPython console by dl75a = BA.dictWords(75), I get an int value of 25 for dl75a. But that is not the value I expect. If I tell the console dl75b = BA.dictWords(75.), then I get a float value of 24.25 - still not right. (I was expecting only integer values, with extraWords being the only fraction and going through np.ceil, and I read on another question that float, which I expect maxLength = 1. to generate, is automatically 64 bits.) However, if I put some script dl75 = dictWords(75) in the .py file that contains the function code and run it, then I get the float64 of 24.0 that I expected. It looks like the problem might have something to do with IPython, and could be sidestepped by calling the function from within a script and running it. But, if I try calling the function from a script in a separate file, then I get the int value of 25 again, so clearly the problem is not with IPython, but with calling the function from outside the file containing it. One thought that comes to mind is that Numpy is imported at the top of the module, as np, and maybe that makes a difference. However, I tried adding import numpy as np as the first line of the function definition and it made no difference - the calls from the other script and from IPython still produce the int of 25 and the float of 24.25. Where is the problem, causing the same function code to be interpreted differently depending on whether it is from within the .py file that contains the def or not?
tagged with: python
has comment: http://stackoverflow.com/comment/85655619
type: AnsweredQuestion
tagged with: python-2.7
score: 0
has title: Different results between def file script and calling from outside
has comment: http://stackoverflow.com/comment/85540344
tagged with: spyder
has comment: http://stackoverflow.com/comment/85558365
answer count: 1
has comment: http://stackoverflow.com/comment/85537853
tagged with: ipython
accepted answer: http://stackoverflow.com/a/49327618
type: Question
tagged with: numpy

http://stackoverflow.com/comment/85284648
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49139661
type: Comment
has text: Niggle: I'm not sure that would do what she *expects*. She may expect that if the inner `if` fails, it will fall through to the next `elif`.

http://stackoverflow.com/q/49156529
has comment: http://stackoverflow.com/comment/108238614
answer count: 1
tagged with: distribute
has title: Adding json file to MANIFEST.in and installing package results in an error
favorite count: 0
has answer: http://stackoverflow.com/a/49157055
has comment: http://stackoverflow.com/comment/85318844
type: Question
tagged with: setuptools
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85319099
has comment: http://stackoverflow.com/comment/85317929
has comment: http://stackoverflow.com/comment/85318051
upvote count: 2
score: 2
has body: My package tree looks like this: (with a few more irrelevant files) - setup.py - MANIFEST.in - mydir | - file.py - file.json setup.py: from distutils.core import setup setup( name = 'mydir', packages = ['mydir'], version = '1.2.2', description = 'desc', author = 'my name', author_email = 'my@email.com', url = 'https://github.com/myname/mydir', download_url = 'https://github.com/myname/mydir/archive/1.2.2.tar.gz', keywords = ['key1', 'key2'], classifiers = [], ) When the MANIFEST.in file was empty, the json wasn't included in the dist file. So I've added the json file to the MANIFEST.in so now it contains only: include mydir/file.json When I execute the python setup.py sdist command, the auto generated MANIFEST file contains all the necessary files, including file.json. However, as I try to install my package using pip, I get the following error: error: can't copy 'file.json': doesn't exist or not a regular file
downvote count: 0

http://stackoverflow.com/a/49187019
has body: You could use OrderedDict in order to sort the dict object as per your requirement. As this: from collections import OrderedDict from operator import itemgetter x = raw_input('Please enter a string: ').lower()#raw input for string to improve parsing. def counter(): counts = dict() words = str.split(x) for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 print(counts) d = OrderedDict(sorted(counts.items(), key=itemgetter(1),reverse =True))#Ordered Dict for sorting in reverse of keys like you like. print d return d counter() Output: OrderedDict([('father', 2), ('thou', 1), ('where', 1), ('art', 1), ('are', 1)])
has comment: http://stackoverflow.com/comment/85379514
score: 0
has comment: http://stackoverflow.com/comment/85379426
answers question: http://stackoverflow.com/q/49186864
type: Answer

http://stackoverflow.com/q/49135146
score: 1
has comment: http://stackoverflow.com/comment/85278338
has answer: http://stackoverflow.com/a/49135472
possible better answer: http://stackoverflow.com/a/49135472
has comment: http://stackoverflow.com/comment/85275355
tagged with: python
favorite count: 0
tagged with: parsing
type: Question
has answer: http://stackoverflow.com/a/49135718
has answer: http://stackoverflow.com/a/49136256
tagged with: split
answer count: 5
has answer: http://stackoverflow.com/a/49135591
downvote count: 0
upvote count: 1
has title: Split string based on predefined character types
tagged with: string
has answer: http://stackoverflow.com/a/49135569
type: AnsweredQuestion
has body: I have a predefined character->type dictionary. For example, 'a' - is a lower_case letter, 1 is a digit, ')' is a punctuation symbol etc. With the following script, I label all characters in a given string: labels='' for ch in list(example): try: l = character_type_dict[ch] print(l) labels = labels+l except KeyError: labels = labels+'o' print('o') labels For example, given "1,234.45kg (in metric system)" as input, the code produces dpdddpddwllwpllwllllllwllllllp as output. Now, I would like to split the string based on the groups. the output should look something like this: ['1',',','234','.','45','kg',' ','(','in',' ','metric',' ','system',')'] That is, it should split based on the character-type borders. Any ideas how this might be done efficiently?
accepted answer: http://stackoverflow.com/a/49136256

http://stackoverflow.com/a/49208116
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85478095
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49206395
score: 1
has body: You can first calculate all possible intersections between L1 and L2, then calculate the intersections between that set and L3 and so on. list_generator = iter([ # some generator that produces your lists [{2,7}, {2,7,8}, {2,3,6,7}, {1,2,4,5,7}], [{3,6}, {1,3,4,6,7}, {2,3,5,6,8}], [{2,5,7,8}, {1,2,3,5,7,8}, {2,4,5,6,7,8}], ]) # for example, you can read from a file: # (adapt the format to your needs) def list_generator_from_file(filename): with open(filename) as f: for line in f: yield list(map(lambda x: set(x.split(',')), line.strip().split('|'))) # list_generator would be then list_generator_from_file('myfile.dat') intersections = next(list_generator) # get first list new_intersections = set() for list_ in list_generator: for old in intersections: for new in list_: new_intersections.add(frozenset(old.intersection(new))) # at this point we don't need the current list any more intersections, new_intersections = new_intersections, set() print(intersections) Output looks like {frozenset({7}), frozenset({3, 7}), frozenset({3}), frozenset({6}), frozenset({2, 6}), frozenset({6, 7}), frozenset(), frozenset({8, 2}), frozenset({2, 3}), frozenset({1, 7}), frozenset({4, 7}), frozenset({2, 5}), frozenset({2})}, which matches what you have except for the {1,7} set you missed.
has comment: http://stackoverflow.com/comment/88162184
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85493944
has comment: http://stackoverflow.com/comment/85478723
answers question: http://stackoverflow.com/q/49206395
has comment: http://stackoverflow.com/comment/85477001

http://stackoverflow.com/q/49267094
linked to: http://stackoverflow.com/q/28423069
tagged with: spacy
score: 2
upvote count: 2
downvote count: 0
duplicate of: http://stackoverflow.com/q/28423069
has title: Where should I instantiate spaCy in a Flask application?
duplicate of: http://stackoverflow.com/q/42680357
answer count: 0
favorite count: 0
has body: When building a Flask application, what is the right place to instantiate spaCy, or, for that matter any memory-intensive object to be used in requests? The problem with spaCy is that it takes roughly 15 seconds to load and occupies quite a lot of memory. So it makes no sense to instantiate it for every request. On the upside, spaCy is presumably thread safe, so it could be instantiated once per process and used in all its threads. I'm using Flask 0.12. I'm mostly repeating the flaskr demo app, with the factory function create_app() that collects all the blueprints and returns the application object. There's also the wsgi.py that creates the variable app using the factory function. I use that file as the entry point for uWSGI. So what is the most appropriate place to instantiate spaCy, so that it is visible in every request? Should I just instantiate it in create_app() and attach it to app?
type: Question
duplicate of: http://stackoverflow.com/q/32815451
tagged with: python
type: UnansweredQuestion
tagged with: flask

http://stackoverflow.com/q/49145136
type: Question
tagged with: python-3.x
has title: How to use multiprocessing to parallelize two calls to the same function, with different arguments, in a for loop?
tagged with: for-loop
has body: In a for loop, I am calling a function twice but with different argument sets (argSet1, argSet2) that change on each iteration of the for loop. I want to parallelize this operation since one set of the arguments causes the called function to run faster, and the other set of arguments causes a slow run of the function. Note that I do not want to have two for loops for this operation. I also have another requirement: Each of these functions will execute some parallel operations and therefore I do not want to have any of the functions with either argSet1 or argSet2 be running more than once, because of the computational limited resources that I have. Making sure that the function with both argument sets is running will help me utilize the CPU cores as much as possible. Here's how do it normally without parallelization: def myFunc(arg1, arg2): if arg1: print ('do something that does not take too long') else: print ('do something that takes long') for i in range(10): argSet1 = arg1Storage[i] argSet1 = arg2Storage[i] myFunc(argSet1) myFunc(argSet2) This will definitely not take the advantage of the computational resources that I have. Here's my try to parallelize the operations: from multiprocessing import Process def myFunc(arg1, arg2): if arg1: print ('do something that does not take too long') else: print ('do something that takes long') for i in range(10): argSet1 = arg1Storage[i] argSet1 = arg2Storage[i] p1 = Process(target=myFunc, args=argSet1) p1.start() p2 = Process(target=myFunc, args=argSet2) p2.start() However, this way each function with its respective arguments will be called 10 times and things become extremely slow. Given my limited knowledge of multiprocessing, I tried to improve things a bit more by adding p1.join() and p2.join() to the end of the for loop but this still causes slow down as p1 is done much faster and things wait until p2 is done. I also thought about using multiprocessing.Value to do some communication with the functions but then I have t…
accepted answer: http://stackoverflow.com/a/49150181
downvote count: 0
has comment: http://stackoverflow.com/comment/85295483
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85300306
has answer: http://stackoverflow.com/a/49150181
tagged with: ubuntu
has answer: http://stackoverflow.com/a/49145470
has comment: http://stackoverflow.com/comment/85295401
has comment: http://stackoverflow.com/comment/85322852
possible better answer: http://stackoverflow.com/a/49145440
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/49145440
has comment: http://stackoverflow.com/comment/85295522
has comment: http://stackoverflow.com/comment/85295356
score: 1
has comment: http://stackoverflow.com/comment/85318268
favorite count: 0
tagged with: multiprocessing

http://stackoverflow.com/comment/85503757
type: Comment
has text: I found a solution in the xlrd documentation. The last option (copy and paste the date column as text) did not work for me. Thanks for sharing!
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49244388

http://stackoverflow.com/comment/85978322
comment on: http://stackoverflow.com/q/49276118
type: QuestionComment
has text: Did you check [this](https://stackoverflow.com/questions/34749806/using-moviepy-scipy-and-numpy-in-amazon-lambda) and [this](https://stackoverflow.com/questions/43877692/pandas-in-aws-lambda-gives-numpy-error)
type: Comment
score: 0

http://stackoverflow.com/comment/85534982
type: QuestionComment
has text: @ZhouYunqing I could provide you with a copy of my template if you need it. Let me know.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49176813

http://stackoverflow.com/q/49228191
type: Question
has comment: http://stackoverflow.com/comment/85463735
has comment: http://stackoverflow.com/comment/85462006
upvote count: 0
has comment: http://stackoverflow.com/comment/85463858
tagged with: scikit-learn
downvote count: 1
linked to: http://stackoverflow.com/q/48639028
favorite count: 0
has title: matplotlib : how to draw a line perfectly dividing my graph into two sections and color them
has comment: http://stackoverflow.com/comment/85463696
has comment: http://stackoverflow.com/comment/85461665
type: AnsweredQuestion
tagged with: pandas
has body: Hi so i was trying to implement my svm in python using matplotlib and was able to do so as you can see below Code: import numpy as np import matplotlib.pyplot as plt from sklearn import svm import pandas as pd from matplotlib import style style.use("ggplot") def Build_Data_Set(features = ["EstimatedSalary","Age"]): data_df = pd.DataFrame.from_csv("C:\\Users\\sidharth.m\\Desktop\\Project_sid_35352\\Intern_work\\Social_Network_Ads.csv") data_df = data_df[:100] X = np.array(data_df[features].values) y = (data_df["Purchased"] .replace("1",0) .replace("0",1) .values.tolist()) return X,y def Analysis(): X, y = Build_Data_Set() clf = svm.SVC(kernel="linear", C=1.0) clf.fit(X, y) w = clf.coef_[0] a = -w[0] / w[1] xx = np.linspace(min(X[:, 0]), max(X[:, 0])) yy = a * xx - clf.intercept_[0] / w[1] #h0 = plt.plot(xx, yy, "k-", label="age") plt.scatter(X[:, 0], X[:, 1], c=y) plt.ylabel("Age") plt.xlabel("Estimated Salary") plt.legend() plt.show() Analysis() Graph: graph for svm made using matplotlib Seeing the graph above, how do i effectively draw a line separating the purple and yellow clusters and color the backgrounds so as to show they are different.
answer count: 1
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49231212
accepted answer: http://stackoverflow.com/a/49231212
has comment: http://stackoverflow.com/comment/85463629

http://stackoverflow.com/comment/85416646
comment on: http://stackoverflow.com/q/49205663
type: QuestionComment
has text: If you're going to use the `%11` test at the end of the code, there's no reason to go through all the hoops with the recursive function first. Just do `return num % 11` and be done with it. If you're not allowed to do a mod 11 test (but can do mods of other numbers), you could use a while loop `while num > 10: num = helper(num, 0)` then return `num == 0` afterwards (outside the loop).
type: Comment
score: 0

http://stackoverflow.com/a/49236993
type: AcceptedAnswer
downvote count: 0
score: 12
upvote count: 12
type: Answer
accepted answer of: http://stackoverflow.com/q/49236905
answers question: http://stackoverflow.com/q/49236905
has comment: http://stackoverflow.com/comment/85477939
has comment: http://stackoverflow.com/comment/85477908
has body: The ~ is the operator equivalent of the __invert__ dunder which has been overridden explicitly for the purpose performing vectorized logical inversions on pd.DataFrame/pd.Series objects. s = pd.Series([True, False]) ~s 0 False 1 True dtype: bool s.__invert__() 0 False 1 True dtype: bool Note: Dunder methods must not be used directly in code, always prefer the use of the operators. Also, since you've asked, the section on Boolean Indexing describes its use. Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, &amp; for and, and ~ for not. These must be grouped by using parentheses. Bold emphasis mine.

http://stackoverflow.com/comment/85415149
type: Comment
type: QuestionComment
has text: Please either provide a few rows of your .csv file or do a `df.head()` and copy and past the result by [editing](https://stackoverflow.com/posts/49204861/edit) your post, don't paste it in the comment. Without those, your question is not answerable.
comment on: http://stackoverflow.com/q/49204861
score: 0

http://stackoverflow.com/a/49202971
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49202479
upvote count: 1
has body: I just figured it out. This is part of the python api wrapper code at C:\Users\username\AppData\Local\Continuum\anaconda2\Lib\site-packages\mljar\client\dataset.py def add_new_dataset(self, data, y, title_prefix = 'dataset-'): [...] file_path = '/tmp/dataset-'+ str(uuid.uuid4())[:8]+'.csv' [...] data.to_csv(file_path, index=False) It tries to create the dataset file at /tmp but the directory doesn't exist. In my opinion, the best way to solve this is to create a tmp folder at the root of your current drive. In my case, this is shared network drive, in which there was no /tmp folder. I also found the part of the code responsible for the missing traceback: C:\Users\username\AppData\Local\Continuum\anaconda2\Lib\site-packages\mljar\mljar.py except Exception as e: print 'Ups, %s' % str(e)
type: Answer
answers question: http://stackoverflow.com/q/49202479
score: 1

http://stackoverflow.com/comment/85452884
type: QuestionComment
comment on: http://stackoverflow.com/q/49160034
score: 0
has text: This example works fine for me. Does the problem reproduce for any publicly available IP?
type: Comment

parsing
tags question: http://stackoverflow.com/q/49176400
tags question: http://stackoverflow.com/q/49203278
tags question: http://stackoverflow.com/q/49175933
tags question: http://stackoverflow.com/q/49186267
tags question: http://stackoverflow.com/q/49210018
tags question: http://stackoverflow.com/q/49128661
tags question: http://stackoverflow.com/q/49180932
tag name: parsing
tags question: http://stackoverflow.com/q/49140416
tags question: http://stackoverflow.com/q/49220179
tags question: http://stackoverflow.com/q/49229096
tags question: http://stackoverflow.com/q/49177723
tags question: http://stackoverflow.com/q/49269034
tags question: http://stackoverflow.com/q/49213003
tags question: http://stackoverflow.com/q/49135146
tags question: http://stackoverflow.com/q/49188488
tags question: http://stackoverflow.com/q/49126348
tags question: http://stackoverflow.com/q/49181878
tags question: http://stackoverflow.com/q/49143128
tags question: http://stackoverflow.com/q/49122952
tags question: http://stackoverflow.com/q/49197088
tags question: http://stackoverflow.com/q/49219454
tags question: http://stackoverflow.com/q/49245474
tags question: http://stackoverflow.com/q/49175624
tags question: http://stackoverflow.com/q/49245314
type: Tag
tags question: http://stackoverflow.com/q/49165733

http://stackoverflow.com/comment/85382385
has text: try with "from A import B" might make sense......
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49185593

http://stackoverflow.com/comment/85491160
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49241854
type: Comment
has text: It depends on what your use-case is. You can explode the dict using pyspark and get columns for each relationship in the data struct. Alternatively you can assign a schema beforehand and expect that transformation in your new object.

http://stackoverflow.com/q/49143411
has answer: http://stackoverflow.com/a/49143509
has comment: http://stackoverflow.com/comment/85292408
tagged with: time
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49143453
tagged with: sum
has title: How to add a list of datetime?
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/85292424
has comment: http://stackoverflow.com/comment/85292474
score: 0
has answer: http://stackoverflow.com/a/49143650
tagged with: list
has comment: http://stackoverflow.com/comment/85292463
answer count: 3
has body: ['00:00:36', '00:02:54', '00:06:06', '00:07:28', '00:07:57', '00:10:44', '00:11:34', '00:14:57', '00:15:03', '00:17:01', '00:17:13', '00:18:28', '00:18:50', '00:23:41', '00:25:47'] 1) I have a datetime.datetimeobject (basically time stamp) but I just pulled out HH:MM:SS and printed it here. How can I add this(datetime.datetime object)? [{'Start Time': '2017-01-01 00:00:36'}, {'Start Time': '2017-01-01 00:02:54'}, {'Start Time': '2017-01-01 00:06:06'}, {'Start Time': '2017-01-01 00:07:28'}, {'Start Time': '2017-01-01 00:07:57'}, {'Start Time': '2017-01-01 00:10:44'}, {'Start Time': '2017-01-01 00:11:34'}, {'Start Time': '2017-01-01 00:14:57'}, {'Start Time': '2017-01-01 00:15:03'}, {'Start Time': '2017-01-01 00:17:01'}, {'Start Time': '2017-01-01 00:17:13'}, {'Start Time': '2017-01-01 00:18:28'}, {'Start Time': '2017-01-01 00:18:50'}, {'Start Time': '2017-01-01 00:23:41'}, {'Start Time': '2017-01-01 00:25:47'}] 2) Should I convert it all to seconds add them out and return to time or is there a better and neat way to do this? 3) '00:00:36' this value becomes a string right? output (1) should be in HH:MM:SS format. output (2) DD:HH:MM:SS format.
has comment: http://stackoverflow.com/comment/85292569
type: Question
has comment: http://stackoverflow.com/comment/85292560

http://stackoverflow.com/q/49182170
tagged with: pandas
score: 1
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49183163
possible better answer: http://stackoverflow.com/a/49183163
type: AnsweredQuestion
tagged with: python-3.x
answer count: 2
has body: I'm trying to optimize my code and save time. My current solution works, but is redundant and not maintainable when I apply similar functions to multiple dataframes. How do I automate the creation of new column based on conditions of another column? Some data: import pandas as pd df = {'Column1': [1,2,3,4,5], 'Column2': ["A","B","C","D","E"]} df = pd.DataFrame(df, columns=['Column1','Column2']) df Column1 Column2 0 1 A 1 2 B 2 3 C 3 4 D 4 5 E Method 1: Works, but not maintainable each time I need to do something similar with new dataframes # create band if column 2 contains A-C df['Col_2_Band V1'] = "D-E" df['Col_2_Band V1'][df['Column2'].isin(['A','B','C'])] = "A-C" df Column1 Column2 Col_2_Band V1 0 1 A A-C 1 2 B A-C 2 3 C A-C 3 4 D D-E 4 5 E D-E Method 2: Can't get to work def applyV2(row): row['Col_2_Band V2'] = "D-E" row['Col_2_Band V2'][df['Column2'].isin(['A','B','C'])] = "A-C" return row df = df.apply(applyV2, axis=1) **Error:** --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-8-cf5d31427d02&gt; in &lt;module&gt;() 4 return row 5 ----&gt; 6 df = df.apply(applyV2, axis=1) C:\Users\cfeld\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds) 4852 f, axis, 4853 reduce=reduce, -&gt; 4854 ignore_failures=ignore_failures) 4855 else: 4856 return self._apply_broadcast(f, axis) C:\Users\cfeld\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py in _apply_standard(self, func, axis, ignore_failures, reduce) 4948 try: 4949 for i, v in enumerate(series_gen): -&gt; 4950 results[i] = func(v) 4951 keys.append(v.name) 4952 except Exception as e: &lt;ipython-input-8-cf5d31427d02&gt; in applyV2(row) 1 def applyV2(row): 2 row['Col_2_Band V2'] = "D-E" ----&gt; 3 row['Col_2_Band V2'][df['Column2'].isin(['A','B','C'])] = "A-C" 4 return row 5 TypeError: ("'str' object does not support item ass…
has answer: http://stackoverflow.com/a/49185303
accepted answer: http://stackoverflow.com/a/49185303
downvote count: 0
tagged with: loops
upvote count: 1
favorite count: 0
has title: Applying Pandas Create Column Method With a Function
type: Question

http://stackoverflow.com/a/49219041
score: 0
has body: from math import exp def epsilon(t): epsilon = (1 - exp(-pow(t, 4))) return epsilon def r(t): print(2) t=epsilon(t) r = pow( ( t- 16) / 4, 1/4) return r print(r(0)) Or from numpy import exp def epsilon(t): epsilon = (1 - exp(-pow(t, 4))) return epsilon def r(t): print(2) t=epsilon(t) r = pow( float( t- 16) / 4, 1/4) return r print(r(0))
answers question: http://stackoverflow.com/q/49218648
type: Answer

http://stackoverflow.com/comment/85353272
comment on: http://stackoverflow.com/q/49173597
score: 0
has text: I think I need something different to both - I want your version with all the columns, but without rows with lower values - just the max rows
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49184033
upvote count: 1
tagged with: python
favorite count: 0
type: AnsweredQuestion
score: 1
tagged with: math
accepted answer: http://stackoverflow.com/a/49186164
has body: I'm trying to convert a range of numbers to a another range (in an exponential way). I'm trying to do this in python. I don't have a background in mathematics (nor a formal education in computer science actually), so I'll do my best to explain my question in a clear manner. Let's say I have the following ranges [A,B]: [-10 , 25] [-35 , -1] [0 , 100] I want to normalize them to the following ranges[C,D]: [0 , 3] [1 , 5] [0 , 100] I could of course normalize those numbers through this: normalized = (x-min(x))/(max(x)-min(x)) That would give me a (linear) normalized response between 0 and 1. If I want to get an exponential result, I'd feed the normalized result through a function: Now my question: I want to create a function where I can input both ranges ([A,B] and [C,D]) where at the extremes: A = C B = D and the results grow exponentially. Again, here my mathematics are lacking. Above image example doesn't give y = 100 when x = 100. So I don't know how to determine the exponential formula considering changing input. So in short: I want to choose different strengths of exponentials growth while using different variables as input, but always have y = max_result when x = max_input and y = min_result when x = min_input. An example: Input: # Range of input values AB = [0,100] # Range of output values CD = [0,1000] # Math function for exponential formula_input = # Some formula made with range [0,100] on both X and Y x1 = 10 x2 = 20 x3 = 50 x4 = 90 Output: formula = 1.072^x y1 = 2.004 y2 = 4.017 y3 = 32.34 y4 = 521.832 I hope this question is clear enough. Thanks in advance for helping!
has answer: http://stackoverflow.com/a/49186164
possible better answer: http://stackoverflow.com/a/49184405
type: Question
has title: Converting a range of integers exponentially to another range
answer count: 2
has answer: http://stackoverflow.com/a/49184405
downvote count: 0

http://stackoverflow.com/comment/85459408
type: QuestionComment
comment on: http://stackoverflow.com/q/49227963
score: 2
has text: The simplest way is to create an empty list `result = []`, and then `result.append(x)` instead of `return x`, and then after the whole loop, `return result`.
type: Comment

http://stackoverflow.com/q/49121491
downvote count: 0
has answer: http://stackoverflow.com/a/49127283
accepted answer: http://stackoverflow.com/a/49127283
favorite count: 0
tagged with: networkx
type: Question
score: 3
tagged with: python
tagged with: graph-visualization
has comment: http://stackoverflow.com/comment/85270205
has title: Issue with spacing nodes in networkx graph
type: AnsweredQuestion
tagged with: python-3.x
has body: I'm trying to make a networkx graph with several hundred edges: def generate_network_graph(graph): visual_graph = networkx.Graph() for edge in graph.edges: visual_graph.add_edge(edge.actor.name, edge.movie.title) plt.figure(3, figsize=(30, 30)) networkx.spring_layout(visual_graph, k=0.9, iterations=20) networkx.draw_spring(visual_graph) plt.show() No matter how much I seem to increase k, however, my graph comes out looking like a clustered mess: I'm not sure what else to do keep the nodes from overlapping; I've tried a range of k values from 0.0 to 5.0. I thought about decreasing the size of the nodes, but I'm not sure if that would just make the graph less readable. Not only that, but regenerating this graph takes an abysmal amount of time, ~15 minutes. Am I simply not using the right graph library for the job? Or is there something I can modify to make my graph clearer.
upvote count: 3
has comment: http://stackoverflow.com/comment/139258433
answer count: 1

http://stackoverflow.com/a/49192665
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/49178659
downvote count: 0
score: 4
has body: The problem was that I wasn't importing the class definitions for Blinds and Datum anywhere, so they weren't evaluated! Before I split them up into different files, I had imported them to get to Base. Thanks to @IljaEverilä for this answer!
has comment: http://stackoverflow.com/comment/102943584

http://stackoverflow.com/q/49162937
upvote count: 2
has comment: http://stackoverflow.com/comment/85332352
has body: I am using the following models and forms to build two dropdown menus. The City menu is dependent upon the Country menu. Right now my code does the filtering and ordering correctly. However, distinct() is not working. I've played around with the ordering of the queries for a while and it still doesn't work. How can I fix this? models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Person(models.Model): country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name forms.py from django import forms from .models import Person, City class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('country', 'city') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id=\ country_id).order_by().distinct() except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name') views.py from django.shortcuts import render from django.views.generic import ListView, CreateView, UpdateView from django.urls import reverse_lazy from .models import Person, City from .forms import PersonForm class PersonListView(ListView): model = Person context_object_name = 'people' class PersonCreateView(CreateView): model = Person form_class = PersonForm success_url = reverse_lazy('person_changelist') class PersonUpdateView(UpdateView): model = Person form_class = PersonForm s…
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/85331881
downvote count: 0
tagged with: django
tagged with: django-forms
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85331580
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49163937
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/85331834
has title: Queryset distinct() with filter() and order_by() does not work
score: 2

http://stackoverflow.com/comment/85555049
score: 0
type: AnswerComment
has text: @tobias_k I'm sure I'm capable of spelling gender
comment on: http://stackoverflow.com/a/49276296
type: Comment

http://stackoverflow.com/q/49213314
downvote count: 2
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49213334
accepted answer: http://stackoverflow.com/a/49213334
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has title: Accessing the value of a key in a nested JSON converted to a dictionary in python
type: AnsweredQuestion
tagged with: python-3.x
score: 0
has body: I wish to access the value of 'elevation' i.e. 1608.637939453125 and store it into the variable 'g'. Below is the code import requests, json r = requests.get(api link) r= json.loads(r.text) g=r['results']['elevation'] the above code returns this error TypeError: list indices must be integers or slices, not str Here's the dictionary data { "results" : [ { "elevation" : 1608.637939453125, "location" : { "lat" : 39.7391536, "lng" : -104.9847034 }, "resolution" : 4.771975994110107 } ], "status" : "OK" }
upvote count: 2

http://stackoverflow.com/comment/85441726
type: Comment
has text: Did you try using a simple BytesIO buffer?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49215675

http://stackoverflow.com/q/49237522
answer count: 3
has answer: http://stackoverflow.com/a/69095597
possible better answer: http://stackoverflow.com/a/49237841
downvote count: 0
has answer: http://stackoverflow.com/a/49237841
score: 30
favorite count: 0
type: Question
upvote count: 30
has answer: http://stackoverflow.com/a/49238256
tagged with: matplotlib
has title: How to annotate end of lines using python and matplotlib?
tagged with: python
type: AnsweredQuestion
has body: With a dataframe and basic plot such as this: import pandas as pd import numpy as np import matplotlib.pyplot as plt np.random.seed(123456) rows = 75 df = pd.DataFrame(np.random.randint(-4,5,size=(rows, 3)), columns=['A', 'B', 'C']) datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist() df['dates'] = datelist df = df.set_index(['dates']) df.index = pd.to_datetime(df.index) df = df.cumsum() df.plot() What is the best way of annotating the last points on the lines so that you get the result below?
accepted answer: http://stackoverflow.com/a/49238256

http://stackoverflow.com/comment/85363261
comment on: http://stackoverflow.com/q/49178906
score: 0
has text: I updated the question. In the first version, constructor is called twice.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49278005
has comment: http://stackoverflow.com/comment/85558543
has comment: http://stackoverflow.com/comment/85558450
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/85576609
has comment: http://stackoverflow.com/comment/85559502
has comment: http://stackoverflow.com/comment/85558552
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85567818
has comment: http://stackoverflow.com/comment/85558455
has comment: http://stackoverflow.com/comment/85567918
accepted answer: http://stackoverflow.com/a/49278909
has comment: http://stackoverflow.com/comment/85600175
answer count: 1
has answer: http://stackoverflow.com/a/49278909
has comment: http://stackoverflow.com/comment/85603244
has comment: http://stackoverflow.com/comment/85591323
has comment: http://stackoverflow.com/comment/85591378
tagged with: re-python
type: Question
has body: I'm working with long strings and I need to replace with '' all the combinations of adjacent full stops . and/or colons :, but only when they are not adjacent to any whitespace. Examples: a.bcd should give abcd a..::.:::.:bcde.....:fg should give abcdefg a.b.c.d.e.f.g.h should give abcdefgh a .b should give a .b, because . here is adjacent to a whitespace on its left, so it has not to be replaced a..::.:::.:bcde.. ...:fg should give abcde.. ...:fg for the same reason Well, here is what I tried (without any success). Attempt 1: s1 = r'a.b.c.d.e.f.g.h' re.sub(re.search(r'[^\s.:]+([.:]+)[^\s.:]+', s1).group(1), r'', s1) I would expect to get 'abcdefgh' but what I actually get is r''. I understood why: the code re.search(r'[^\s.:]+([.:]+)[^\s.:]+', s1).group(1) returns '.' instead of '\.', and thus re.search doesn't understand that it has to replace the single full stop . rather than understanding '.' as the usual regex. Attempt 2: s1 = r'a.b.c.d.e.f.g.h' re.sub(r'([^\s.:]*\S)[.:]+(\S[^\s.:]*)', r'\g&lt;1&gt;\g&lt;2&gt;', s1) This doesn't work as it returns a.b.c.d.e.f.gh. Attempt 3: s1 = r'a.b.c.d.e.f.g.h' re.sub(r'([^\s.:]*)[.:]+([^\s.:]*)', r'\g&lt;1&gt;\g&lt;2&gt;', s1) This works on s1, but it doesn't solve my problem because on s2 = r'a .b' it returns a b rather than a .b. Any suggestion?
has title: Python regex: how to achieve this complex replacement rule?

http://stackoverflow.com/q/49183973
answer count: 3
type: UnansweredQuestion
score: 1
downvote count: 0
upvote count: 1
has body: I would like to print out these results with my code: {'name': 'asm0', 'size': '1024000'} {'name': 'asm1', 'size': '1024000'} {'name': 'asm2', 'size': '1024000'} But it appears like this.. {'name': 'asm0', 'size': '1024000'} {'name': 'asm01', 'size': '1024000'} {'name': 'asm012', 'size': '1024000'} Please see my sample code below and let me know how can I fix it.. #----------------------------------- !/usr/bin/python vdisks = { "name": "asm", "size": "1024000" } for i in range(3): new_vdisks = vdisks new_vdisks["name"] = vdisks["name"] + str(i) print new_vdisks #-----------------------------------
has answer: http://stackoverflow.com/a/49184063
favorite count: 0
has title: How can I edit an attribute?
has answer: http://stackoverflow.com/a/49184091
tagged with: python
has answer: http://stackoverflow.com/a/49184049
type: Question

http://stackoverflow.com/a/77174881
answers question: http://stackoverflow.com/q/49224770
type: Answer
has body: Just going to throw out this solution. This will allow you to define a message with the class definition. First a base exception class: class DefaultException(Exception): """A class to define a default message with the exception definition""" MSG = '' def __init__(self, *args, message=None, **kwargs): if message is None: message = self.MSG super().__init__(message) Now we can define exceptions with their default messages easily: class CustomException(DefaultException): """This is just an example exception""" MSG = 'This is a default message!' You can even modify the DefaultException to format the default message using the kwargs, if you want there to be some formatting as well
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/85431436
score: 0
has text: Is your classification binary or multi-class? And JFYI `in_top_k` is a dangerous choice of accuracy measure - https://stackoverflow.com/q/48993004/712995
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49210520

http://stackoverflow.com/q/49221481
has body: Im trying to present stimuli on screen in psychopy. Is there a way to set (0,0) to be top/bottom left instead of center?
has title: Set (0,0) location in psychopy to be left
type: UnansweredQuestion
tagged with: screen
downvote count: 0
upvote count: 1
tagged with: python
tagged with: psychopy
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/49221582
favorite count: 0
type: Question

http://stackoverflow.com/comment/85314241
type: QuestionComment
has text: ...so how does your L array look like?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49151557

http://stackoverflow.com/comment/85540547
type: QuestionComment
score: 0
has text: Yes, I am using Pandas Dataframe.
comment on: http://stackoverflow.com/q/49268554
type: Comment

http://stackoverflow.com/comment/85252504
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49122567
has text: @lieblos: The language spec doesn't provide guarantees in most cases (the Python tutorial mentions that slicing a `list` shallow copies, but otherwise doesn't get into it). Stuff like `str` slices being copies vs. views isn't a language guarantee; at one point they considered making `str` slices views, but decided against it largely because of the implicit, non-intuitive keep-alive effect (slicing two characters out of a 1 GB `str` causing the 1 GB `str` to live until the slice is cleaned up). Mostly I just read the Python bug tracker, the PEPs, and the What's New pages for each release.

http://stackoverflow.com/q/49264076
has answer: http://stackoverflow.com/a/49264251
tagged with: python
tagged with: sparse-matrix
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/49264251
score: 1
downvote count: 0
linked to: http://stackoverflow.com/q/49254111
has body: I want to divide each row of the csr_matrix by the number of non zero entries in that row. For example : Consider a csr_matrix A: A = [[6, 0, 0, 4, 0], [3, 18, 0, 9, 0]] Result = [[3, 0, 0, 2, 0], [1, 6, 0, 3, 0]] What's the shortest and efficient way to do it ?
upvote count: 1
tagged with: scipy
accepted answer: http://stackoverflow.com/a/49264259
favorite count: 0
has title: Normalize scipy sparse matrix with number of nonzero elements
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49264259

http://stackoverflow.com/a/49217429
type: Answer
score: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49217347
downvote count: 1
has body: programming is not magic, you have a file path i.e: c://myfolder/song.mp3 - assuming your music files are named after the song, you must parse the url for the song name and set the status bar title/label to the song you are currently playing. I suggest you take a entry lvl course on python before mixing qt frameworks into it.

http://stackoverflow.com/comment/85399776
comment on: http://stackoverflow.com/q/49197240
type: Comment
has text: Try running it in the console, screen shot the console, and then send us the screen shot.
type: QuestionComment
score: 0

http://stackoverflow.com/a/49193071
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49192901
type: Answer
has body: As @DavidG mentioned in his answer, you are trying to access the first element of an empty list by doing: score = [] // [...] score[0] // anything with this But even when correcting this, you should consider the following: You are iterating through name (as you use name[counter] in your loop). However, for some reason, you are basing counter's range on len(home). What if home has more elements than name? Also, is there any reason why those two blocks don't share the same logic? score[0].append = int(input("Judge 1: ")) // here ^^^^^^^ score[0] = validate(0,10,score[0]) score[1] = int(input("Judge 2: ")) // ^-- nothing there score[1] = validate(0,10,score[1]) should be (for example): score.append(validate(0,10,int(input("Judge 1: ")))) score.append(validate(0,10,int(input("Judge 2: "))))
upvote count: 2

http://stackoverflow.com/comment/85457298
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49226665
has text: Found it: https://www.w3.org/TR/unicode-xml/#Suitable

http://stackoverflow.com/comment/85464691
type: QuestionComment
comment on: http://stackoverflow.com/q/49229010
has text: That didn't answer my question, but okay.
type: Comment
score: 0

http://stackoverflow.com/q/49213832
upvote count: 1
score: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49213933
has body: I am trying to update a table titled 'stats' using sqlite3 and python. The table has the structure [username, correct, total]. This is the code I'm using: conn = sqlite3.connect(stats_db) # connect to that database (will create if it doesn't already exist) c = conn.cursor() # make cursor into database (allows us to execute commands) outs = "" try: c.execute('''CREATE TABLE stats (username text,correct int, total int);''') # run a CREATE TABLE command outs = "database constructed" except: things = c.execute('''SELECT * FROM stats;''').fetchall() output_list = [] for x in things: output_list.append(x) new_correct = output_list[0][1] + int(correct) new_total = output_list[0][2] + 1 c.execute('''UPDATE stats SET correct = (?) and total = (?) where username = (?);''',(new_correct, new_total, username)) things = c.execute('''SELECT * FROM stats;''').fetchall() # outs = "Things:\n" output_list = [] for x in things: output_list.append(x) outs += str(output_list) conn.commit() # commit commands conn.close() # close connection to database return outs However, the values in the table never get updated. new_correct and new_total are returning correctly. Also, is there a way to update without first calling the previous values? I just need to increment total by 1 and correct by either 0 or 1 depending on what the input of correct is?
has answer: http://stackoverflow.com/a/49213933
type: Question
tagged with: python
has title: Updating table using sqlite3 and python
type: AnsweredQuestion
tagged with: sqlite
downvote count: 0

http://stackoverflow.com/q/49131693
has comment: http://stackoverflow.com/comment/85270718
upvote count: 1
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85270636
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/85747085
favorite count: 0
tagged with: command-prompt
score: 1
has title: Error while trying to install JupyterLab with pip
tagged with: jupyter-notebook
has comment: http://stackoverflow.com/comment/85271195
type: Question
linked to: http://stackoverflow.com/q/25981703
tagged with: jupyter-lab
has body: I have just installed Anaconda on a new machine (Microsoft Windows 10 Enterprise, 64-bit). As I try to install JupyterLab with pip, I always get the following error: Collecting ipykernel (from notebook&gt;=4.3.1-&gt;jupyterlab) Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)'),)': /simple/ipykernel/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)'),)': /simple/ipykernel/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)'),)': /simple/ipykernel/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)'),)': /simple/ipykernel/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)'),)': /simple/ipykernel/ Could not fetch URL https://pypi.python.org/simple/ipykernel/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/ipykernel/ (Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)'),)) - skipping Could not find a version that satisfies the requirement ipykernel (from notebook&gt;=4.3.1-&gt;jupyterlab) (from versions: ) No matching distribution found for ipykernel (from notebook&gt;=4.3.1-&gt;jupyterlab) I see that ipykernel is involved, but what is the problem here?
answer count: 0

http://stackoverflow.com/comment/85282131
type: Comment
comment on: http://stackoverflow.com/a/49132841
has text: When I run it twice I get duplicate entries. Can you help me with how I don't insert already existing videos, but only add new videos. Make it skip already inserted entires.
score: 0
type: AnswerComment

http://stackoverflow.com/q/49208875
has comment: http://stackoverflow.com/comment/85422343
duplicate of: http://stackoverflow.com/q/35567753
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85422258
has body: I'm using click in Python3: @click.option('--param1', help="param1") @click.option('--param2', help="param2") @click.option('--from', help="from where..") I want to use it in my main: def main(param1, param2, from): .. It works fine for param1 and param2 but for from I receive an error: SyntaxError: invalid syntax formal parameter name expected I think because the word from will probably also have another usage in python? How can I make it work so I can use 'from' as a parameter?
linked to: http://stackoverflow.com/q/35567753
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85422375
tagged with: python-3.x
has title: Parameter 'from' in python3: formal parameter name expected
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85422277
has comment: http://stackoverflow.com/comment/85422304

http://stackoverflow.com/a/53860954
answers question: http://stackoverflow.com/q/49210695
downvote count: 0
type: Answer
has body: Piggybacking off Paul Brodersen's answer, if you want different nodes to be in the foreground and background, I think you should do the following: For all nodes that belong in the same layer, draw the subgraph corresponding to the nodes, and set the , as follows: pos = {...} # some dictionary of node positions, required for the function below H = G.subgraph(nbunch) collection = nx.draw_networkx_nodes(H, pos) collection.set_zorder(zorder) Do this for every group of nodes that belong in the same level. It's tedious, but it will do the trick. Here is a toy example that I created based on looking up this question as part of my own research import matplotlib as mpl mpl.use('agg') import pylab import networkx as nx G = nx.Graph() G.add_path([1, 2, 3, 4]) pos = {1 : (0, 0), 2 : (0.5, 0), 3 : (1, 0), 4 : (1.5, 0)} for node in G.nodes(): H = G.subgraph([node]) collection = nx.draw_networkx_nodes(H, pos) collection.set_zorder(node) pylab.plot([0, 2], [0, 0], zorder=2.5) pylab.savefig('nodes_zorder.pdf', format='pdf') pylab.close() This makes a graph, and then puts the each node at a successively higher level going from left to right, so the leftmost node is farthest in the background and the rightmost node is farthest in the foreground. It then draws a straight line whose zorder is 2. As a result, it comes in front of the two left nodes, and behind the two right nodes. Here is the result.
score: 3
upvote count: 3

http://stackoverflow.com/comment/85439318
has text: @DhavalThakkar One way to do it: in the `parse` function extract the name of the currency from `response.url` and add it to the file name. Best is to write an [item pipeline](http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html) and put the `data_to_csv` function in there telling the scraper where to save each item.
type: Comment
comment on: http://stackoverflow.com/a/49214674
score: 0
type: AnswerComment

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

http://stackoverflow.com/a/49183843
score: 1
upvote count: 1
downvote count: 0
has body: In case you want to replace last occurrence of brackets even if they are not at the end of the string: *AWL* (GREATER) MINDS LIMITED (CLOSED) END you can use tempered greedy token: &gt;&gt;&gt; re.sub(r"\([^)]*\)(((?!\().)*)$", r'\1', '*AWL* (GREATER) MINDS LIMITED (CLOSED) END') # =&gt; '*AWL* (GREATER) MINDS LIMITED END' Demo Explanation: \([^)]*\) matches string in brackets (((?!\().)*)$ assures that there are no other opening bracket until the end of the string (?!\() is negative lookeahead checking that there is no ( following . matches next char (that cannot be ( because of the negative lookahead) (((?!\().)*)$ the whole sequence is repeated until the end of the string $ and kept in a capturing group we replace the match with the first capturing group (\1) that keeps the match after the brackets
answers question: http://stackoverflow.com/q/49183568
type: Answer

http://stackoverflow.com/q/49191309
has comment: http://stackoverflow.com/comment/85387801
type: AnsweredQuestion
score: 1
has body: A data file was getting corrupted when I terminated the program and realised that it was never properly closed. It is quite critical that it does not get corrupted. So I added a statement to close the file. Now, it seems like the file gets opened twice and then closed. That's one operation too many. There are of course many read-write operations in-between but it should only open and close the files once. Here is what I have done to the standarize web.py template: import web import pandas as pd store = pd.HDFStore('data_file.h5') urls = ( '/', 'index' ) class index: def __init__(self): self.__df = store['df'] def GET(self): # several read-write, and modify operations on self.__df return "Hello, world!" if __name__ == "__main__": try: app = web.application(urls, globals()) app.run() finally: store.close() Now, if I move the line which opens the store down inside the try statement at the bottom, it complains since it compiles the class but I can't find the variable store. I tried initialising store with None at the top but it didn't work either. Then I tried putting that line up at the top in the function and calling it from the bottom, however, that didn't bring it into scope. I was thinking of making it a global variable, which would probably do the trick, is that the right approach?
has answer: http://stackoverflow.com/a/49212127
has comment: http://stackoverflow.com/comment/85388559
tagged with: python
has comment: http://stackoverflow.com/comment/85388306
has comment: http://stackoverflow.com/comment/85390108
has comment: http://stackoverflow.com/comment/85390354
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49212127
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85388249
linked to: http://stackoverflow.com/q/42305098
has title: where to open and close file in web.py
tagged with: web.py

http://stackoverflow.com/comment/85465728
has text: @SamuelMuiruri yes it tried . i am getting an error saying **Error: Destination path 'c:\destination\.' already exists**
comment on: http://stackoverflow.com/q/49231054
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49172828
upvote count: 5
downvote count: 0
tagged with: python
has body: I am trying to calculate an fft with Python. I am using the function fft.fft and I am applying it to a simple Sinusoidal signal. Here is my code: import numpy as np import matplotlib.pyplot as plt frames=100 fps=1000 t=np.linspace(0, frames, frames)/fps x=np.sin(2*np.pi*80*t)+1 plt.plot(t, x, 'o-') plt.title('seno') plt.ylabel('sin') plt.xlabel('time $s$') plt.grid() plt.show() #calculating the fft sin_fft=np.fft.fft(x) #calculating the absolute value sin_fft_abs=np.ones(len(sin_fft)) for i in range(len(sin_fft)): sin_fft_abs[i]=np.sqrt((sin_fft[i].real**2)+(sin_fft[i].imag**2)) sin_fft_final=sin_fft_abs/frames #calculating the frequencies inc=fps/frames freq=np.linspace(0, fps-inc, fps/inc) plt.plot(freq, sin_fft_final, 'o-') plt.xlim(xmax=fps/2) plt.title('seno fft') plt.ylabel('sin fft') plt.xlabel('f $Hz$') plt.grid() plt.show() It can find the right offset (1 in this simple case), but the amplitude of the peak corresponding to the Sinus Frequency (80 in this case) is half the Amplitude of the Signal, always. I have no idea why it finds the correct Offset, but not the correct Amplitude! I would be grateful if somebody could help me, Thanks a lot, Francesca
has answer: http://stackoverflow.com/a/49173672
answer count: 1
has title: Wrong Amplitude of the fft of a signal
favorite count: 0
tagged with: fft
type: Question
type: UnansweredQuestion
score: 5

http://stackoverflow.com/comment/85271380
type: Comment
comment on: http://stackoverflow.com/q/49129065
type: QuestionComment
score: 0
has text: Sure, i've updated the answer - thanks

dbus
type: Tag
tags question: http://stackoverflow.com/q/49153583
tag name: dbus

http://stackoverflow.com/comment/85502098
has text: Please mention reason for down vote , It will help him to improve his question next time.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49249356

http://stackoverflow.com/comment/85397852
has text: Hm, you appear to indeed have `google-auth` installed. Do you see the `google/auth/__init__.py` and `google/auth/app_engine.py` files under `lib`?
comment on: http://stackoverflow.com/q/49194575
score: 0
type: Comment
type: QuestionComment

quantlib
tags question: http://stackoverflow.com/q/49199836
type: Tag
tag name: quantlib

http://stackoverflow.com/q/49191058
has comment: http://stackoverflow.com/comment/85388440
tagged with: multidimensional-array
type: UnansweredQuestion
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49195626
has title: Append elemnets to numpy nd array
has comment: http://stackoverflow.com/comment/85387162
has comment: http://stackoverflow.com/comment/85388924
score: 0
has body: After performing houghlinesp I trying to filter out the line that has an angle of 85 to 90 degress def filter_line(lines): """ Filter the input the input lines to +/- 5 deg. Parameters: image: The output of a Canny transform. """ filtered_line= np.empty([0, 1, 4]) if lines is not None: for i in range(0, len(lines)): l = lines[i][0] dx = l[2]-l[0] dy = l[3]-l[1] angle= degrees(atan2(dy, dx)) if (angle &gt; 85): print(l) print(type(l)) print(l.shape) np.reshape(l, (1, 1, 4)) print(l.shape) filtered_line = np.append(filtered_line, l, axis=0) return filtered_line type(lines) --> 'numpy.ndarray' lines.shape --> (29, 1, 4) line --> [[[339 475 339 4]] [[224 4 416 4]] [[269 33 400 33]] ...]]] l --> [339 475 339 4] l --> 'numpy.ndarray' l --> (4,) I am looking to output the filtered_line of same dimension ValueError: all the input arrays must have same number of dimensions Not sure how to make it work.
type: Question
tagged with: numpy

http://stackoverflow.com/q/49190879
has comment: http://stackoverflow.com/comment/85387259
has answer: http://stackoverflow.com/a/49191262
type: UnansweredQuestion
tagged with: python
has title: I'm getting keyerror and can not import data from csv file
has comment: http://stackoverflow.com/comment/85386865
score: 0
has body: def load_data(label_dict): x = [] y = [] x_keys = ['FEAT_1','FEAT_2','FEAT_3','FEAT_4','FEAT_5','FEAT_6'] y_keys = ['LABEL']; for item in label_dict: x.append([float(item[k]) for k in x_keys]) y.append([float(item[k]) for k in y_keys]) return (x,y) Error is: File "NID_1.py", line 54, in load_data x.append([float(item[k]) for k in x_keys]) KeyError: 'FEAT_1'
answer count: 1
has comment: http://stackoverflow.com/comment/85386697
upvote count: 1
has comment: http://stackoverflow.com/comment/85387447
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49154589
type: Question
has answer: http://stackoverflow.com/a/49155856
tagged with: python
has body: My dataset looks like this: Year Month Day Category Quantity 1984 1 1 2 10.5 1984 1 1 6 3.7 1985 1 2 8 4.8 1985 2 1 3 20 1986 1 1 1 9 1986 2 1 18 12.6 1987 1 29 20 2.8 Note that every day of every month of every year contains one unique entry. In other words each day can only have one category (not several). I am trying to count how many times each category occurred every year. However, using count in Pandas I realized zero-counts are not included. In other words, if a category did not take place one year it is not included. So in order to solve that I tried using: fill_value=0 (as shown in the below code). I ended up with this (WARNING: don't run this code as is because it eats up all the memory apparently): import pandas as pd df = pd.read_csv("import.csv", header=0, encoding='iso-8859-1') midx = pd.MultiIndex.from_product([ df['Year'], df['Category'] ], names=['Year', 'Category']) df['QuantityWithNaN'] = pd.to_numeric(df['Quantity'], errors='coerce') count_quantity_yearly_above_5 = df[df['QuantityWithNaN'] &gt; 5.0].groupby(['Year', 'Category'])['Quantity'].count() count_quantity_yearly_above_5.reindex(midx, fill_value=0) df['count_quantity_yearly_above_5'] = df.apply(count_quantity_yearly_above_5,axis=1) df.to_csv("export.csv",encoding='iso-8859-1') The datatypes of the dataframe df is after running that code: The datatypes for the dataframe that is imported from the CSV is as: Year int64 Month int64 Day int64 Category int64 Quantity object QuantityWithNaN float64 The end result should thus be like, but is not achieved with the code above. (The end result must not be sorted in any specific order, only important thing is that all categories appear each year): Year Month Day Category Quantity count_quantity_yearly_above_5 1984 1 1 1 10.5 2 1984 1 1 2 3.7 7 1984 1 2 3 4.8 1 1985 2 1 1 20 9 1985 1 1 2 9 1 1986 2 1 3 12.6 4 1987 1 29 20 2.8 5 1988 10 2 0 Also for visualization and the information that matters in the end will entirely be given by the columns as follow…
type: AnsweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/19384532
has title: How to include zero-values with Pandas count and merge results with original dataframe
score: 1
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49155856
favorite count: 0

http://stackoverflow.com/a/49151500
has comment: http://stackoverflow.com/comment/85343560
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/85310973
has body: Let's go in reverse order and start from your last question: what is the difference between compute a gradient and apply a gradient? Computing the gradients means running the backward pass on the network, after having computed the loss. For gradient descent, this means estimating the gradients value in the formula beneath (note: this is a huge simplification of what computing gradients actually entails, look up more about backpropagation and gradient descent fora proper explanation of how this works). Applying the gradients means updating the parameters according to the gradients you just computed. For gradient descent, this (roughly) means executing the following: weights = weights - (learning_step * gradients) Note that, depending on the value of learning_step, the new value of weights depends on both the previous value and the computed weights. With this in mind, it's easier to understand the PS/worker architecture. Let's make the simplifying assumption that there is only one PS (we'll see later how to extend to multi-PS) A PS (parameter server) keeps in memory the weights (i.e. the parameters) and receives gradients, running the update step I wrote in the code above. It does this every time it receives gradients from a worker. A worker, on the other hand, looks up what's the current value of weights in the PS, makes a copy of it locally, runs a forward and a backward pass of the network on a batch of data and gets new gradients, which then sends back to the PS. Note the emphasis on "current": there is no locking or inter-process synchronization between workers and the PS. If a worker reads weights in the middle of an update (and, for example, half already have the new value and half are still being updated), that's the weights he'll use for the next iteration. This keeps things fast. What if there's more PSs? No problem! The parameters of the network are partitioned among the PSs, the worker simply contacts all of them to get the new values for each chunk of the…
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85310244
answers question: http://stackoverflow.com/q/49150587
has comment: http://stackoverflow.com/comment/85310737
score: 5
accepted answer of: http://stackoverflow.com/q/49150587
upvote count: 5

http://stackoverflow.com/a/49215296
score: -1
has body: You can pass a chunk_size parameter to read_table() or read_csv() commands: pd.read_csv('fname.csv', sep=',', chunksize=4) Further information in the documentation. Have you checked that?
upvote count: 0
answers question: http://stackoverflow.com/q/49215252
downvote count: 1
type: Answer

http://stackoverflow.com/a/49291995
has body: API.followers([id/screen_name]) only returns followers 100 at a time. Try: API.followers_ids(id/screen_name/user_id) It will return a list of ID's for all the people following the specified user. Just put your ID in the parameters.
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49244096
accepted answer of: http://stackoverflow.com/q/49244096
type: Answer

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

http://stackoverflow.com/q/49263046
has comment: http://stackoverflow.com/comment/85530883
has body: I have a list that represents points, some are inside the area of a function and others aren't. I want to know if I can paint the points as pixels instead of plotting them.
has comment: http://stackoverflow.com/comment/85530151
tagged with: python
type: Question
tagged with: paint
score: 0
has title: how to paint points inside or outside a function with python and not just plot them?
answer count: 0
tagged with: pixel
type: UnansweredQuestion

http://stackoverflow.com/comment/85482617
type: AnswerComment
has text: I think it should be possible to modify my answer to get what you want. You can pass a number of lines into `find_intersections`, create a list of the output, that list can be passed back to `find_intersections` along some more lines from the feed. You might want to prune empty sets from each iteration, if you are not interested in those.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49208404

http://stackoverflow.com/a/49210167
has comment: http://stackoverflow.com/comment/104675130
answers question: http://stackoverflow.com/q/49157048
upvote count: 21
score: 21
has body: I came across this gem, pd.DataFrame.resample, after I posted my round-to-hour solution. # Construct example dataframe times = pd.date_range('1/1/2018', periods=5, freq='25min') values = [4,8,3,4,1] df = pd.DataFrame({'val':values}, index=times) # Resample by hour and calculate medians df.resample('H').median() Or you can use groupby with Grouper if you don't want times as index: df = pd.DataFrame({'val':values, 'times':times}) df.groupby(pd.Grouper(level='times', freq='H')).median()
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49157048
has comment: http://stackoverflow.com/comment/131899621

http://stackoverflow.com/comment/85414513
score: 0
has text: Thanks. I admit it is but I was wondering whether that's efficient enough. Also, I was thinking about your method of padding. The argument passed into the forward method is padded I suppose. However, in that way, the padding is done for all the training data. This will result in unnecessary padding, e.g., if I have a mini-batch with length ranging from 3 to 5, and another batch from 30 to 50. Then in your method, the padding is done using the max length as 50. Am I understanding something wrong here? Thanks again!
comment on: http://stackoverflow.com/a/49204483
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49246497
upvote count: 1
tagged with: tcp
tagged with: scapy
downvote count: 1
answer count: 1
has body: I've been playing around with scapy and I have a small question... Let's say I have a socket open on a server, say at port 80 at the IP address 1.2.3.4, and say it is listening for and recording any connections. Now, I want to connect to this port from my client (say 2.3.4.5) using scapy, so I have to initiate a three-way handshake, which I've been trying to execute using the following code: ip=IP(src="2.3.4.5", dst="1.2.3.4") TCP_SYN=TCP(sport=1500, dport=80, flags="S", seq=100) TCP_SYNACK=sr1(ip/TCP_SYN) my_ack = TCP_SYNACK.seq + 1 TCP_ACK=TCP(sport=1500, dport=80, flags="A", seq=101, ack=my_ack) send(TCP_ACK/ip) my_payload="space for rent!" TCP_PUSH=TCP(sport=1500, dport=80, flags="PA", seq=102, ack=my_ack) sendp(ip/TCP_PUSH/my_payload) But I never get a response from the server; the console just prints "Finished to send 1 packets." and then prints a stream of dots. Does anyone know what I'm doing wrong?
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: network-programming
type: UnansweredQuestion
tagged with: python
has title: Connecting to a TCP port using Scapy
has answer: http://stackoverflow.com/a/49246618
score: 0

http://stackoverflow.com/comment/85381593
type: Comment
comment on: http://stackoverflow.com/a/49188088
has text: thx. to note, what's interesting (and not completely understood) is that it works if I save the condition statement in separate variable (for instance cond1, cond2) then merge as cond1 & cond2 inside the indexing of file[].
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85369192
type: Comment
type: QuestionComment
score: 0
has text: Possible duplicate of [OS X Get highlighted text](https://stackoverflow.com/questions/1151417/os-x-get-highlighted-text)
comment on: http://stackoverflow.com/q/49181697

http://stackoverflow.com/comment/85263877
type: Comment
comment on: http://stackoverflow.com/a/49129564
score: 0
type: AnswerComment
has text: Could you post your model please.

http://stackoverflow.com/a/76511534
has body: do not train all dataset together train only few samples as per memory requirement I have experiment with large dataset and train only few samples at a time. train_data = train_data.sample(n=200, random_state=12).copy() train_data = train_data.reset_index(drop=True) based on requirement you can modify n(numbers of samples) and random states. random states used to set a seed for the random number generator. It ensures that the dataset is sampled in a reproducible manner.
answers question: http://stackoverflow.com/q/49152221
type: Answer
score: 0

http://stackoverflow.com/q/49249130
has title: Issue with fake_useragent json Python 3 not connecting
has comment: http://stackoverflow.com/comment/85501872
tagged with: python
has body: So I have been working with fake_useragent for a web-scraping project. I recently started receiving the following error in Python 3: Error occurred during loading data. Trying to use cache server http://d2g6u4gh6d9rq0.cloudfront.net/browsers/fake_useragent_0.1.10.json Traceback (most recent call last): File "/home/jalias/virtualenv/python3.5.5/lib/python3.5/site-packages/fake_useragent/utils.py", line 67, in get context=context, File "/opt/python/3.5.5/lib/python3.5/urllib/request.py", line 163, in urlopen return opener.open(url, data, timeout) File "/opt/python/3.5.5/lib/python3.5/urllib/request.py", line 466, in open response = self._open(req, data) File "/opt/python/3.5.5/lib/python3.5/urllib/request.py", line 484, in _open '_open', req) File "/opt/python/3.5.5/lib/python3.5/urllib/request.py", line 444, in _call_chain result = func(*args) File "/opt/python/3.5.5/lib/python3.5/urllib/request.py", line 1282, in http_open return self.do_open(http.client.HTTPConnection, req) File "/opt/python/3.5.5/lib/python3.5/urllib/request.py", line 1257, in do_open r = h.getresponse() File "/opt/python/3.5.5/lib/python3.5/http/client.py", line 1198, in getresponse response.begin() File "/opt/python/3.5.5/lib/python3.5/http/client.py", line 297, in begin version, status, reason = self._read_status() File "/opt/python/3.5.5/lib/python3.5/http/client.py", line 258, in _read_status line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") File "/opt/python/3.5.5/lib/python3.5/socket.py", line 576, in readinto return self._sock.recv_into(b) socket.timeout: timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/jalias/virtualenv/python3.5.5/lib/python3.5/site-packages/fake_useragent/utils.py", line 166, in load verify_ssl=verify_ssl, File "/home/jalias/virtualenv/python3.5.5/lib/python3.5/site-packages/fake_useragent/utils.py", line 122, in get_browser_versions verify_ssl=verify_ssl, File "/home/jalias/virtualenv/py…
tagged with: python-2.7
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85502167
type: Question
tagged with: python-3.x
type: UnansweredQuestion

http://stackoverflow.com/comment/85345694
has text: if i put "for x in items" after my submin should i remove the for-loop then?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49168456

http://stackoverflow.com/a/49233784
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49210695
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49210695
type: Answer
has body: draw is a wrapper around draw_networkx_nodes and draw_networkx_edges. Unlike draw, the two functions return their respective artists ( PathCollection and LineCollection, IIRC). These are your standard matplotlib artists, and as as such their relative draw order can be controlled via their zorder attribute.
score: 1

http://stackoverflow.com/comment/85508963
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49252573
has text: how can it improve time ?

http://stackoverflow.com/q/49265474
has body: Basically I'm trying to add together the count column values of item columns with the same name in a csv file. I then need to sort the results in ascending alphabetic order by item column values. For example: Leading Cause, Deaths Diabetes Mellitus, 123 Influenza and Pneumonia, 325 Diabetes Mellitus, 100 I need to add the values 123 and 100 to get a new row for Diabetes. It should look like this: &nbsp;&nbsp;&nbsp;&nbsp;Diabetes Mellitus, 223. This is the code I have so far: import csv import sys with open(sys.argv[1], 'r') as File: reader = csv.reader(File) itemindex = sys.argv[2] countindex = sys.argv[3] item column = 0 count column = 0 first row = True dictionary = {} for row in reader: if firstrow == True: firstrow = False itemcolumn = row.index(itemindex) countcolumn = row.index(countindex) else: if item column in dictionary: # Add the item at the row's count column (converted to an int) to the # prexisting entry with that item column. else: #create a new entry in the dictionary print(itemindex + "," + countindex) for key, value in sorted(dictionary) print(key + "," + value) The commented parts are the ones I'm stuck on.
has title: How to extract data from a column with variable number of values in each row in a CSV file?
type: Question
possible better answer: http://stackoverflow.com/a/49265607
has answer: http://stackoverflow.com/a/49266621
has answer: http://stackoverflow.com/a/49265607
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
accepted answer: http://stackoverflow.com/a/49266621
has answer: http://stackoverflow.com/a/49265551
score: 2
type: AnsweredQuestion
answer count: 3
upvote count: 2
downvote count: 0
tagged with: file
tagged with: variables
favorite count: 0

http://stackoverflow.com/a/49148056
downvote count: 0
has comment: http://stackoverflow.com/comment/85300663
has body: You can repeat index values: lens = df['column_x'].str.len() a = np.repeat(df.index.values, lens) print (a) [0 0 1 1] df = df.loc[a].assign(column_x=np.concatenate(df['column_x'].values)).reset_index(drop=True) print (df) column_a column_b column_x 0 a_1 b_1 c_1 1 a_1 b_1 c_2 2 a_2 b_2 d_1 3 a_2 b_2 d_2
has comment: http://stackoverflow.com/comment/85373183
accepted answer of: http://stackoverflow.com/q/49147996
score: 2
has comment: http://stackoverflow.com/comment/85397807
has comment: http://stackoverflow.com/comment/85303076
type: Answer
answers question: http://stackoverflow.com/q/49147996
upvote count: 2
type: AcceptedAnswer

http://stackoverflow.com/a/49149398
type: Answer
accepted answer of: http://stackoverflow.com/q/49146623
has comment: http://stackoverflow.com/comment/85304104
score: 0
has body: Assuming your XML code is in test.xml in the working directory. new_content = [] with open("test.xml") as f: content = f.readlines() for line in content: newline = line if 'key="setid"' in line: newline = line[:line.find("value=")] + 'value=".\donotpritnnt\data1" /&gt;\n' new_content += [newline] with open('test.xml', 'w') as f: for line in new_content: f.write(line) Its not the nicest way, but it works for the example you provided, and may also be extentable since it iterates over the file and looks at each line. Further improvements may probably by using regex etc.
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49146623

http://stackoverflow.com/a/49138802
accepted answer of: http://stackoverflow.com/q/49138756
upvote count: 3
score: 3
type: AcceptedAnswer
has body: From the python docs: exception ValueError Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError. So it sounds like you want ValueError, unless you want to define your own custom exception class.
answers question: http://stackoverflow.com/q/49138756
downvote count: 0
type: Answer

http://stackoverflow.com/q/49210622
tagged with: python
tagged with: amazon-web-services
accepted answer: http://stackoverflow.com/a/49242341
has body: Im working on a bot and would like to integrate to a website for my project. My Bot is fully functional, lambda fulfillment coded in python runtime. I see example of how to integrate bot implemented in javascript(lambda node runtime) but not able to find help for python implementation. Does my bot need to be implemented in javascript(lambda node runtime) to be able to integrate with website? I not very familiar with UI stuff and any help to get me started is appreciated.
type: AnsweredQuestion
score: 0
tagged with: chatbot
answer count: 1
upvote count: 1
downvote count: 1
tagged with: amazon-lex
favorite count: 0
tagged with: aws-lambda
type: Question
has answer: http://stackoverflow.com/a/49242341
has title: Integrate AWS Lex to website(lambda implemented in python runtime)

http://stackoverflow.com/q/49153682
has comment: http://stackoverflow.com/comment/85311749
upvote count: 1
has comment: http://stackoverflow.com/comment/85312744
answer count: 1
downvote count: 1
favorite count: 0
has body: I am trying to write a Python script that checks if a file exists from the day before. In this instance, I am trying to establish if the file "myFile_20180306" exists with the C:\myFolder\ directory. The issue I am having is that in the for loop it prints "ERROR: myFile_20180306 does not exist!" multiple times in the console. How do I re-write this script to display the print line only once if the file exists or not? #!/usr/bin/python import os, sys from datetime import date, timedelta yesterday = date.today() - timedelta(1) yesterdaysDate = yesterday.strftime('%Y%m%d') yesterdaysFile_myFile = yesterday.strftime('myFile_%Y%m%d.csv') for subdir, dirs, files in os.walk('C:\myFolder'): for file in files: if file == yesterdaysFile_myFile: print 'OKAY: ',yesterdaysFile_myFile,' is available.' else: print 'ERROR: ',yesterdaysFile_myFile,' does not exist!'
type: Question
has comment: http://stackoverflow.com/comment/85311838
has comment: http://stackoverflow.com/comment/85311943
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85312023
has title: Python - Check if file exists from yesterday
tagged with: python
has answer: http://stackoverflow.com/a/49157121
has comment: http://stackoverflow.com/comment/85312229
score: 0

http://stackoverflow.com/q/49265300
upvote count: 1
tagged with: imputation
has comment: http://stackoverflow.com/comment/85534880
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49265948
type: Question
has answer: http://stackoverflow.com/a/49265948
tagged with: python
has title: Python: automatic data imputing based on machine learning
score: -1
type: AnsweredQuestion
downvote count: 2
has body: Besides filling the missing data with mean, one could actually use machine learning (even regression) to fill in the missing value. As there are more and more automatic machine learning code available. I wonder if there is any python code that allows me the fill in the missing value of pandas dataframe with some kind of machine learning method. Thanks.

http://stackoverflow.com/a/49244528
answers question: http://stackoverflow.com/q/49209385
accepted answer of: http://stackoverflow.com/q/49209385
type: Answer
upvote count: 6
has body: The issue comes from a conflict between multiple atexit.register() calls. The documentation states that: atexit runs these functions in the reverse order in which they were registered; if you register A, B, and C, at interpreter termination time they will be run in the order C, B, A. [...] The assumption is that lower level modules will normally be imported before higher level modules and thus must be cleaned up later. By first importing multiprocessing and then calling atexit.register(my_stop), you would expect your stop function to be executed before any internal termination procedure... But this is not the case, because atexit.register() may be called dynamically. In the present case, the multiprocessing library makes use of a _exit_function function which is meant to cleanly close internal threads and queues. This function is registered in atexit at the module level, however the module is only loaded once the Queue() object is initialized. Consequently, the MyClass stop function is registered before the multiprocessing's one and thus instance.stop is called after _exit_function. During its termination, _exit_function closes internal pipes connections, so if the thread later try to call .get() with a closed read-connection, an EOFError is raised. This happens only if Python did not have time to automatically kill the daemon thread at the end, that is if a "slow" exit function (like time.sleep(0.1) or in this case thread.join()) is register and run after the usual closure procedure. For some reason, the write-connection shutdown is delayed hence .put() does not raise error immediately. As to why small modifications to the snippet makes it work: SimpleQueue does not have Finalizer so internal pipe is closed later. The internal thread of Queue is not started until the first .put() is called so removing it means there is no pipe to close. It is also posible to force registeration by importing multiprocessing.queues.
type: AcceptedAnswer
downvote count: 0
score: 6

http://stackoverflow.com/comment/85398648
type: Comment
has text: Thanks, I think your reasoning is correct but we are not quite there. When using your solution 'body' just contains the div tag: but I need the content of the div tag.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49196240

http://stackoverflow.com/comment/85346173
comment on: http://stackoverflow.com/a/49170340
type: Comment
has text: then change the file name it maybe possible that python is executing some other test.py
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85484060
comment on: http://stackoverflow.com/q/49237582
has text: For `max_depth` just add the depth to the node and break if it hits the max. For `num_paths` the easiest way would be just to change all the `reuturn` statements to `yield` and use it as a generator, either using `next` for just one result, or `slice(astar(...), num)` for `num` results.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85523584
type: Comment
type: QuestionComment
has text: What is the initial value of `b`?
comment on: http://stackoverflow.com/q/49260086
score: 1

http://stackoverflow.com/q/49151849
answer count: 1
has answer: http://stackoverflow.com/a/49153607
accepted answer: http://stackoverflow.com/a/49153607
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: discord.py
tagged with: raspberry-pi
linked to: http://stackoverflow.com/q/46673995
has body: I need help with this: import discord from discord.ext import commands from discord.voice_client import VoiceClient bot = commands.Bot(";") @bot.command(pass_context=True) async def sendm(member, sv, ch, *, msg): serverd = member.server.id("{0}".format(sv)) channel = member.server.get_channel("{0}".format(ch)) await bot.send_message(serverd, channel, msg) bot.run("TOKEN") error list: what I entered in a discord server: ;sendm 411576459077877783 general test Hosting with Raspberry Pi 3
tagged with: python
type: AnsweredQuestion
has title: How to send a message to another server from my server?
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/85331056
type: QuestionComment
has text: wow thanks didn't saw that
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49162578

http://stackoverflow.com/comment/85546592
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49200872
type: Comment
has text: They are initialized to zero and do not change during backpropagation

http://stackoverflow.com/comment/85494059
type: QuestionComment
has text: Note to downvoters: It's okay, this isn't a bad question. Most pandas questions don't involve code because code is useless. Quite often users try things that don't work. Posting attempts here is meaningless, data is more important.
comment on: http://stackoverflow.com/q/49244884
score: 0
type: Comment

http://stackoverflow.com/a/49237565
type: Answer
answers question: http://stackoverflow.com/q/49236146
downvote count: 0
score: 1
upvote count: 1
has body: You should be using Hough to search for circles. This method project every single white pixel as a circle, and tries to get as many overlapping pixels possible. You'll have to specify the predicted radiuses of circles to be found within image. Left - original image Top-right - each white pixel is projected as red circle - they are too small to find intersecting point Bottom-right - green circle is larger, and all the intersecting points meet exactly at the middle of the circle! Both radius and position is returned by cvHoughCircles This person dealt with blob detection (that's what finding circles is called I think) using cvHoughCircles with cvCanny-ized image (read OPs update). OpenCV: Error in cvHoughCircles usage

http://stackoverflow.com/q/49131708
has comment: http://stackoverflow.com/comment/85268125
has comment: http://stackoverflow.com/comment/85268122
answer count: 1
has comment: http://stackoverflow.com/comment/85278796
upvote count: 1
tagged with: python
downvote count: 1
favorite count: 0
has title: Conditional python regex
has comment: http://stackoverflow.com/comment/85271536
has answer: http://stackoverflow.com/a/49131786
has comment: http://stackoverflow.com/comment/85271576
has body: I am trying to parse the nmap output for service discovery with the following regex. regex = "(?P&lt;ports&gt;[\d]+)\/(?P&lt;protocol&gt;tcp|udp)\s+(?P&lt;state&gt;open|filtered|closed)\s+(?P&lt;service&gt;[\w\S]*)\s+(?P&lt;reason&gt;\S*\s+\S+\s+\S*(?=\w)\w)(?:\n|(?P&lt;version&gt;.*))" It could parse the output with the following pattern. PORT STATE SERVICE REASON VERSION 80/tcp open http str1 str2 str3 version string here But is not able to correctly parse the following output. PORT STATE SERVICE REASON VERSION 161/tcp filtered snmp no-response Is there any single regex which can parse both the above patterns?
tagged with: regex
has comment: http://stackoverflow.com/comment/85269443
has comment: http://stackoverflow.com/comment/85268050
type: Question
score: 0
has comment: http://stackoverflow.com/comment/85278860
type: UnansweredQuestion

http://stackoverflow.com/comment/85554267
score: 0
type: Comment
has text: @vumaasha 2.7.12
type: QuestionComment
comment on: http://stackoverflow.com/q/49275661

http://stackoverflow.com/q/49201787
favorite count: 0
type: Question
tagged with: python
type: AnsweredQuestion
has body: I've changed the name of an item in a StreamField from tiles = StreamField( [ ('items', StructBlock([ ('icon', ImageChooserBlock()), ('text', CharBlock()), ]) ), ], blank=True) To tiles = StreamField( [ ('info', StructBlock([ ('icon', ImageChooserBlock()), ('text', CharBlock()), ]) ), ], blank=True) Any idea how I can create a migration to rename the field ?
downvote count: 0
score: 1
upvote count: 1
tagged with: wagtail
has answer: http://stackoverflow.com/a/49204648
answer count: 1
accepted answer: http://stackoverflow.com/a/49204648
has title: Wagtail - Possible to rename an item in a streamfield in a migration?

http://stackoverflow.com/q/49256838
tagged with: pandas
answer count: 0
has title: Run calculations on list of selected columns
linked to: http://stackoverflow.com/q/45250425
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85519002
duplicate of: http://stackoverflow.com/q/13256917
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85516621
has comment: http://stackoverflow.com/comment/85519396
has body: For this exercise I have a dataframe containing orders numbers, item ids, company ids, countries and count. In practice I have many more columns. Now I want to automate some calculations for analysis purposes, by generating the mean, sum, etc. of the order count for every column I select. E.g. if I select the item_id and company_id I want the mean of those as separate columns. Preferably with generated column headers, e.g. item_id_mean and company_id_mean. I know how to group by one or multiple columns. This works manually perfect for every selected column. But now want to run this for a larger set of columns based on a column selection (through a separate file) Question: How to group by every single column from a list of columns headers individually and calculate the mean (or sum)? Also, how to generate the respective headers for these new columns? My testcode: df_columnselect = pd.DataFrame({'Column':['ordernumber','item_id', 'company_id','country', 'count'], 'Selected':['no','yes','yes','no','no']}, columns=['Column','Selected’]) print(df_columnselect) Column Selected 0 ordernumber no 1 item_id yes 2 company_id yes 3 country no 4 count no Selected_Cols=df_columnselect.loc[df_columnselect.Selected=='yes', 'Column'] print(Selected_Cols) 1 item_id 2 company_id df_orders = pd.DataFrame({'ordernumber':[1,2,3,4,5,6,7,8,9,10], 'item_id': [1, 1, 2, 2, 3, 4, 4, 5, 7, 8], 'company_id':['a','b','c','a','b','c','a','b','c','a'], 'country':[0, 1, 0, 1, 1, 0, 1, 1, 1, 0], 'count':[27, 49, 3, 1, 6, 8, 14, 1, 1, 6] }, columns=['ordernumber','item_id', 'company_id','country', 'count']) I've tried te following, based on your input, but the first only generates 1 column and calculates the wrong mean. Whereas the second is the correct mean, but does not automate the generation of new columns based on the selection (Selected_Cols) df_orders['new_col'] = df_orders.groupby(Selected_Cols)['count'].transform('mean') df_orders['new_col2'] = df_orders.groupby('item_id')['count'].transform(…
type: UnansweredQuestion
downvote count: 0
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85523098
linked to: http://stackoverflow.com/q/13256917

http://stackoverflow.com/comment/85267573
comment on: http://stackoverflow.com/q/49131510
has text: `df.isin([0, 1]).any(axis=0)`?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49175624
has comment: http://stackoverflow.com/comment/85360646
downvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85382277
has comment: http://stackoverflow.com/comment/85358884
has comment: http://stackoverflow.com/comment/85418382
has answer: http://stackoverflow.com/a/49176138
has comment: http://stackoverflow.com/comment/85362449
has comment: http://stackoverflow.com/comment/85356745
has comment: http://stackoverflow.com/comment/85356563
has comment: http://stackoverflow.com/comment/85357157
has body: I need to detect direct and indirect recursion in a rather large (5-15,000) set of C (not C++) files. The files are already preprocessed. The code is pretty "old school" for safety reasons so no fancy things like function pointers in there, only functions that pass variables about and some function-macros that do the same. The most natural way to detect recursion is to make a directed call-graph, considering each function a node with an edge going to all the other functions that it calls. If the graph has any cycles, then we have recursion. A regex to find function calls is trivial to make but I also need to know which function did the calling. PyCParser was nice but it complains about a lot of things such as variables that are not defined or typedefs where the source type is not defined or defined in a different file which are completely irrelevant in my use-case. The project uses a custom dependency management system so some includes and the such are added automatically so I would need PyCParser to not care about anything other than FuncCall and FuncDef nodes and I don't think there is a way to limit the parsing process itself to just that. I would rather not implement a parser as there i do not exactly have the time to learn how to do that in python and then implement the solution. Back to the issue, how would I go about parsing the functions in a C file? Basically getting a dict with strings(names of functions defined in the file) as the keys, and lists of strings(the functions called by each function) as the values? A regex seems to be the most natural solution. Using python is not optional sadly.
has comment: http://stackoverflow.com/comment/85359141
type: Question
has comment: http://stackoverflow.com/comment/85356411
has comment: http://stackoverflow.com/comment/85357006
score: 3
has comment: http://stackoverflow.com/comment/85356470
has comment: http://stackoverflow.com/comment/85357199
tagged with: python
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/c
tagged with: regex
has comment: http://stackoverflow.com/comment/85356581
has comment: http://stackoverflow.com/comment/85356674
has comment: http://stackoverflow.com/comment/85356608
has comment: http://stackoverflow.com/comment/85358202
has comment: http://stackoverflow.com/comment/85362274
tagged with: parsing
has comment: http://stackoverflow.com/comment/85357062
upvote count: 4
has comment: http://stackoverflow.com/comment/85356509
has title: Detecting recursion in a C file with Python

http://stackoverflow.com/comment/85455693
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49225757
has text: thank you though, I really appriciate the help, I just get really annoyed because, even though I state that I'm a beginner, most people instantly assume that I'm not and shit talk me and criticize me. I misread your words, but thanks, I appriciate

http://stackoverflow.com/comment/85565374
type: QuestionComment
has text: In my opinion, Dhugalmac's comment provides the best answer to this question. I went to the link and it does seem to provide a solution.
type: Comment
comment on: http://stackoverflow.com/q/49252677
score: 0

http://stackoverflow.com/comment/118477920
type: Comment
comment on: http://stackoverflow.com/a/58071119
has text: you can indeed create a process and exit the terminal!
type: AnswerComment
score: 0

decision-tree
type: Tag
tags question: http://stackoverflow.com/q/49227490
tags question: http://stackoverflow.com/q/49134216
tags question: http://stackoverflow.com/q/49170296
tags question: http://stackoverflow.com/q/49155456
tag name: decision-tree

http://stackoverflow.com/a/49121724
has comment: http://stackoverflow.com/comment/85249671
accepted answer of: http://stackoverflow.com/q/49121631
type: Answer
has body: Suppose you have: df1=pd.DataFrame({'col_1': {0: 3, 1: 4, 2: 5}, 'col_2': {0: 7, 1: 8, 2: 5}}) df2=pd.DataFrame({'col_1': {0: 4, 1: 5}, 'col_3': {0: 78, 1: 89}}) You can use merge: pd.merge(df1,df2,on='col_1',how='left').fillna(0) Out[22]: col_1 col_2 col_3 0 3 7 0.0 1 4 8 78.0 2 5 5 89.0 If you need col_3 as int (thanks to piRSquared for his suggestion): pd.merge(df1,df2,on='col_1',how='left').fillna(0, downcast='infer') Out[25]: col_1 col_2 col_3 0 3 7 0 1 4 8 78 2 5 5 89
has comment: http://stackoverflow.com/comment/85249664
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/49121631
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/85284221
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49139418
has text: I mean, everything you write here is correct, but the question asks why in the plot shown (which is copied from the documentation), the two whisker lines are different, given that they should be 1.5*IQR long on both sides of the box.

http://stackoverflow.com/q/49176543
tagged with: python
tagged with: numpy
has body: I would like to use pandas in Pycharm under Python27. Every time I try to import it I get the following error: import pandas Traceback (most recent call last): 'this pandas version'.format(_np_version)) ImportError: this version of pandas is incompatible with numpy &lt; 1.9.0 your numpy version is 1.8.1. Please upgrade numpy to &gt;= 1.9.0 to use this pandas version I noticed that this has to do with the numpy version. Indeed when I do the following it does confirm that the version of numpy I have installed is version 1.8.1. import numpy numpy.version.version Out[6]: '1.8.1' This was confusing because in my interpreter settings it shows numpy 1.14.1. I then checked to see what folder it was interpreting numpy from: In[8]: numpy.__file__ Out[8]: 'C:\\Program Files\\ParaView 5.2.0-Qt4-OpenGL2-Windows-64bit\\bin\\Lib\\site-packages\\numpy\\__init__.pyc' I believe this is the problem, numpy is being imported from a different package (paraview.simple in this case), which makes use of an earlier version of numpy and includes it within its directory for its own purposes. I'd like pandas to go ahead and use its own numpy, but also have paraview.simple use its own numpy. How can I ensure the packages don't interfere with each other? Thanks
has comment: http://stackoverflow.com/comment/85359157
answer count: 0
has comment: http://stackoverflow.com/comment/85359672
type: UnansweredQuestion
type: Question
score: 0
has comment: http://stackoverflow.com/comment/85358334
has title: several versions of numpy installed but all needed in python

http://stackoverflow.com/q/49212832
linked to: http://stackoverflow.com/q/369438
score: 7
has comment: http://stackoverflow.com/comment/85511614
has title: Implementing smooth colouring in mandelbrot set
has comment: http://stackoverflow.com/comment/85489093
type: Question
tagged with: python-3.x
tagged with: mandelbrot
has body: I am trying to colour MandelBrot using HSV values and the PIL Library. Even after multiple tries fiddling with HSV values, I could not achieve the desired effect. here is what I currently have Here is the desired effect This is the code that I am trying, It could also be beneficial if you could add some tips to optimise the below code to compute the set faster, I am new to python from PIL import Image import random import math from decimal import Decimal # Size of the Image Canvas HEIGHT = 500 ZOOM = 0.0 Y_PAN = 0.0 # Range of the Complex Plane MIN_X = -2.0 + ZOOM MAX_X = 2.0 - ZOOM MAX_Y = 2.0 + Y_PAN - ZOOM MIN_Y = -2.0 + Y_PAN + ZOOM DATA = [] def map_to_scale_d(x, in_min, in_max, out_min, out_max): # returns float return float((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min) def map_to_scale(x, in_min, in_max, out_min, out_max): # returns int return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min # Max iterations till Zn ITER = 200 # loop to traverse every single point in Canvas for y in xrange(HEIGHT): for x in xrange(HEIGHT): # convert to complex plane scale a = map_to_scale_d(x, 0, HEIGHT, MIN_X, MAX_X) b = map_to_scale_d(y, 0, HEIGHT, MAX_Y, MIN_Y) # original values _a = a _b = b counter = 0 # start the iteration at (a,b) in complex plane # calculate z^2 + c while(counter &lt; ITER): aa = a * a - b * b bb = 2 * a * b a = aa + _a b = bb + _b if((abs(aa + bb)) &gt; 4): break counter = counter + 1 # initialise color h = 0 s = map_to_scale(counter, 0, ITER, 0, 100) v = map_to_scale(counter, 0, ITER, 0, 100) if(counter == ITER): h = 0 s = 0 v = 0 # convert to 8-bit h = map_to_scale(h, 0, 360, 0, 255) s = map_to_scale(s, 0, 100, 0, 255) v = map_to_scale(v, 0, 100, 0, 255) DATA.append((h, s, v)) img = Image.new('HSV', (HEIGHT, HEIGHT)) img.putdata(DATA) img.show() img.convert('RGB').save('test.png')
type: UnansweredQuestion
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/76944501
tagged with: python
has comment: http://stackoverflow.com/comment/99038230
upvote count: 7
favorite count: 0
tagged with: fractals
linked to: http://stackoverflow.com/q/56195735

http://stackoverflow.com/q/49222525
tagged with: binary-search
tagged with: recursion
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49222612
has title: Binary Search Iterative and Recursive with tuple (python)
has answer: http://stackoverflow.com/a/49222612
type: Question
answer count: 1
has body: I am trying to create a binary search (both iterative and recursive) with the parameters being (tuple, int). I really want to understand it more because I thought I understood the code logically as is, but apparently not. The iterative code (isMemberI) is giving me correct results half of the time, and then randomly incorrect so I don't know what is causing this. I am getting no errors, just the wrong answer sometimes. The recursive code gives me errors sometimes, and then works probably ¼ of my test cases. When I try the following, I am getting these errors: &gt;&gt;&gt; isMemberR((1, 2, 3, 3, 4), 4 Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; isMemberR((1, 2, 3, 3, 4), 4) File "/Users/alyssakelley/Documents/p93_binsearch.py", line 127, in isMemberR return isMemberR(aseq[midpoint + 1], target) File "/Users/alyssakelley/Documents/p93_binsearch.py", line 117, in isMemberR if len(aseq) == 0: TypeError: object of type 'int' has no len() &gt;&gt;&gt; isMemberR('aeiou', 'y') Traceback (most recent call last): File "&lt;pyshell#3&gt;", line 1, in &lt;module&gt; isMemberR('aeiou', 'y') File "/Users/alyssakelley/Documents/p93_binsearch.py", line 127, in isMemberR return isMemberR(aseq[midpoint + 1], target) File "/Users/alyssakelley/Documents/p93_binsearch.py", line 127, in isMemberR return isMemberR(aseq[midpoint + 1], target) IndexError: string index out of range &gt;&gt;&gt; isMemberR((1, 3, 5, 7), 4) Traceback (most recent call last): File "&lt;pyshell#4&gt;", line 1, in &lt;module&gt; isMemberR((1, 3, 5, 7), 4) File "/Users/alyssakelley/Documents/p93_binsearch.py", line 125, in isMemberR return isMemberR(aseq[:midpoint], target) File "/Users/alyssakelley/Documents/p93_binsearch.py", line 127, in isMemberR return isMemberR(aseq[midpoint + 1], target) IndexError: tuple index out of range Here is my code: def isMemberI(aseq, target): first = 0 last = len(aseq) - 1 found = False while first &lt; last: midpoint = (first + last) // 2…
tagged with: python
has comment: http://stackoverflow.com/comment/85448643

http://stackoverflow.com/comment/85340860
has text: Yes X_ are the same. The four values are the cost function. Left with the gradients, left with the out of the box optimizer...
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49135653
type: Comment

http://stackoverflow.com/comment/85374587
has text: One of the model parameters has `None` grad. It is hard to tell more than this.
comment on: http://stackoverflow.com/q/49184241
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/q/49210745
has answer: http://stackoverflow.com/a/49223193
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85427339
upvote count: 1
tagged with: python
tagged with: matlab
has body: I have two modules, and I need to import one from another. In first module, I need to only declare variable and load (if its not loaded). In second, just read this variable and use that (if not loaded, in another module load it) First module: run_engine.py: #run_engine.py import matlab eng = None if(eng == None): eng = matlab.engine.start_matlab() start.py: #!/usr/bin/python import matlab.engine import os import run_engine def app(): currentDir = os.path.dirname(os.path.abspath(__file__)) matlabInstance = run_engine.eng matlabInstance.addpath(currentDir) matlabInstance.sim('thermo_simple') if __name__ == '__main__': app() matlab.engine.start_matlab takes about 30seconds to start, and i´m using start.py repeatly, so I need only one instance of eng, but correct loaded. How can I do that?
has answer: http://stackoverflow.com/a/49211640
score: 1
has comment: http://stackoverflow.com/comment/85444530
has title: Python reusing of module without new load
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/q/49160428
answer count: 2
tagged with: pandas
score: 1
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/49160507
favorite count: 0
type: Question
has title: Turning a list of lists into a column of arrays in a dataframe
has comment: http://stackoverflow.com/comment/85326447
accepted answer: http://stackoverflow.com/a/49160588
has comment: http://stackoverflow.com/comment/85326365
tagged with: python
has answer: http://stackoverflow.com/a/49160588
has body: I have an embedding matrix - that is a list of same size embedding vectors. Each embedding correspond to a sentence. I have a pandas dataframe where each row represents a sentence, and I would like to add to this dataframe a new column that contains the embedding of each sentence. I tried: df['sent_emb'] = pd.DataFrame(sentences) And got : &gt; ValueError: Wrong number of items passed 30, placement implies 1 (My embedding size is 30). I couldn't get it right without loosing the array structure. Thanks
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49160507

http://stackoverflow.com/q/49267321
has answer: http://stackoverflow.com/a/49267606
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85538022
has title: Python csv file lookup
score: -3
has body: Working on a project where we have been provided three csv files (by city name). Project requires to write an interactive code where if a user specifies a city, the full pathname of the city shows up. def get_city(): '''Asks the user for a city and returns the filename for that city's bike share data. Args: none. Returns: (str) Filename for a city's bikeshare data. ''' city = input('\nHello! Let\'s explore some US bikeshare data!\n' 'Would you like to see data for Chicago, New York, or Washington?\n')
tagged with: python
has comment: http://stackoverflow.com/comment/85539678
upvote count: 0
answer count: 1
downvote count: 3
favorite count: 0
type: Question

http://stackoverflow.com/q/49245258
has answer: http://stackoverflow.com/a/49245487
has comment: http://stackoverflow.com/comment/85494510
has title: Percentage change in panel data with pandas
downvote count: 0
has body: I have the following panel data, long format. Column date is the time dimension, and jointly with supermkt and product identify an observation. I want to calculate the percentual change in time in column price (losing one observation per supermkt, product). cols = ['date', 'supermkt', 'product', 'price'] data = [['2012-08-01',1,1,83], ['2012-08-02',1,1,68], ['2012-08-03',1,1,94], ['2012-08-04',1,1,98], ['2012-08-05',1,1,101], ['2012-08-01',1,2,21], ['2012-08-02',1,2,6], ['2012-08-03',1,2,6], ['2012-08-04',1,2,4], ['2012-08-05',1,2,12], ['2012-08-01',2,1,78], ['2012-08-02',2,1,88], ['2012-08-03',2,1,48], ['2012-08-04',2,1,48], ['2012-08-05',2,1,48]] d = pd.DataFrame(data, columns=cols) Expected output for supermkt=1,product=1: cols = ['date', 'supermkt', 'product', 'price','pct_change'] data = [[2012-08-01,1,1,83,Nan], [2012-08-02,1,1,68,-0.18], [2012-08-03,1,1,94,0.38], [2012-08-04,1,1,98,1.04], [2012-08-05,1,1,101,1.03]]
tagged with: pandas
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/85249421
comment on: http://stackoverflow.com/q/49121895
type: Comment
score: 0
has text: @alpine.lines: `staticmethod` is basically only for utility functions specifically useful to a class that serve no purpose outside the class, but could just as easily be defined outside the class completely. `classmethod` is for alternate constructors. All other class methods (that actually use information about the instance) can and should be plain instance methods.
type: QuestionComment

http://stackoverflow.com/q/49186639
has comment: http://stackoverflow.com/comment/85378903
has answer: http://stackoverflow.com/a/49186801
tagged with: python
score: 1
has title: Separating Python bytes array starting on \x with regEx
answer count: 1
upvote count: 1
tagged with: regex
favorite count: 0
tagged with: aes
type: Question
tagged with: hex
type: UnansweredQuestion
has body: Trying to Encrypt every 26 char length block like so, first turn it into an array of bytes then use regex to find every \x in the bytearray and afterwards encrypt it with AES. import re import base64 from Crypto.Cipher import AES from Crypto.Random import get_random_bytes key=get_random_bytes(16) generator = AES.new(key, AES.MODE_CCM) crypt="" textHex="87315a69020000006400110400096d617274696e657433010882848b962430486c03010b0504000100002a01042f010432040c121860dd06001018010100dd160050f20101000050f20201000050f20201000050f202" textBlocks=re.findall('.{1,26}',textHex) for i in range(0,len(textBlocks)): textBlocks[i]=bytes.fromhex(textBlocks[i]) textBlocks2=re.findall('.+?(?=\\\x)', textBlocks[i]) for j in range(0,len(textBlocks2): crypt += generator.encrypt(textBlocks2[j]) The problem is that the regex doesnt recognise the \x00 also while this regex works on the RegExr , python displays the following error SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 8-9: truncated \xXX escape
downvote count: 0

http://stackoverflow.com/q/49270059
has answer: http://stackoverflow.com/a/49270165
downvote count: 0
has comment: http://stackoverflow.com/comment/85543417
upvote count: 1
has comment: http://stackoverflow.com/comment/85543293
accepted answer: http://stackoverflow.com/a/49270201
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49270165
score: 1
tagged with: python
has title: Run functions in list except for function specified
type: Question
answer count: 2
has body: Is there a way to run a list of functions in a method from another method while skipping over 1 specified function in the list? For example, I have the contentList method: def contentList(self): methods = [self.title, self.containerDIV, self.heading, self.stopSection, self.offlineSection, self.onlineSection, self.endDIV, self.otherImages] for m in methods: m() def test(self): self.contentList() # skip over stopSection Is there a way to run those methods from test method while skipping over or not running the self.stopSection? UPDATE Here is more on what I am trying: #**************************** BEGIN OF HTML CONTENT **************************** def title(self): self.wfile.write(bytes("&lt;div id='title'&gt;&lt;img src='../images/title.png'&gt;&lt;/div&gt;", "utf8")) def containerDIV(self): self.wfile.write(bytes("&lt;div id='container'", "utf8")) def endDIV(self): self.wfile.write(bytes("&lt;/div&gt;", "utf8")) #**************************** END OF HTML CONTENT **************************** def contentList(self, skip_name): # All content functions in list methods = [self.title, self.containerDIV, self.endDIV] for m in methods: if m.__name__ != skip_name: m() def narrow(self): try: self.contentList('title') # removed title return # GET def do_GET(self): try: self.contentList('none') # I added none here because I want to keep title return
has answer: http://stackoverflow.com/a/49270201

ansible-vault
type: Tag
tags question: http://stackoverflow.com/q/49151299
tag name: ansible-vault

http://stackoverflow.com/a/49219352
has comment: http://stackoverflow.com/comment/85442582
has comment: http://stackoverflow.com/comment/85442694
score: 1
has comment: http://stackoverflow.com/comment/85442862
downvote count: 0
has comment: http://stackoverflow.com/comment/85443465
upvote count: 1
answers question: http://stackoverflow.com/q/49218914
has comment: http://stackoverflow.com/comment/85442486
has comment: http://stackoverflow.com/comment/85442669
type: Answer
has comment: http://stackoverflow.com/comment/85442829
has comment: http://stackoverflow.com/comment/85442405
has body: I think it is supposed to be bla = obj["followers_count"]

http://stackoverflow.com/q/49132967
tagged with: subprocess
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85270743
upvote count: 1
has answer: http://stackoverflow.com/a/49133991
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85271240
has title: Run multiple subprocesses in parallel - python 2.7
tagged with: linux
tagged with: network-programming
accepted answer: http://stackoverflow.com/a/49133991
tagged with: python
tagged with: ping
type: AnsweredQuestion
has body: The script shown below is my attempt at pinging multiple network namespaces using python 2.7 running on Linux (Fedora) OS. Current status and problem: When I run this file; the ping from elem1 (namespace) gets stored in a file called results.txt. But, I can't seem to get the loop to come back around and ping elem2, elem3, ... elemN Attempted Fixes: I tried killing the process using "kill -9 p.pid" (as shown) in the hope that this would kill the process and then a new process could be created on next iteration of the loop. However this is not the case! I've checked the documentation ( https://docs.python.org/2/library/subprocess.html ) and tried several different permutations of kill(), terminate(), removing shell=True etc... but to no avail. import time import os import signal import subprocess IP_ADDR="192.168.1.1" def main(): arry =["elem1", "elem2", "elem3", "elem4", "elem5", "elem6", "elem7"] array of network namespaces's to ping with open('results.txt', 'a+') as outfile: for elem in arry: command = "ip netns exec {0} ping {1}".format(elem, IP_ADDR) outfile.write("\n\nPinging {}\n".format(elem)) p = subprocess.Popen(command, shell=True, stdout=outfile) command_kill = "kill -9 {}".format(p.pid) time.sleep(2) #wait 5 seconds p.kill() outfile.close() if __name__ == '__main__': main() My Questions: (1) Can someone explain what the code is doing here? (2) Can you suggest a means to achieve my aforementioned goal? Thank you

http://stackoverflow.com/comment/85325129
has text: that was it, thanks for the help
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49159623
score: 0

http://stackoverflow.com/q/49171345
favorite count: 0
has title: How to handle fallback intent in RASA NLU by setting a threshold value
type: Question
type: UnansweredQuestion
tagged with: rasa-nlu
has answer: http://stackoverflow.com/a/49171455
tagged with: python
score: 4
has body: I'm trying to build an application in RASA NLU where I want to route all not understood text to the None Intent. But, if I give some gibberish text, it's not giving the none intent instead its giving me some other intent. My questions are: How do I set a threshold value for None Intent, such that if confidence score is below that it will fallback to the None Intent. Why is it routing to another intent instead of None intent when I'm giving gibberish input?
upvote count: 4
answer count: 1
downvote count: 0

http://stackoverflow.com/a/49253516
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49253395
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/85511253
answers question: http://stackoverflow.com/q/49253395
has body: ModelForm.save() is called first and it is calling Model.save() internally. Method in ModelForm is an helper to build or update Model object from data provided in form and save it to database. It also saves any many to many or reversed foreign key relations.
score: 2

http://stackoverflow.com/comment/85280864
comment on: http://stackoverflow.com/a/49137865
score: 0
type: Comment
has text: WEN YOU THE BEST! But can you explain why it is 0:5? Wouldnt that mean first 6 characters??
type: AnswerComment

http://stackoverflow.com/comment/85291441
has text: See https://repl.it/repls/HeftyScarceStrategy for an interactive example. That's how you add methods to classes dynamically; dead simple. https://repl.it/repls/FlamboyantCrookedThing is how you add them to instances; still pretty simple. Whatever problems you're having are either because you're trying to do something trickier than necessary, or because you're misunderstanding something much more fundamental and shouldn't even be trying this stuff yet.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49142821
score: 0

http://stackoverflow.com/comment/85292077
comment on: http://stackoverflow.com/q/49143198
has text: Can't reproduce. Is that the actual order in which you executed those statements? I bet you didn't actually execute `import numpy.matlib as npm` before `a = np.matlib.repmat([1,1],1,2)`.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85354712
comment on: http://stackoverflow.com/a/49174759
type: Comment
has text: It did not give e output from my side. Is it working at your side?
type: AnswerComment
score: 0

http://stackoverflow.com/q/49262649
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/49437131
has title: How to use Asynchronous Generators in Twisted?
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85538949
answer count: 1
has comment: http://stackoverflow.com/comment/85541227
tagged with: twisted.internet
tagged with: twisted
score: 0
has body: Twisted provides wrapping native coroutines(coroutines using async/await). Using ensureDeferred, we can wrap a coroutine and get its equivalent deferred. How to wrap an asynchronous generator (available in Python 3.6), so that we get a deferred ? Trying to wrap an asynchronous object returns following error: File "/home/yash/Scrapy/vnv/lib/python3.6/site-packages/Twisted-17.9.0-py3.6-linux-x86_64.egg/twisted/internet/defer.py", line 915, in ensureDeferred raise ValueError("%r is not a coroutine or a Deferred" % (coro,)) ValueError: is not a coroutine or a Deferred EDIT: I have provided a sample code where the logic required is demonstrated,and the corresponding error occuring: from twisted.internet import reactor, defer import asyncio async def start_request(): urls = ['https://example.com/page/1', 'https://example.com/page/2', 'https://example.com/page/3'] async for url in urls: yield url await asyncio.sleep(2) async def after_request(): await asyncio.sleep(3) print("Completed the work") deferred = ensureDeferred(start_request()) deferred.addCallback(after_request()) print("reactor has started") reactor.run() Error Traceback: Traceback (most recent call last): File "req2.py", line 20, in &lt;module&gt; deferred = defer.ensureDeferred(start_request()) File "/home/yash/Scrapy/vnv/lib/python3.6/site-packages/Twisted- 17.9.0-py3.6-linux-x86_64.egg/twisted/internet/defer.py", line 915, in ensureDeferred raise ValueError("%r is not a coroutine or a Deferred" % (coro,)) ValueError: &lt;async_generator object start_request at 0x7febb282cf50&gt; is not a coroutine or a Deferred
upvote count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85873087

http://stackoverflow.com/q/49236146
favorite count: 0
type: Question
answer count: 2
upvote count: 2
has body: I am trying to detect bubbles on an OMR sheet which looks something like this: My code for edge detection and contour display is referenced from here. However, before finding the actual contours, I am trying to detect the edges but somehow not able to set the correct values of parameters. This is what I get: Code: from imutils.perspective import four_point_transform from imutils import contours import numpy as np import argparse import imutils import cv2 def auto_canny(image, sigma=0.50): # compute the median of the single channel pixel intensities v = np.median(image) # apply automatic Canny edge detection using the computed median lower = int(max(0, (1.0 - sigma) * v)) upper = int(min(255, (1.0 + sigma) * v)) edged = cv2.Canny(image, lower, upper) # return the edged image return edged # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to the input image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) r = 500.0 / image.shape[1] dim = (500, int(image.shape[0] * r)) # perform the actual resizing of the image and show it image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) equalized_img = cv2.equalizeHist(gray) cv2.imshow('Equalized', equalized_img) # cv2.waitKey(0) blurred = cv2.GaussianBlur(equalized_img, (7, 7), 0) # edged =cv2.Canny(equalized_img, 30, 160) edged = auto_canny(blurred) cv2.imshow('edged', edged) cv2.waitKey(0) How can I get all the 90*4 circles?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/10653433
has answer: http://stackoverflow.com/a/49237565
downvote count: 0
tagged with: python
has title: Python cv2 edge and contour detection
tagged with: opencv
score: 2
has comment: http://stackoverflow.com/comment/112034488
has comment: http://stackoverflow.com/comment/85486338
has comment: http://stackoverflow.com/comment/85476496
has answer: http://stackoverflow.com/a/51443536

http://stackoverflow.com/a/49171876
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Here is one way. Note indexing starts at 0 in Python, so I have changed your inputs accordingly. lst = ['foo', 'bar', 'spam', 'baz', 'qux'] indices = [0, -1] other_list = ['spam'] def magic(lst, indices, other): n = len(lst) idx = {k if k &gt;= 0 else n+k for k in indices} other = set(other) return [j for i, j in enumerate(lst) if (i in idx) or (j in other)] processed_list = magic(lst, indices, other_list) # ['foo', 'spam', 'qux']
accepted answer of: http://stackoverflow.com/q/49171749
type: Answer
answers question: http://stackoverflow.com/q/49171749

http://stackoverflow.com/q/49192052
tagged with: gtktreeview
tagged with: python
tagged with: gtk
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49192965
accepted answer: http://stackoverflow.com/a/49192965
has body: In my GTK3 window I have a Treeview with many items, so I have make it scrollable. I'm using a Scrolledwindow for that: self.codes = Gtk.Treeview() codeswindow = Gtk.ScrolledWindow() codeswindow.add_with_viewport(self.codes) codeswindow.show() When running the application and selecting an item ("selection_changed" event) the Treeview will jump to the top, so the selected item will be out of sight. The same happens when double clicking an item for editing it. After selecting an item I then have to scroll down to the selected item. How do I prevent this? Maybe related: When selecting items using Arrow up or Arrow down the window is not scrolling along.
answer count: 1
has comment: http://stackoverflow.com/comment/85389348
has comment: http://stackoverflow.com/comment/85390167
type: Question
has title: Treeview jumps to top on selecting or editing item
tagged with: gtkscrolledwindow

http://stackoverflow.com/comment/85371797
has text: Thank you. Clearly a brain fart! Maybe I need a break?
type: Comment
comment on: http://stackoverflow.com/a/49182612
type: AnswerComment
score: 1

http://stackoverflow.com/q/49231527
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: To provide some context : I want to write a bulk update query(possibly affecting 0.5 - 1M docs). The update would be in the aspects field (shown below) which are mostly duplicated. My thinking was if I normalised it into another entity (aspect_label), the amount of docs updated would be reduced drastically (say 500-1000 max). Query : I want to find out if there is a way to get linked documents via id in Elastic Search. Eg. if I have documents in index my_db according to the mapping below. Just to point out : processed_reviews is a child of aspect_label { "my_db":{ "mappings":{ "processed_reviews":{ "_all":{ "enabled":false }, "_parent":{ "type":"aspect_label" }, "_routing":{ "required":true }, "properties":{ "data":{ "properties":{ "insights":{ "type":"nested", "properties":{ "aspects":{ "type":"nested", "properties":{ "aspect_label_id":{ "type":"keyword" }, "aspect_term_frequency":{ "type":"long" } } } } }, "preprocessed_text":{ "type":"text" }, "preprocessed_title":{ "type":"text" } } } } } } } } And another entity aspect_label : { "my_db": { "mappings": { "aspect_label": { "_all": { "enabled": false }, "properties": { "aspect": { "type": "keyword" }, "aspect_label_new": { "type": "keyword" }, "aspect_label_old": { "type": "text" } } } } } } Now, I want to write a search query on the processed_reviews type such that the aspect_label_id entity is replaced with the the value of aspect_label_new in the doc or the entire doc in aspect_label matching the id. { "_index":"my_db", "_type":"processed_reviews", "_id":"191b3bff-4915-4404-a05a-10e6bd2b19d4", "_score":1, "_routing":"5", "_parent":"5", "_source":{ "data":{ "preprocessed_text":"Good product I really like so comfortable and so light wait and looks good", "preprocessed_title":"Good choice", "insights":[ { "aspects":[ { "aspect_label":"color", "aspect_term_frequency":1 } ] } ] } } } Also, if there is a better way to approach this problem/ something wrong with my approach or if this is possible or not. Please inform…
tagged with: nosql
has title: Getting linked documents in single lookup query in Elastic Search
has comment: http://stackoverflow.com/comment/85490209
has comment: http://stackoverflow.com/comment/85494165
tagged with: elasticsearch
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85467305
favorite count: 0
type: Question

http://stackoverflow.com/q/49203133
score: 0
has body: Fatal Python error: (pygame parachute) Segmentation Fault Traceback (most recent call last): File "C:\Python34\lib\site-packages\pkg_resources\__init__.py", line 1150, in resource_exists return get_provider(package_or_requirement).has_resource(resource_name) File "C:\Python34\lib\site-packages\pkg_resources\__init__.py", line 1608, in has_resource return self.has(self.fn(self.module_path, resource_name)) File "C:\Python34\lib\site-packages\pkg_resources\__init__.py", line 1663, in _has "Can't perform this operation for unregistered loader type" NotImplementedError: Can't perform this operation for unregistered loader type I converted a python game I had made into an executable file. I then went to install the game and then went to run it. When I ran the executable file (which was just installed) it gives me that error in a cmd prompt and then says that the application stops working. Nothing from the actual game runs, it instantly stops working. I used cx_Freeze to convert it into an executable file. I'm running Python 3.4 and have the correct cx_Freeze installed.
answer count: 1
has title: Error when trying to run an executable of a python file
has comment: http://stackoverflow.com/comment/85411637
type: Question
tagged with: cx-freeze
has answer: http://stackoverflow.com/a/49203152
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85411885
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/125846200
type: AnswerComment
has text: Your answer is not relevant to the question. Please read questions carefully before trying to post any answers.
comment on: http://stackoverflow.com/a/71192182
type: Comment
score: 0

apache-spark-sql
tags question: http://stackoverflow.com/q/49272209
tags question: http://stackoverflow.com/q/49177352
tag name: apache-spark-sql
tags question: http://stackoverflow.com/q/49168338
tags question: http://stackoverflow.com/q/49196607
tags question: http://stackoverflow.com/q/49180047
tags question: http://stackoverflow.com/q/49204024
tags question: http://stackoverflow.com/q/49163141
tags question: http://stackoverflow.com/q/49242550
tags question: http://stackoverflow.com/q/49155388
tags question: http://stackoverflow.com/q/49267331
type: Tag
tags question: http://stackoverflow.com/q/49263438

http://stackoverflow.com/a/49229821
score: 0
answers question: http://stackoverflow.com/q/49228842
type: Answer
has body: If you want to leave the list items with non-duplicate second elements untouched, and the ability to deal with the cases where multiple second items can be duplicate, I think you'll need more than the built-in sort. What my function achieves: Say your list is: table = [[5, 7], [6, 1], [8, 9], [3, 1], [4, 3], [3, 3], [2, 3], [1, 3]] It will not touch the items [5, 7] and [8, 9], but will sort the remaining items by swapping them based on their second elements. The result will be: [[5, 7], [3, 1], [8, 9], [6, 1], [1, 3], [2, 3], [3, 3], [4, 3]] Here is the code: def secondItemSort(table): # First get your second values secondVals = [e[1] for e in table] # The second values that are duplicate dups = [k for k,v in Counter(secondVals).items() if v&gt;1] # The indices of those duplicate second values indices = dict() for d in dups: for i, e in enumerate(table): if e[1]==d: indices.setdefault(d, []).append(i) # Now do the sort by swapping the items intelligently for dupVal, indexList in indices.items(): sortedItems = sorted([table[i] for i in indexList]) c = 0 for i in range(len(table)): if table[i][1] == dupVal: table[i] = sortedItems[c] c += 1 # And return the intelligently sorted list return table Test Let's test on a little bit more complicated table: table = [[5, 7], [6, 1], [8, 9], [3, 1], [4, 3], [3, 9], [3, 3], [2, 2], [2, 3], [1, 3]] Items that should stay in their places: [5, 7] and [2, 2]. Items that should be swapped: [6, 1] and [3, 1]. [8, 9] and [3, 9] [4, 3], [3, 3], [2, 3], [1, 3] Drumroll... In [127]: secondItemSort(table) Out[127]: [[5, 7], [3, 1], [3, 9], [6, 1], [1, 3], [8, 9], [2, 3], [2, 2], [3, 3], [4, 3]]

http://stackoverflow.com/q/49215738
tagged with: python
accepted answer: http://stackoverflow.com/a/49215932
has body: I have two lists with the same len. list1=[0, 1, 1, 1, 0, 0, 0, 1] list2=['ATT', 'TTC', 'TCC', 'CCC', 'CCA', 'CAA', 'AAA', 'AAG'] Note: 1). The number of elements in each list varies, but the two lists always have the same len. 2). list1 only contains integers 0, or 1. It can only contain 0s, only contain 1s, or contain both 0s and 1s. 3). list2 only contains strings with the same length, also for each string k (k is a index &gt;0), list2[k][:-1]=list2[k-1][1:], meaning that if k=2, list[k]='TCC', list[k][:-1]='TC', list[k-1]='TTC', list[k-1][1:]='TC'. Thus, list2[k][:-1]=list2[k-1][1:]. I want to group the strings in list2 based on their corresponding elements in list1 (corresponding: elements in list1 and list2 sharing the same index). If list1[n]==1, then list2[n-1]+list2[n][-1]. If list1[n]==0, and list1[n+1]==0, do nothing. e.g. the corresponding string of the first integer 1 in list2 is 'TTC', then 'ATT', and 'TTC' become 'ATTC'. The corresponding string of the second integer 1 in list2 is 'TCC', then 'ATTC' (Note; already combined), and 'TCC' become 'ATTCC'. Then list1[3]==1, 'ATTCC' and 'CCC' become 'ATTCCC'. list1[7]==1, then 'AAG' ('AAG'=list2[7]) needs to be grouped with its previous string, 'AAA', the two become 'AAAG'. The only condition that you do nothing is when n=0, and n+1=0. That's why, list1[4]==0, and list1[4+1]==0, 'CCA' stays the same. list1[5]==0, and list1[5+1]==0, then list2[5]='CAA' remains unchanged. After transformation, This is the output I want. newlist2=['ATTCCC', 'CCA', 'CAA', 'AAAG'] Obviously the code is not correct. for i in range(1, len(list1)): if list1[i]==1: newlist2[i-1]+newlist2[i][-1] else: do nothing
possible better answer: http://stackoverflow.com/a/49215797
has answer: http://stackoverflow.com/a/49215932
has comment: http://stackoverflow.com/comment/85435917
answer count: 2
has title: python group strings in lists
tagged with: string
type: Question
has answer: http://stackoverflow.com/a/49215797
has comment: http://stackoverflow.com/comment/85436007
type: AnsweredQuestion
score: 0
tagged with: list
tagged with: grouping

http://stackoverflow.com/comment/85523332
score: 0
type: AnswerComment
has text: Found this, and it worked :D `for key in weights: print(weights[key])`
comment on: http://stackoverflow.com/a/49226597
type: Comment

http://stackoverflow.com/q/49243128
score: 0
tagged with: groovy
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49243332
has body: I see this python code and I trying to know if exist any way of do this simple code in groovy Please help me f=open("header.fdf","rb") s=str(f.read()) f.close() s=s.replace(b'PatientName',name)
tagged with: binary
has title: its any way of read a binary file and replace text in groovy like this python code?
has answer: http://stackoverflow.com/a/49243332
tagged with: python
tagged with: replace
type: AnsweredQuestion

http://stackoverflow.com/q/49248732
type: Question
has body: Are there any built-in Python classes that are not instances of type metaclass? &gt;&gt;&gt; type(list) &lt;type 'type'&gt; &gt;&gt;&gt; type(dict) &lt;type 'type'&gt; &gt;&gt;&gt; type(some_builtin_python_class) &lt;type 'some_type_other_than_type'&gt;
tagged with: python
has title: Built-in classes metaclass in Python
type: AnsweredQuestion
tagged with: metaclass
score: 2
upvote count: 2
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49248790
favorite count: 0
has answer: http://stackoverflow.com/a/49248790

http://stackoverflow.com/comment/85375366
type: AnswerComment
has text: I am actually not sure. Was going to tag you under this. I have informed him as well as PyTorch developers. The fix was told in torch community
comment on: http://stackoverflow.com/a/49184744
type: Comment
score: 0

http://stackoverflow.com/q/49264567
score: 1
answer count: 1
has title: Graphics in PyQtGraph not updating after zoom
tagged with: pyqt5
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49264958
tagged with: pyqt
tagged with: python
tagged with: pyqtgraph
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49264958
has body: I have the following PyQtGraph program, which makes a red square "move" when moving a slider: import sys from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import QSlider from pyqtgraph import ( mkBrush, mkPen, GraphicsObject, QtGui, PlotWidget, ) class SquareItem(GraphicsObject): def __init__(self): super().__init__() self.position_picture = QtGui.QPicture() def paint(self, p, *args): p.drawPicture(0, 0, self.position_picture) def boundingRect(self): return QtCore.QRectF(-5, -5, 20, 10) def update_position(self, x): self.position_picture = QtGui.QPicture() painter = QtGui.QPainter(self.position_picture) painter.scale(1, -1) painter.setBrush(mkBrush('r')) painter.setPen(mkPen(None)) painter.drawRect(QtCore.QRectF(x, 0, 1, 1)) painter.end() self.informViewBoundsChanged() class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle('Micromouse maze simulator') self.resize(600, 600) frame = QtWidgets.QFrame() layout = QtWidgets.QVBoxLayout(frame) self.graphics = PlotWidget() self.graphics.setAspectLocked() self.item = SquareItem() self.graphics.addItem(self.item) self.slider = QSlider(QtCore.Qt.Horizontal) self.slider.setSingleStep(1) self.slider.setPageStep(10) self.slider.setRange(0, 10) self.slider.setTickPosition(QSlider.TicksAbove) self.slider.valueChanged.connect(self.slider_value_changed) self.slider.setValue(1) layout.addWidget(self.graphics) layout.addWidget(self.slider) self.setCentralWidget(frame) def slider_value_changed(self, value): self.item.update_position(value) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) main = MainWindow() main.show() sys.exit(app.exec_()) Everything seems to work fine, but if I zoom in/out and then move the slider again the square position is no longer updated (i.e.: the square is not re-drawn). How can I fix that? Updates I am using a square to simplify the problem. In reality, I do not only change position, but I can also draw different shapes, s…
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49187237
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49187362
has answer: http://stackoverflow.com/a/49187362
possible better answer: http://stackoverflow.com/a/49187294
type: Question
has answer: http://stackoverflow.com/a/49187294
answer count: 2
tagged with: function
tagged with: python
has title: loading and manipulating data from a textfile in python
has body: TLDR: I want to print c at the bottom but to do that I have to make arrest and brest float. I cant do that I've made a function that reads a file and separates the first line from the rest I have two files I'm using for this aaa.txt and bbb.txt then i try to manipulate the data. I try squaring each element of each string i realise I need to float it. I followed some guys advice but I still can't multiply stuff is there any way I can make the brest or arrest into an array and rename them a_array. so i can just type a_array**2=h print(h) ? but I'm really struggling to make it work. please copy and paste stuff and see if it works because I've been taking peoples suggestions for hours and nothing works. its 5 am I'm dying over here :( aaa.txt is below test a line 1 3,6,8,99,-4,0.6,8 0,9,7,5,7,9,5 2,2,2,2,2,2,5 7,5,1,2,12,8,0.9 bbb.txt is below test b line 1 1,2,3,4,5,6,7,8 55,0,90,09,1,2,3, 8,9,7,6,8,7,6 3,43,5,8,2,4,1 def mi_func(P): f=open(P, 'r') first = f.readline() restlines= f.readlines() f.close() return first, restlines afirst,arest = mi_func('aaa.txt') bfirst,brest = mi_func('bbb.txt') #this ensures there are no standalone new line characters like ['\n', '5,6'..] arest = [x for x in arest if x != '\n'] brest = [x for x in arest if x != '\n'] for i in range(len(arest)): arest[i] = [float(x)**2 for x in arest[i].strip().split(',') if x != '\n'] for i in range(len(brest)): brest[i] = [float(x) for x in brest[i].strip().split(',') if x != '\n'] print(arest) c=(arest**2)+(brest**2) print(c) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-16-629073a6846e&gt; in &lt;module&gt;() 22 print(arest) 23 ---&gt; 24 c=(arest**2)+(brest**2) 25 print(c) TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'

http://stackoverflow.com/q/49271678
downvote count: 1
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/4355061
upvote count: 2
type: UnansweredQuestion
has body: My output text is long and I want to cut part and add "|" character For 40 width, the output is look like this: [1] This is my text. A very long text. | My text is going outside to terminal | width. Look at the "|" character in | the beginning of any part text. and for 50 width, the output is look like this: [1] This is my text. A very long text. My text | is going outside to terminal width. Look at | the "|" character in the beginning of any part | text. So I'll print : [1] This is my text. A very long text. "\n" | My text is going outside to terminal "\n" | width. Look at the "|" character in "\n" | the beginning of any part text. For 40 width And I'll print : [1] This is my text. A very long text. My text "\n" | is going outside to terminal width. Look at "\n" | the "|" character in the beginning of any part "\n" | text. For 50 width
tagged with: python
has comment: http://stackoverflow.com/comment/85546523
has comment: http://stackoverflow.com/comment/85546922
answer count: 0
has title: How to match long text with terminal width with separator?
score: 1

http://stackoverflow.com/comment/85371589
has text: You can turn any expression statement into a function by adding `def make_result(x):` before it and `return result` after it. Or you can turn any whole suite of statements into a function by just adding `def do_stuff():` before them. Whether either of those gives you what you want depends on what exactly you wanted the function to do.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49182901

http://stackoverflow.com/a/49214373
type: Answer
answers question: http://stackoverflow.com/q/49214304
score: 0
has body: You can use conditional variable used in classical synchronization problem, to avoid busy waiting. You can read more about "Producer consumer" problem. In this case, the producer threads will add one or more items to the queue, whereas a consumer would be a thread waiting for an item in the queue. Look at threading.Condition class for usage and more details. Ref: https://docs.python.org/3/library/threading.html#threading.Condition Edit: If you use Queue class from queue module then you don't have to implement nitty-gritty of thread lock and condition management w.r.t Queue. Ref: https://docs.python.org/3.8/library/queue.html def worker(): while True: item = q.get() if item is None: break do_work(item) q.task_done() q = queue.Queue() threads = [] for i in range(num_worker_threads): t = threading.Thread(target=worker) t.start() threads.append(t) for item in source(): q.put(item) # block until all tasks are done q.join() # stop workers for i in range(num_worker_threads): q.put(None) for t in threads: t.join() In the above example, the worker thread is waiting for the item in the queue. If an item is made available then Queue object will notify the waiting threads and one of them will get the item from the queue.

http://stackoverflow.com/q/49248346
score: 0
has answer: http://stackoverflow.com/a/49248448
has body: I would like to perform a single pass multiple find and replace but ignoring case. I have come across the below that works very well when accepting case sensitivity. Does anyone know how I would utilize a method such as below ignoring the case? import re def multiple_replace(dict, text): regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys()))) return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text) if __name__ == "__main__": text = "Test one, test One, test Two, tEst three" dict = { "Test one" : "Test 1", "Test Two" : "Test 2", "Test three" : "Test 3", } print multiple_replace(dict, text) For example: In the above I would like to see all the keys get mapped to the values ignoring the keys case. If anyone could point me in the right direction this would be appreciated
answer count: 1
type: Question
tagged with: python
type: AnsweredQuestion
has title: Single pass multiple re find and replace ignorecase
accepted answer: http://stackoverflow.com/a/49248448

http://stackoverflow.com/a/75935888
score: 0
has body: To run the job every day, you can use Airflow (GCP Composer) to schedule your execution. You can follow the official documentation here You can complete this task using Airflow operators only, and no need to use Apache Beam or Dataflow. I will recommend you have a look at BigQuery Operators for Airflow here and here A full tutorial here includes the check operator. If you must use Apache Beam, which I don't recommend if you are not doing any transformation and integration of other data sources., then build a dataflow template using your apache beam script to execute your job. You can follow the official documentation here. and you can execute it using Airflow or API calls. You can easily read the data from BigQuery whatever our query is: with beam.Pipeline(options=pipeline_options) as pipeline: # Read from BigQuery load_data_from_bq = ( pipeline | "ReadBigQuery" >> beam.io.ReadFromBigQuery( query=query_string, project=PROJECT, use_standard_sql=True, gcs_location=bqtfs_options.gcs_location.get(), # method="DIRECT_READ" ) # | "printer" >> beam.Map(lambda x: print(type(x))) ) # Writ to BigQuery data_written = ( load_data_from_bq | beam.io.WriteToBigQuery( table='orders_test', dataset='external', project='experimental', schema='field1:type1,field2:type2,field3:type3', write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE, create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED ) ) Last point: Generally speaking, do not use SELECT * FROM table in BigQuery... it is expensive and not the best practice. check here
answers question: http://stackoverflow.com/q/49265480
type: Answer

http://stackoverflow.com/q/49276429
type: Question
has body: I have datetime.now() objects, and I want to know how many hours will pass before a specific hour the next day I've tried this: now = datetime.now() then = datetime.now() + timedelta(days=1) then.hour = 12 # doesn't work hours = then - now But I don't know how can I specify the exact hour for then object
has comment: http://stackoverflow.com/comment/85555277
has comment: http://stackoverflow.com/comment/85555196
has answer: http://stackoverflow.com/a/49276687
type: AnsweredQuestion
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49277554
tagged with: datetime
accepted answer: http://stackoverflow.com/a/49277554
tagged with: python
possible better answer: http://stackoverflow.com/a/49276687
has title: How can I get the difference in the number of hours with a date from the future?
has answer: http://stackoverflow.com/a/49280276

http://stackoverflow.com/comment/85399024
has text: @Adonis I tried to format it to a json format but something wasn't correct, could you describe how this can be done?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49196889
score: 0

http://stackoverflow.com/comment/85333313
has text: @SrinivasSuresh: The `zipapp` module only ships with Python 3.5 and higher, but it can make zipapp's for any version of Python (the `zipapp` module is used to build the zip in the correct format, but isn't needed to run it). Technically, you don't even need the `zipapp` module at all (you can create the necessary zip file manually the same way `zipapp` does), but it makes it a lot simpler.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49163548

http://stackoverflow.com/q/49182255
upvote count: 3
type: UnansweredQuestion
downvote count: 0
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/49183199
score: 3
tagged with: pandas
has title: Executing a function that adds columns and populates them dependig on other columns in Pandas
has body: I have got a dataframe that contains a text and result Text Result 0 some text... True 1 another one... False And I have got a function that does a feature extraction from text - returns dict with about 1000 keys that are words and T/F values depending if the word was in a text. words = ["some", "text", "another", "one", "other", "words"] def extract(text): result = dict() for w in words: result[w] = (w in text) return result Result I am expecting is Text some text another one other words Result 0 some text... True True False False False False True 1 another one... False False True True False False False But I don't know how to apply this on a dataframe? What I have done so far is to create columns with default False value, but I have no clue how to populate it with True values. for feature in words: df[feature] = False I guess that there is better way to do it in pandas?
has answer: http://stackoverflow.com/a/49182402
type: Question
answer count: 2

http://stackoverflow.com/q/49238807
has body: So basically I have two threads, one is running the bottle api, which has a post call. I want to be able to post to this api, and then the api will push some data from the post to the global queue, and the other thread catches this and does something with it. How do I make this queue object accessible from the post call? def publisher(q): while 1: q.get() #do stuff def main(): q = Queue(maxsize=0) b = Process(target=run, kwargs=dict(host='localhost', port=1313, debug=True)) s = Process(target=publisher, args=(q,) b.start() s.start() @post('/process') def my_process(): req_obj = json.loads(request.body.read()) q.put(req_obj)
tagged with: rest
has title: Global queue accessible from bottle API in python
tagged with: python
tagged with: bottle
has answer: http://stackoverflow.com/a/49279106
tagged with: global-variables
type: Question
has comment: http://stackoverflow.com/comment/85484615
score: 0
type: UnansweredQuestion
tagged with: multithreading
answer count: 1

http://stackoverflow.com/a/49207476
score: 1
accepted answer of: http://stackoverflow.com/q/49207240
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
has body: I think maybe you can try a different decode option. In this instance unicode_escape may help.. compose = run.stdout.decode('unicode_escape')
answers question: http://stackoverflow.com/q/49207240

http://stackoverflow.com/q/49252156
tagged with: nlp
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/85508798
type: Question
accepted answer: http://stackoverflow.com/a/49278157
has title: NLP: What is the appropriate way to use engineered features in a sklearn pipeline?
has comment: http://stackoverflow.com/comment/85510317
has body: I'm conducting a text classification task for my first time (twitter sentiment analysis), but I'm unsure of how to incorporate engineered features into my sklearn pipeline. So far I have tried transformations before outputting a classifier. For example: model = Pipeline([('t', 'mean_vectorizer'), ('logreg', LogisticRegression())]) but all of these basic pipelines yield very low scores. So I want to start conducting grid searches and incorporating my own features. So far, my data set (X_train) is such that the rows are tweets (single string). This is the format handled by mean_vectorizer (and tfidf_vectorizer if I use it). Incorporating new features Take for example 1 new feature, a boolean value for whether or not a positive word exists (just a basic example). I would create a (len(X_train), 1)-dimensional array of boolean values corresponding to each tweet. My ideas: After preprocessing the tweets, tokenize them and replace the words with values from a word2index dict. Pad the tweets to equal length, and then concatenate this array with my features. Then pass this into the Pipeline as normal. Maybe there is a way in which these features can be passed individually into the Pipeline? Maybe the transformations will have issues using an array of integers instead of strings? Question Could someone please advise on the best way to go forward with this using sklearn. Assume that the data is a list of sentences (training separate from testing) and each sentence is a single string. I think this will be a really helpful for other people starting out with NLP, so please be as general as possible.
has answer: http://stackoverflow.com/a/49278157
tagged with: python

http://stackoverflow.com/a/49177910
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85361670
type: Answer
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/49177748
has comment: http://stackoverflow.com/comment/85363187
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49177748
has body: Like any other use of square brackets, Union[int, str] is implemented by Union.__getitem__((int, str)). In this case, Union is an instance of the class _Union which defines __getitem__. You don't really need to know those details to use the class.
has comment: http://stackoverflow.com/comment/85361837

http://stackoverflow.com/comment/85432553
comment on: http://stackoverflow.com/a/49213977
type: Comment
type: AnswerComment
score: 0
has text: thank you so much mate! How can I learn this? The reason for my question is that I am finding my self always asking questions on this topic and I can not know how to import sublime to an editor to learn how sublime text uses the commands see my unanswered question on this topic https://stackoverflow.com/questions/49200465/python-pip-install-sublime-not-working

http://stackoverflow.com/a/49247455
upvote count: 2
has body: one line code: m_list = [(y2_val-y1_val)/(x2-x1) for y1_val in y1 for y2_val in y2] x1 = 10.18182 x2 = 13.14286 y1 = (0.30097,0.31036,0.3911,0.34255,0.198374,0.398574,0.377364,0.2428,0.319312,0.13338,0.228027,0.242637,0.326533) y2 = (0.536551,0.450893,0.299292,0.286737,0.438004,0.272566,0.42541,0.430583,0.282882,0.285569,0.286261,0.439658) m_list = [(y2_val-y1_val)/(x2-x1) for y1_val in y1 for y2_val in y2] print m_list
score: 2
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49247407
answers question: http://stackoverflow.com/q/49247407
type: AcceptedAnswer

http://stackoverflow.com/a/49179710
answers question: http://stackoverflow.com/q/49176961
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85367817
has body: from bs4 import BeautifulSoup import re HTML='''&lt;body&gt;...''' soup = BeautifulSoup(HTML,'lxml').body child= soup.find_next(lambda x: re.search('&lt;',str(x))) print(child) print(child.find_next_sibling(lambda x: re.search('&lt;',str(x)))) soup.find_next() finds the next element (and next element only), because you want to find the next tags without knowing the tag (search for "&lt;", if returns true, grabs that element). soup.find_next_sibling() will find the next sibling of the tag(i.e. the next lateral tag, in this case class="story"

http://stackoverflow.com/comment/85426217
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49209915
has text: Nice answer! Thank you very much! I didn't check the documentation carefully.
type: AnswerComment

http://stackoverflow.com/a/49140441
has comment: http://stackoverflow.com/comment/85286432
type: Answer
has comment: http://stackoverflow.com/comment/85286357
score: 0
has comment: http://stackoverflow.com/comment/85286263
has body: Looks like a good excuse to use zip, sorted, and reversed in one method. A = {0: {'a': 1, 'b': 7, 'weight': 0.6}, 1: {'a': 5, 'b': 5, 'weight': 0.3}, 2: {'a': 4, 'b': 6, 'weight': 0.1}} # Make sorted list from A.items(), sorted by weight: a_list = sorted(list(A.items()), key=lambda item: item[1]['weight']) # Make a reversed copy of that list: b_list = reversed(A_list) A = {} for a_item, b_item in zip(a_list, b_list): a_item[1]['inverse_weight'] = b_item[1]['weight'] A[a_item[0]] = a_item[1]
answers question: http://stackoverflow.com/q/49140169

http://stackoverflow.com/a/76406080
has body: I had the same error. In my case, the declaration inside the constructor was in the wrong order. A method tried to read from the attribute, before it was set. Most of the simple __init__-code does not care about order. But you just cannot read from a variable that has not been set yet.
answers question: http://stackoverflow.com/q/49258892
score: 0
type: Answer

http://stackoverflow.com/a/49208397
has comment: http://stackoverflow.com/comment/85421487
type: Answer
has comment: http://stackoverflow.com/comment/88342573
has body: From the staticmethod documentation: A static method does not receive an implicit first argument. ... It can be called either on the class (such as C.f()) or on an instance (such as C().f()). You still need to self reference the object. Otherwise, the interpreter will be looking for a top level function named hello. class Test: @staticmethod def hello(): print("static method is on") def hey(self): self.hello() t = Test() t.hey() out: "static method is on" Test.hey() out: "static method is on" Hopefully, this example explains better. def hello(): print("this is not the static method you are loking for") class Test: @staticmethod def hello(): print("static method is on") def hey(self): hello() t = Test() t.hey() out: "this is not the static method you are loking for"
answers question: http://stackoverflow.com/q/49208365
downvote count: 0
has comment: http://stackoverflow.com/comment/85421439
upvote count: 1
score: 1

http://stackoverflow.com/comment/85463916
type: QuestionComment
comment on: http://stackoverflow.com/q/49145852
score: 0
has text: Sorry, but I am confused - How is possible match `Horror Horror - FRANKESTIEN - Multi Total no_of_prize` columns by accepted answer?
type: Comment

http://stackoverflow.com/q/49230658
tagged with: tkinter
has body: I would like to apply customized stylenames defined in a class to widgets found in other classes. How can I implement this? Below is a test script for consideration. I would like to apply stylenames 'page.TFrame' and 'press.TButton' to classes Page1 and Page2 Test script: #!/usr/bin/python3 # -*- coding: utf-8 -*- # tkinter modules import tkinter as tk import tkinter.ttk as ttk import tkinter.font as tkFont class App(ttk.Frame): def __init__(self, parent=None, *args, **options): # Extract key and value from **options using Python3 "pop" function: # pop(key[, default]) self.style = options.pop('style',ttk.Style()) self.bg0 = options.pop('background1','light grey') self.bg1 = options.pop('background2','grey') self.fg0 = options.pop('fg_link','black') self.fg1 = options.pop('fg_text','white') self.font = options.pop('font',tkFont.Font(family='Nimbus Roman No9 L', size='10', weight='normal')) # Initialise App Frame ttk.Frame.__init__(self, parent, style='self.TFrame') self.__setFont() self.__setStyle() self.__createPages(parent) def __setFont(self): """Set the fonts to be used to build the App GUI.""" self.fontTitle = self.font.copy() self.fontTitle.config(size='30') self.font.config(size='13') def __setStyle(self): """Customise ttk styles""" ## LoginPanel styles self.style.configure('self.TFrame', background='pink') self.style.configure('page.TFrame', background=self.bg0) self.style.configure('press.TButton', font=self.fontTitle, background=self.bg0, foreground=self.fg0, relief='raised') def __createPages(self, parent): """Create Login and NewUser pages.""" self._frames = {} for F in (Page1, Page2): page_name = F.__name__ frame = F(parent=self) self._frames[page_name] = frame frame.grid(row=0, column=0, sticky="nsew") self.showFrame("Page1") parent.rowconfigure(0, weight=1) parent.columnconfigure(0, weight=1) def showFrame(self, page_name): '''Show a frame for the given page name''' frame = self._frames[page_name] frame.tkraise() class Page1(ttk.Frame): def __init__(se…
answer count: 1
has title: tkinter: How to apply customized ttk stylename that is defined in one class to other classes
tagged with: ttk
tagged with: python
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49231797
accepted answer: http://stackoverflow.com/a/49231797
type: Question

http://stackoverflow.com/comment/85502139
type: QuestionComment
has text: First, remove the `()` and then print out `list_of_functions[i].__name__`
score: 0
comment on: http://stackoverflow.com/q/49249383
type: Comment

http://stackoverflow.com/q/49207257
type: Question
has body: How can I remove all brackets and marks using python. Here's my code in flask-python: @app.route('/login',methods=['GET','POST']) def login(): username = db.session.query(User.username).order_by(User.username.desc()).limit(1).all() return render_template("index.html",user = username) and in my html file just {{user}} and the result in browser is like: [('tshibek',)] How can I remove all of this and to only get the nickname tshibek. The second question is I want to have an example of 10 last rows (I know how do that) but what I don't know is how to display this nickname like links to the profile, every nickname to another line like the link to the profile. example: I have rows nickname: tshibe,tshibek,wasda,something and i wanna get in HTML link localhost//profil/tshibe localhost//profil/tshibek localhost//profil/wasda ... I dont know how to start with that, can someone show me a way to do that ?
tagged with: python
tagged with: flask
answer count: 1
tagged with: flask-sqlalchemy
type: AnsweredQuestion
score: 0
has title: Remove brackets from selected row sqlalchemy
upvote count: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49207358
has answer: http://stackoverflow.com/a/49207358

http://stackoverflow.com/q/49225933
tagged with: arrays
tagged with: python
has comment: http://stackoverflow.com/comment/85455664
has answer: http://stackoverflow.com/a/49226113
accepted answer: http://stackoverflow.com/a/49226113
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85455598
score: 0
tagged with: list
possible better answer: http://stackoverflow.com/a/49226542
has answer: http://stackoverflow.com/a/49226542
linked to: http://stackoverflow.com/q/49064548
has comment: http://stackoverflow.com/comment/85456389
type: Question
tagged with: numpy
has title: When turning a list of lists of tuples to an array, how can I stop tuples from creating a 3rd dimension?
has comment: http://stackoverflow.com/comment/85455609
has comment: http://stackoverflow.com/comment/85455524
answer count: 2
has comment: http://stackoverflow.com/comment/85455573
has body: I have a list of lists (each sublist of the same length) of tuples (each tuple of the same length, 2). Each sublist represents a sentence, and the tuples are bigrams of that sentence. When using np.asarray to turn this into an array, python seems to interpret the tuples as me asking for a 3rd dimension to be created. Full working code here: import numpy as np from nltk import bigrams arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) bi_grams = [] for sent in arr: bi_grams.append(list(bigrams(sent))) bi_grams = np.asarray(bi_grams) print(bi_grams) So before turning bi_grams to an array it looks like this: [[(1, 2), (2, 3)], [(4, 5), (5, 6)], [(7, 8), (8, 9)]] Output of above code: array([[[1, 2], [2, 3]], [[4, 5], [5, 6]], [[7, 8], [8, 9]]]) Converting a list of lists to an array in this way is normally fine, and creates a 2D array, but it seems that python interprets the tuples as an added dimension, so the output is of shape (3, 2, 2), when in fact I want, and was expecting, a shape of (3, 2). The output I want is: array([[(1, 2), (2, 3)], [(4, 5), (5, 6)], [(7, 8), (8, 9)]]) which is of shape (3, 2). Why does this happen? How can I achieve the array in the form/shape that I want?

sql-server
tags question: http://stackoverflow.com/q/49259839
tags question: http://stackoverflow.com/q/49198761
tags question: http://stackoverflow.com/q/49217448
tags question: http://stackoverflow.com/q/49252636
tags question: http://stackoverflow.com/q/49251226
type: Tag
tags question: http://stackoverflow.com/q/49261287
tags question: http://stackoverflow.com/q/49138864
tags question: http://stackoverflow.com/q/49181433
tags question: http://stackoverflow.com/q/49268589
tag name: sql-server
tags question: http://stackoverflow.com/q/49231063

http://stackoverflow.com/comment/85440407
has text: I'm looking for the similarity between each `x[n, :]` and `y[n, :]` - this should give me `n` results
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49218285
score: 0

http://stackoverflow.com/q/49263066
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49263446
has title: Pandas Data Frame Average Values
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49263248
tagged with: data-analysis
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/49263248
possible better answer: http://stackoverflow.com/a/49263446
tagged with: dataframe
score: 1
has comment: http://stackoverflow.com/comment/85538769
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85529891
downvote count: 0
has body: I have a large dataset that looks like this: Year Month Day Hour Count Value 2017 1 1 1 59 0 .. .. .. .. .. .. 2011 12 29 23 60 12 I am trying to use Pandas to generate averages for the Value column for the same month,day,and hour. I've used this in the past: df = pd.read_csv('pathtofile/values.csv') df1 = df.groupby([df.Month,df.Day,df.Hour]).mean() however the new df1 will not average the Value column, it does however provide an average for the Count and Year column (which are of no interest to me). I'm thinking that this has something to do with the data in the Value column as most of the values are zero. I've tried replacing all the zero values with null values however to no avail. Is there something that I'm missing?
has comment: http://stackoverflow.com/comment/85529946

http://stackoverflow.com/comment/85401315
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49198027
has text: Pretty much contradictory statements `generated by the javascript` & `wait for presence by class`

http://stackoverflow.com/q/49177716
tagged with: python-xarray
has comment: http://stackoverflow.com/comment/85380499
has title: How to index data based on multi-dimension physical coordinates of xarray
tagged with: pandas
has answer: http://stackoverflow.com/a/49186916
score: 0
answer count: 1
type: Question
tagged with: numpy
type: UnansweredQuestion
has body: Here is a content of xarray.DataArray T2, which is a variable of netcdf file. t2 Out[107]: &lt;xarray.DataArray 'T2' (Time: 37, south_north: 87, west_east: 87)&gt; array([[[ 301.933167, 301.936584, ..., 301.620209, 301.607941], [ 301.920776, 301.924011, ..., 301.599274, 301.586975], ..., [ 301.045288, 301.036804, ..., 300.311218, 300.303253], [ 301.041595, 301.033081, ..., 300.309479, 300.301727]], [[ 296.742706, 296.72821 , ..., 296.217377, 296.214142], [ 296.763031, 296.739899, ..., 296.148071, 296.144348], ..., [ 296.089752, 296.044952, ..., 295.49353 , 295.468292], [ 296.100159, 296.062836, ..., 295.492157, 295.468506]], ..., [[ 300.907532, 300.923737, ..., 298.770752, 298.690582], [ 300.775482, 300.850494, ..., 298.792206, 298.726898], ..., [ 300.170013, 300.139709, ..., 298.117035, 298.107849], [ 299.788116, 299.756744, ..., 298.397705, 298.410217]], [[ 299.074066, 299.143402, ..., 296.732635, 296.73407 ], [ 299.060425, 299.158508, ..., 296.767517, 296.765015], ..., [ 298.227905, 298.278107, ..., 297.223846, 297.228607], [ 298.114319, 298.189362, ..., 297.272247, 297.263367]]], dtype=float32) Coordinates: XLAT (Time, south_north, west_east) float32 39.3806 39.3806 39.3807 ... XLONG (Time, south_north, west_east) float32 -86.6092 -86.5972 ... XTIME (Time) datetime64[ns] 2012-09-01 2012-09-01T02:00:00 ... Dimensions without coordinates: Time, south_north, west_east Attributes: FieldType: 104 MemoryOrder: XY description: TEMP at 2 M units: K stagger: And the logical coordinates are south_north, west_east, we can select a certain value of some location by t2.sel() with integer index. t2.sel(south_north=1,west_east=2) Out[109]: &lt;xarray.DataArray 'T2' (Time: 37)&gt; array([ 301.927094, 296.76532 , 295.752228, 295.106781, 294.282013, 294.570129, 294.170654, 297.319458, 300.523773, 301.585907, 301.843323, 301.846832, 299.142914, 297.261993, 296.037292, 296.437103, 295.210114, 294.92511 , 295.933716, 296.18924 , 297.529388, 298.79248 , 299.271606, 298.389435, 296.37…
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85378822

http://stackoverflow.com/a/49226994
has comment: http://stackoverflow.com/comment/85493665
downvote count: 0
upvote count: 1
has body: For the first problem: Mathematically, arr1 = array([[ 0.8, -0.2, -0.2, -0.2, -0.2], [-0.2, 0.8, -0.2, -0.2, -0.2], [-0.2, -0.2, 0.8, -0.2, -0.2], [-0.2, -0.2, -0.2, 0.8, -0.2], [-0.2, -0.2, -0.2, -0.2, 0.8]]) is equivalent to arr1 = -0.2 * [[1,1,1,1,1,], + 1 [1,1,1,1,1,], 1 [1,1,1,1,1,], 1 [1,1,1,1,1,], 1 [1,1,1,1,1,]] 1 = [1] [1, 1, 1, 1, 1] * 0.2 + 1 [1] 1 [1] 1 [1] 1 [1] 1 Thus, it can be generated using -0.2 * np.outer([1,1,1,1,1], [1,1,1,1,1]) + scipy.sparse.identity(5) For the second problem, let me abuse the notation -0.2* [1] [1, 1, 1, 1, 1] @ B + scipy.sparse.identity(5) @ B [1] [1] [1] [1] can be reduced to np.outer([1, 1, 1, 1, 1], B.sum(axis=0)) * -0.2 + scipy.sparse.identity(5) @ B One needs not really compute np.outer([1, 1, 1, 1, 1], B.sum(axis=0)) as this would be a dense square matrix that the memory may not fit. (Note that the outer product is basically repeats B.sum(axis=0) in every row it contains.) To recover the results in a memory efficient way, you only need to store B.sum(axis=0) and scipy.sparse.identity(5) @ B .
score: 1
answers question: http://stackoverflow.com/q/49223219
type: Answer
has comment: http://stackoverflow.com/comment/85494619

http://stackoverflow.com/comment/85435837
score: 0
comment on: http://stackoverflow.com/q/49211981
has text: You cannot use text data. You need to completely replace it by using different techniques.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85302391
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49148592
score: 0
has text: Fixed used a basic if statement to replace none type with 'None' (text rather than None type) then when loading it i do the reverse. Thanks to everyone who helped!

http://stackoverflow.com/a/49177542
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49177153
has body: Read the guide thorougly before doing a spider. To populate items, you should use an Item Loader, that can have post and pre-processors useful for your purpose. For duplication, you can use a custom pipeline.
type: Answer
accepted answer of: http://stackoverflow.com/q/49177153

http://stackoverflow.com/a/49143578
has comment: http://stackoverflow.com/comment/99150334
answers question: http://stackoverflow.com/q/49142505
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49142505
has comment: http://stackoverflow.com/comment/85292714
has comment: http://stackoverflow.com/comment/85292785
type: AcceptedAnswer
type: Answer
score: 13
has comment: http://stackoverflow.com/comment/85292589
has body: There is no cross-inheritance between object and type. In fact, cross-inheritance is impossible. # A type is an object isinstance(int, object) # True # But an object is not necessarily a type isinstance(object(), type) # False What is true in Python is that... Everything is an object Absolutly everything, object is the only base type. isinstance(1, object) # True isinstance('Hello World', object) # True isinstance(int, object) # True isinstance(object, object) # True isinstance(type, object) # True Everything has a type Everything has a type, either built-in or user-defined, and this type can be obtained with type. type(1) # int type('Hello World') # str type(object) # type Not everything is a type That one is fairly obvious isinstance(1, type) # False isinstance(isinstance, type) # False isinstance(int, type) # True type is its own type This is the behaviour which is specific to type and that is not reproducible for any other class. type(type) # type In other word, type is the only object X in Python such that type(X) is X type(type) is type # True # While... type(object) is object # False This is because type is the only built-in metaclass. A metaclass is simply a class, but its instances are also classes themselves. So in your example... # This defines a class class Foo(object): pass # Its instances are not types isinstance(Foo(), type) # False # While this defines a metaclass class Bar(type): pass # Its instances are types MyClass = Bar('MyClass', (), {}) isinstance(MyClass, type) # True # And it is a class x = MyClass() isinstance(x, MyClass) # True
upvote count: 13

http://stackoverflow.com/comment/85302589
comment on: http://stackoverflow.com/a/49148820
type: Comment
has text: You may need to pull a running `p` variable out of the `iframe_calculator`
score: 0
type: AnswerComment

http://stackoverflow.com/a/49229596
downvote count: 0
has body: The Django way of doing this is to define the directory for templates in your settings file 'DIRS': [os.path.join(BASE_DIR, 'templates')], Hence, just add this line to your TEMPLATES setting and then you are good to go. Django automatically searches templates in the directories you pass and you just need to give template name in the render method.
type: Answer
answers question: http://stackoverflow.com/q/49228009
score: 2
upvote count: 2

http://stackoverflow.com/comment/85564364
type: AnswerComment
comment on: http://stackoverflow.com/a/49271683
has text: Can you keep it here for future reference? I'm not going to use it for this but I find it interesting.
type: Comment
score: 0

http://stackoverflow.com/q/49186864
has answer: http://stackoverflow.com/a/49187803
downvote count: 0
has comment: http://stackoverflow.com/comment/85379175
possible better answer: http://stackoverflow.com/a/49186913
has body: I am trying to write a program which will outputs as shown below: father is repeated 2 times where is repeated 1 time art is repeated 1 time are is repeated 1 time thou is repeated 1 time This is what I have for now: x = input('Please enter a string: ').lower() def counter(): counts = dict() words = str.split(x) for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 print(counts) return counts counter() It prints out like this: Please enter a string: father father where art are thou {'father': 2, 'where': 1, 'art': 1, 'are': 1, 'thou': 1} How can I print out the data in the format as shown above?
has answer: http://stackoverflow.com/a/49187019
has comment: http://stackoverflow.com/comment/85379212
has answer: http://stackoverflow.com/a/49186913
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49186889
tagged with: python
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/49186889
has title: Printing dictionary key-value pairs with placeholder string
favorite count: 0
score: 2
tagged with: printing
upvote count: 2
has comment: http://stackoverflow.com/comment/85379452

http://stackoverflow.com/q/49257433
tagged with: web
tagged with: web-scraping
has title: How to close yet another chrome popup using python selenium
linked to: http://stackoverflow.com/q/41649916
favorite count: 0
has comment: http://stackoverflow.com/comment/85519637
type: Question
has body: Link to "chrome_options.add_extension(r'C:\Users\Administrator\Desktop\chromedriver_win32\extension.crx')" Here is my code: import os from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from time import gmtime, strftime from os import system import pyperclip import datetime import time import os import sys executable_path = r"C:\Users\Administrator\Desktop\chromedriver_win32\chromedriver.exe" os.environ["webdriver.chrome.driver"] = executable_path chrome_options = Options() chrome_options.add_extension(r'C:\Users\Administrator\Desktop\chromedriver_win32\extension.crx') driver = webdriver.Chrome(executable_path=executable_path, chrome_options=chrome_options) time.sleep(4) driver.get("https://www.tradingview.com/chart/gK6Rq0UH/") time.sleep(4) driver.find_element_by_xpath("""//*[@id="footer-chart-panel"]/div[2]/span[4]""").click() time.sleep(4) while True: driver.find_element_by_xpath("""//*[@id="bottom-area"]/div[2]/div[1]/div[2]/ul/li[4]""").click() time.sleep(2) contents = pyperclip.paste() time.sleep(2) filepath = r"C:\Users\Administrator\Desktop\DATA.txt" time.sleep(2) with open(filepath, 'w') as f: # 'w' means write mode and we get the file object as f f.write(contents) time.sleep(5) i tried this code, but it didn't helps driver.switchTo().alert().accept(); this code don't work too driver.send_keys("Enter") if i right-click on popup there is simply no action, so i cant find XPath, class id this is sources that (autoview) extension, i assume that this code generate this popup function clipboard(format, data) { const tmp = document.oncopy; document.oncopy = function cl…
upvote count: 2
has answer: http://stackoverflow.com/a/49272654
tagged with: python
has comment: http://stackoverflow.com/comment/85520138
tagged with: selenium-webdriver
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49272654
downvote count: 0
answer count: 1
tagged with: selenium

http://stackoverflow.com/comment/85400416
has text: @FahimShahriar, I think you missed adding an additional slash between `'Downloads'` and `'books'`. It should be `C:\\Users\HP\Downloads\\book\\just.txt'`.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49197601

http://stackoverflow.com/a/49259194
has comment: http://stackoverflow.com/comment/85521811
answers question: http://stackoverflow.com/q/49258986
downvote count: 0
has comment: http://stackoverflow.com/comment/85521548
score: 3
upvote count: 3
type: Answer
has body: if you can enter all elements you want to test in a set, it means that all unhashable elements don't belong to your set (because you can't put them in) You could do: if x.__hash__ and x in {None,False}: when object isn't hashable, x.__hash__ is None (other alternatives: Asking "is hashable" about a Python value) and the second part isn't evaluated. or (better ask forgiveness than permission): def belongs(x): try: return x in {None,False} except TypeError: # unhashable type return False both solutions are faster than using a list or tuple ((None,False)), because there's no linear search involved (that is if there are a lot of elements in the test list, not true for only 2 elements)
has comment: http://stackoverflow.com/comment/85521579

websocket
tags question: http://stackoverflow.com/q/49154106
tags question: http://stackoverflow.com/q/49129451
tags question: http://stackoverflow.com/q/49131111
tag name: websocket
tags question: http://stackoverflow.com/q/49195721
tags question: http://stackoverflow.com/q/49140450
type: Tag
tags question: http://stackoverflow.com/q/49139025

http://stackoverflow.com/comment/85377289
has text: @Julien `return bool(blah)`
type: QuestionComment
comment on: http://stackoverflow.com/q/49185754
score: 0
type: Comment

http://stackoverflow.com/q/49210506
has comment: http://stackoverflow.com/comment/85426224
has body: I need to get the values of all the neighbors around an element in a matrix in python. Suppose I have a matrix like below, matrix=[ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] For the first element i.e., matrix[0][0], the neighbors are [2,5,6]. For matrix[0][1], the neighbors are [1,3,5,6,7]. For matrix[0][2], the neighbors are [2,4,6,7,8]. For a given element, i need to get these list of values. I can do the same by comparing i,j values when i=0,j=0 get matrix[0][1], matrix[1][0], matrix[1][1] using switch case and so. But it will become lengthy code. Is there any inbuilt function or any module to make the above task even simpler?
downvote count: 1
accepted answer: http://stackoverflow.com/a/49210813
tagged with: nearest-neighbor
favorite count: 0
has comment: http://stackoverflow.com/comment/85426227
tagged with: python-3.x
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49210618
has comment: http://stackoverflow.com/comment/85443856
tagged with: python
has comment: http://stackoverflow.com/comment/85443806
upvote count: 6
type: Question
has answer: http://stackoverflow.com/a/49210813
tagged with: list
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/85446553
tagged with: matrix
has title: How to get all the values of neighbours around an element in matrix?
has answer: http://stackoverflow.com/a/49210618

http://stackoverflow.com/a/49198075
has comment: http://stackoverflow.com/comment/85401022
score: -3
has body: You could do df.groupby(Credit_Card).count() then whatever operation you needed to from there
type: Answer
answers question: http://stackoverflow.com/q/49197937
upvote count: 0
downvote count: 3

http://stackoverflow.com/q/49187493
tagged with: python
has comment: http://stackoverflow.com/comment/85380557
score: 2
answer count: 0
has title: How to paginate a list with python django
downvote count: 0
has comment: http://stackoverflow.com/comment/85380239
favorite count: 0
type: Question
has body: I have a code that call a rest-full service that return a list,i want make the pagination but i have some problems. this is my code: results = requests.get(url) col = results.json() page = request.GET.get('page', 1) paginator = Paginator(tuple(col), 10) try: proc = paginator.page(page) except PageNotAnInteger: proc = paginator.page(1) except EmptyPage: proc = paginator.page(paginator.num_pages) When i run my code the variable proc does not have any information. Note: I noted the service return a pagination, for that my code don't work. I change the service and now the service only send the list, and my code work. But if i want that my service send the pagination how i can receive and manage the pagination in my code.
upvote count: 2
type: UnansweredQuestion
tagged with: pagination
tagged with: django

http://stackoverflow.com/q/49186198
has body: I able to get raw javascript raw data from a link to a list datatype but unable to convert it to Pandas Dataframe. import re import request headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'} page = requests.get('http://www.sgx.com/JsonRead/JsonstData?qryId=RAll',headers=headers) data = re.findall(r'items:(.*)',page.content) print data ["[{ID:0,N:'2ndChance W200123',SIP:'',NC:'CDWW',R:'',I:'',M:'',LT:0,C:0,VL:0.000,BV:6099.000,B:'0.007',S:'0.009',SV:7278.300,O:0,H:0,L:0,V:0.000,SC:'5',PV:0.009,P:0,BL:'100',P_:'X',V_:''},{ID:1,N:'3Cnergy',SIP:'',NC:'502',R:'',I:'',M:'t',LT:0,C:0,VL:0.000,BV:130.000,B:'0.022',S:'0.025',SV:100.000,O:0,H:0,L:0,V:0.000,SC:'2',PV:0.021,P:0,BL:'100',P_:'X',V_:''},{ID:2,N:'3Cnergy W200528',SIP:'',NC:'1E0W',R:'',I:'',M:'t',LT:0,C:0,VL:0.000,BV:0,B:'',S:'0.004',SV:50.000,O:0,H:0,L:0,V:0.000,SC:'5',PV:0.002,P:0,BL:'100',P_:'X',V_:''}..}]}" check the type(data), it is shown as list. However, when I pd.DataFrame(data), the output does not shown as a proper dataframe. Instead, it is 0 [{ID:0,N:'2ndChance W200123',SIP:'',NC:'CDWW',... a weird format. How shall I get a neat and tidy dataframe?
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/85378175
has comment: http://stackoverflow.com/comment/85380409
has answer: http://stackoverflow.com/a/49186432
has comment: http://stackoverflow.com/comment/85380112
has answer: http://stackoverflow.com/a/49188144
has comment: http://stackoverflow.com/comment/85377968
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49186317
possible better answer: http://stackoverflow.com/a/49186317
has comment: http://stackoverflow.com/comment/85377972
has answer: http://stackoverflow.com/a/49186901
has comment: http://stackoverflow.com/comment/85380196
tagged with: python
accepted answer: http://stackoverflow.com/a/49188144
has comment: http://stackoverflow.com/comment/85377930
has title: Python: unable to convert list to Pandas dataframe
answer count: 4
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/85386168
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49189075
has text: yes sorry, I forgive my Join part, where I join my first RDD which each mean and count
score: 0

http://stackoverflow.com/q/49209712
has answer: http://stackoverflow.com/a/52871015
downvote count: 0
tagged with: python
tagged with: unit-testing
has body: I'm working on unittesting some python3 code that calls sendmail on an SMTP class via a context manager and attempts to catch exceptions to log them. I can successfully mock the SMTP class and do some checking on it in other tests (e.g. verifying that send_message was actually called), but I can't seem to get the method call to send_message on the class to raise an exception to log the error. Code to be tested (from siteidentity_proxy_monitoring.py): def send_alert(message, email_address): with SMTP('localhost') as email: try: email.send_message(message) except SMTPException: # retry the send print('exception raised') # debugging statement try: email.send_message(message) except: logging.error( 'Could not send email alert to %s', email_address ) Unittest method: @unittest.mock.patch('siteidentity_proxy_monitoring.SMTP') @unittest.mock.patch('siteidentity_proxy_monitoring.logging') def test_logging_when_email_fails(self, mock_logger, mock_smtp): """ Test that when alert email fails to send, an error is logged """ test_print('Testing logging when email send fails') email_instance = mock_smtp.return_value email_instance.send_message.side_effect = SMTPException siteidentity_proxy_monitoring.send_alert( 'test message', 'email@example.com' ) mock_logger.error.assert_called_with( 'Could not send email alert to %s', 'email@example.com' ) Output from the test result: [TEST] ==&gt; Testing logging when email send fails F ====================================================================== FAIL: test_logging_when_email_fails (__main__.TestSiteidentityMonitors) ---------------------------------------------------------------------- Traceback (most recent call last): File "/lib/python3.6/unittest/mock.py",line 1179, in patched return func(*args, **keywargs) File "tests/siteidentity_monitor_tests.py", line 108, in test_logging_when_email_fails 'Could not send email alert to %s', 'email@example.com' File "/lib/python3.6/unittest/mock.py", line 805, in assert_called_with raise Ass…
has answer: http://stackoverflow.com/a/57386593
score: 1
tagged with: python-unittest
upvote count: 1
has comment: http://stackoverflow.com/comment/85426463
has comment: http://stackoverflow.com/comment/85424672
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85423925
tagged with: python-3.x
answer count: 2
has title: Python mocking exception to method calls in a context manager
tagged with: mocking
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85424729

http://stackoverflow.com/comment/85528577
type: QuestionComment
has text: Actually, if the return value is a bool, you might want to use `0` for either true (or whichever of true/false best matches "success", if it's more about success than truth) and 1 for false (or maybe some other value between 2 and 127 for whichever one best matches "failure").
score: 0
comment on: http://stackoverflow.com/q/49248036
type: Comment

http://stackoverflow.com/q/49198786
tagged with: language-design
upvote count: 2
has title: Python list() function update to accept a non-iterable?
has comment: http://stackoverflow.com/comment/85403271
has comment: http://stackoverflow.com/comment/85403262
score: 1
has comment: http://stackoverflow.com/comment/85402866
accepted answer: http://stackoverflow.com/a/49199087
downvote count: 1
has comment: http://stackoverflow.com/comment/85403648
has comment: http://stackoverflow.com/comment/85402623
favorite count: 0
has answer: http://stackoverflow.com/a/49199087
type: Question
has comment: http://stackoverflow.com/comment/85404404
has comment: http://stackoverflow.com/comment/85402770
has body: I've been working on a "learning project" which involves several short single-parameter functions, where the parameter might be either a numeric type or a list of numerics. E.g., def magnitude_of(v): try: return math.sqrt(sum([vi**2 for vi in v])) except: return abs(v) This of course is necessary because if I did this: def magnitude_of(v): return math.sqrt(sum([vi**2 for vi in list(v)])) ...the code would fail because list() only accepts an iterable as an argument. My question is: has there ever been consideration given at PSW to letting list() work with any argument? If so, what prevented the change from being implemented?
has comment: http://stackoverflow.com/comment/85403115
has comment: http://stackoverflow.com/comment/85402605
possible better answer: http://stackoverflow.com/a/66646103
tagged with: python
has answer: http://stackoverflow.com/a/66646103
has comment: http://stackoverflow.com/comment/85531475
has comment: http://stackoverflow.com/comment/85403050
has comment: http://stackoverflow.com/comment/85403121
has comment: http://stackoverflow.com/comment/85402671
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85402822
answer count: 2
has comment: http://stackoverflow.com/comment/85402716

http://stackoverflow.com/a/49264259
has comment: http://stackoverflow.com/comment/85532325
accepted answer of: http://stackoverflow.com/q/49264076
has body: Get the counts with getnnz method and then replicate and divide in-place into its flattened view obtained with data method - s = A.getnnz(axis=1) A.data /= np.repeat(s, s) Inspired by Row Division in Scipy Sparse Matrix 's solution post : Approach #2. Sample run - In [15]: from scipy.sparse import csr_matrix In [16]: A = csr_matrix([[6, 0, 0, 4, 0], [3, 18, 0, 9, 0]]) In [18]: s = A.getnnz(axis=1) ...: A.data /= np.repeat(s, s) In [19]: A.toarray() Out[19]: array([[3, 0, 0, 2, 0], [1, 6, 0, 3, 0]]) Note: To be compatible between Python2 and 3, we might want to use // - A.data //= ...
type: AcceptedAnswer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/49264076
has comment: http://stackoverflow.com/comment/85532344
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/85532339

http://stackoverflow.com/q/49153978
type: Question
has body: I am trying to download this url which is a frame on this page. I have tried like this: import urllib.request url = 'https://tips.danskespil.dk/tips13/?#/tps/poolid/2954' response = urllib.request.urlopen(url) html = response.read() and also this way: import requests page = requests.get(url) but both ways give me the error: SSL: CERTIFICATE_VERIFY_FAILED request.get Any help would be much appriciated.
duplicate of: http://stackoverflow.com/q/34503206
tagged with: python
has comment: http://stackoverflow.com/comment/85312495
linked to: http://stackoverflow.com/q/34503206
type: AnsweredQuestion
score: 0
has title: SSL: CERTIFICATE_VERIFY_FAILED request.get
answer count: 1
has answer: http://stackoverflow.com/a/49154033
accepted answer: http://stackoverflow.com/a/49154033
has comment: http://stackoverflow.com/comment/85312977

http://stackoverflow.com/q/49240332
type: AnsweredQuestion
has body: I've switched from NamedStyle to just regular styles, which seems to work better for me. Now I'm just stuck on trying to fill a single row and column-- I have some over engineered bits that work, but I'm curious why the colA bit doesn't. Gives me an AtrributeError. import openpyxl from openpyxl.utils import get_column_letter from openpyxl.styles import PatternFill, Border, Side, Alignment wb = openpyxl.load_workbook('example5.xlsx') sheet = wb['Sheet1'] day = '' week = ('MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY') sheet['A2'] = 'Monday' sheet['A3'] = 'Tuesday' sheet['A4'] = 'Wednesday' sheet['A5'] = 'Thursday' sheet['A6'] = 'Friday' sheet['A7'] = 'Saturday' sheet['A8'] = 'Sunday' sheet['A1'] = 'Day' sheet['B1'] = 'In' sheet['C1'] = 'Out' sheet['D1'] = 'Total Hours' sheet['E1'] = 'ST Hours' sheet['F1'] = 'OT Hours' sheet['G1'] = 'ST Rate' sheet['H1'] = 'OT Rate' while day not in week: day = input('What day of the week is it? ') day = day.upper() def sheetStyle(var): sheet['B' + var].number_format = 'H:MM AM/PM' sheet['F' + var].number_format = 'H:MM AM/PM' sheet['C' + var].number_format = 'H:MM AM/PM' sheet['E' + var].number_format = 'General' sheet['F' + var].number_format = '#,##0.00' sheet['G' + var].number_format = '[$$]#,##0.00' sheet['H' + var].number_format = '[$$]#,##0.00' sheet['B' + var] = input('Enter the time you clocked in: ') sheet['C' + var] = input('Enter the time you clocked out: ') sheet['D' + var] = '=MOD(C' + var + '-B' + var + ',1)*24' sheet['E' + var] = '=D' + var + '-F' + var sheet['F' + var] = '=MAX(D' + var + '-8,0)' sheet['G' + var] = '=E' + var + '*15' sheet['H' + var] = '=F' + var + '*22.5' def sheetInput(day=''): for i, w in enumerate(week): if day == w: sheetStyle(str(i + 2)) grayFill = PatternFill(start_color='D0CECE', end_color='D0CECE', fill_type='solid') whiteFill = PatternFill(start_color='FFFFFF', end_color='FFFFFF', fill_type='solid') for columns in sheet.iter_cols(min_col=None, max_col=None, min_r…
has comment: http://stackoverflow.com/comment/85528085
tagged with: python
linked to: http://stackoverflow.com/q/45055488
type: Question
score: 2
has comment: http://stackoverflow.com/comment/85505830
has answer: http://stackoverflow.com/a/49263431
has title: Changing style for one row or column in OpenPyxl
upvote count: 2
tagged with: openpyxl
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85527599
accepted answer: http://stackoverflow.com/a/49263431
favorite count: 0
tagged with: excel
has comment: http://stackoverflow.com/comment/85530250

http://stackoverflow.com/a/49276576
downvote count: 0
has body: I think the best is create dictionary of list by DataFrame.to_dict: np.random.seed(456) df = pd.DataFrame(np.random.randint(0,10,size=(10, 4)), columns=list('ABCD')) print (df) A B C D 0 5 9 4 5 1 7 1 8 3 2 5 2 4 2 3 2 8 4 8 4 5 6 0 9 5 8 2 3 6 6 7 0 0 3 7 3 5 6 6 8 3 8 9 6 9 5 1 6 1 d = df.to_dict('l') print (d['A']) [5, 7, 5, 2, 5, 8, 7, 3, 3, 5] If really want A, B, C and D lists: for k, v in df.to_dict('l').items(): globals()[k] = v print (A) [5, 7, 5, 2, 5, 8, 7, 3, 3, 5]
accepted answer of: http://stackoverflow.com/q/49276214
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49276214
type: Answer
has comment: http://stackoverflow.com/comment/85555890

http://stackoverflow.com/a/49211492
answers question: http://stackoverflow.com/q/49211312
type: Answer
has comment: http://stackoverflow.com/comment/85439729
has body: Always use for loop when there are fixed known no: of iterations. Use while when the iterations are unknown like the no: of iterations are calculated from the program dynamically(for example finding Armstrong no:). #check syntax for python if version 3 above, i use 2.7 for i in List: #taking each list out of List as i if len(i)&gt;=2: #to retrieve second element the list should have print(i[1]) #atleast 2 elements
score: 0

http://stackoverflow.com/comment/85450572
has text: Looking at your expected output, why is there a break in the series between the `'1'` and `'6'` of the first two elements of your output `['5', '4', '3', '2', '1'],['6', '7', '8', '9']`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49223147
score: 0

http://stackoverflow.com/q/49279466
has body: I want to build Docker container with python 3.6 and few dependencies. Here is my Dockerfile: FROM noondotcom/alpine-3.6-python-3.6-grpc COPY requirements.txt /requirements.txt RUN python3.6 -m pip install --upgrade pip RUN python3.6 -m pip install -r requirements.txt CMD ["python3.6", "-m requests"] docker build -f Dockerfile . executed without errors and I see all libs in requirements.txt are installed But when I run docker run I got "No module named requests" message. How I can fix that?
tagged with: dockerfile
has answer: http://stackoverflow.com/a/49280014
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49280416
possible better answer: http://stackoverflow.com/a/49280416
has comment: http://stackoverflow.com/comment/85562143
tagged with: python
accepted answer: http://stackoverflow.com/a/49280014
tagged with: docker
type: AnsweredQuestion
score: 0
answer count: 2
has title: Can't see python libs inside Docker image
has comment: http://stackoverflow.com/comment/85562407

http://stackoverflow.com/comment/85350523
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49171240
has text: warning: Debugger speedups using cython not found. Run '"C:\Users\Owner\AppData\Local\Programs\Python\Python36-32\python.exe" "C:\Users\Owner\.p2\pool\plugins\org.python.pydev.core_6.3.1.201802272029\pysrc\setup_cython.py" build_ext --inplace' to build. pydev debugger: starting (pid: 14296) Traceback (most recent call last): File "C:\Users\Owner\.p2\pool\plugins\org.python.pydev.core_6.3.1.201802272029\pysrc\pydevd.py", line 1621, in <module> main() And a host of other errors
score: 0

http://stackoverflow.com/comment/85462901
comment on: http://stackoverflow.com/a/49229831
score: 0
type: Comment
has text: What exactly is a ufunc?
type: AnswerComment

http://stackoverflow.com/comment/85340492
has text: @user4815162342: Ah, I'm not too surprised that the extra overhead of a function call isn't worth it, even to [GMP's lightweight `mpn` functions](https://gmplib.org/manual/Low_002dlevel-Functions.html) that don't do any memory allocation. The functions have lots of pointer args that the compiler has to put in registers instead of accessing with whatever addressing mode, and even just a function call at all clobbers registers.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49154022

http://stackoverflow.com/comment/85472185
comment on: http://stackoverflow.com/q/49234502
score: 0
type: QuestionComment
has text: Please add a data sample of your df. Dates have no "x Days" - that is a string output from somewhere. Read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
type: Comment

http://stackoverflow.com/a/49157516
upvote count: 4
has comment: http://stackoverflow.com/comment/85319941
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85320043
downvote count: 0
has comment: http://stackoverflow.com/comment/85319996
has comment: http://stackoverflow.com/comment/85320156
accepted answer of: http://stackoverflow.com/q/49157255
has comment: http://stackoverflow.com/comment/85319792
has body: You could use type.__new__(type(cls), cls.__name__, cls.__bases__, dict(cls.__dict__)). This uses the normal type creation process, but creates an instance of type(cls) instead of type. As for the __metaclass__ issue, I think that is because __metaclass__ is usually what is called, so type can't use it.
type: Answer
answers question: http://stackoverflow.com/q/49157255
score: 4

http://stackoverflow.com/comment/85418315
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49206561
has text: Do you want `mylist` to be global or belong to `MyClass`? What is the purpose of `MyClass`?
score: 0

http://stackoverflow.com/q/49257867
type: Question
tagged with: http://stackoverflow.com/tag/r
tagged with: satellite
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85519287
score: 2
has title: What is a simple way to extract NDVI average from polygon [Sentinel 2 L2A]
upvote count: 2
has body: Currently, I am working on a project for a non-profit organization. Therefore, I need the average NDVI values for certain polygons. Input for my search: Group of coördinates (polygon) a range of dates (e.g. 01-31-2017 and 02-31-2017) What I now want is: the average NDVI value of the most recent picture in that given date range with 0% cloud coverage of the given polygon Is there a simple way to extract these values via an API (in R or Python)? I prefer working with the sentinel-hub, but I am not sure if it's the best platform to extract the data I need. Because I am working time series I should use the L2A version (there is an NDVI layer).
answer count: 1
downvote count: 0
tagged with: gis
has answer: http://stackoverflow.com/a/62542674
favorite count: 0

http://stackoverflow.com/q/49169051
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/127694992
has title: How to dynamically set the number of jobs in Waf
type: Question
tagged with: waf
type: UnansweredQuestion
downvote count: 0
has body: I am using Waf to automate the building process of my project. The problem is that I have two kinds of parallelization. The first one is by using a switch for the job number meaning parallel processes when running Waf on the command line. $ python waf.py build -j4 The second kind of parallelization happens in some scripts which are executed by Waf and which cannot be rewritten to use Waf's parallelization. To keep the amount of threads used stable, I have to interrupt the build process and change the job switch. Is there a way to do this dynamically so that I can specify for a certain folder that tasks are run using 5 threads or something else? Thanks for your help!
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49199543
has comment: http://stackoverflow.com/comment/85362595
score: 1

http://stackoverflow.com/a/50094640
has body: If you don't need to access or process all of the data at once then you can load it in chunks. If it's a csv file and if you can use pandas then maybe you can do it like this: import pandas as pd for chunk in pd.read_csv('dataset/movies.csv', chunksize=1000): # use this chunk for processing and/or training Hope it helps!
score: 0
answers question: http://stackoverflow.com/q/49152221
type: Answer

http://stackoverflow.com/comment/85367683
type: Comment
has text: @JohnAnderson Have you dragged the scatter?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49178348

http://stackoverflow.com/comment/85315143
type: AnswerComment
has text: Thank you for the answer. The only point of trying to do it in the manner I described in the question, was my ambition to change as little as possible and avoid mistakes when replacing instances of {{ user }}, especially with regard to performance optimization. But I accept the answer as correct, although it appears my ambition will not be realized this time. :) Your proposed solution is the path I expected to be necessary if my attempt were impossible anyway. Thanks again!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49136673

http://stackoverflow.com/comment/85543899
comment on: http://stackoverflow.com/a/49259380
score: 1
has text: Well everytime I change something to fit the assumptions I get no result and errors, the code I have right now is the closest I get to passing the doctest
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85415000
comment on: http://stackoverflow.com/q/49204861
score: 0
has text: What kind of graph?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49142567
score: 1
favorite count: 0
has body: conda command was working fine from Anaconda prompt. I created a new environment for tensorflow after which it says - 'conda' is not recognized as an internal or external command,operable program or batch file. I have checked all my PATH variables, and root, scripts and lib folder paths are added to the PATH. It just does not recognize any commands - conda, activate, deactivate, any of these.
type: Question
possible better answer: http://stackoverflow.com/a/57350144
has answer: http://stackoverflow.com/a/49346022
accepted answer: http://stackoverflow.com/a/49346022
answer count: 2
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/57350144
type: AnsweredQuestion
has title: Conda not recognized as internal or external after creating new environment
tagged with: anaconda

http://stackoverflow.com/q/49222171
has body: I have a json file placed in s3. The s3 url is similar to the below one: https://s3-eu-region-1.amazonaws.com/dir-resources/sample.json But in pyspark when pass the same, It is not reading the file. path = "https://s3-eu-region-1.amazonaws.com/dir-resources/sample.json" df=spark.read.json(path) But I am able to download it through browser.
type: UnansweredQuestion
tagged with: python
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85537540
tagged with: amazon-web-services
answer count: 1
favorite count: 0
has title: Read file data from aws s3 pyspark
type: Question
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/49222316
tagged with: pyspark
linked to: http://stackoverflow.com/q/30851244

http://stackoverflow.com/comment/85332747
type: QuestionComment
comment on: http://stackoverflow.com/q/49163239
has text: Please [edit] the question and word it better. I'd start by improving the title, right now it's pretty unclear what the question is about.
score: 0
type: Comment

http://stackoverflow.com/q/49196758
has comment: http://stackoverflow.com/comment/85399055
has comment: http://stackoverflow.com/comment/85400804
has title: Vectorizing a double sum with j < i+1
has body: I need to calculate a double sum, which now I'm doing in a double for loop as follows: k = 3 sumterm = 0.0 for i in range(k): for j in range(i+1): sumterm = i+2*j I would like to vectorize this sum, though what I'm stuck on is, I'm not just summing every combination of i and j, but just of j &lt; i+1. How would I vectorize this?
has comment: http://stackoverflow.com/comment/85400670
has comment: http://stackoverflow.com/comment/85398620
answer count: 1
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/85398687
has answer: http://stackoverflow.com/a/49198331
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85399261
has comment: http://stackoverflow.com/comment/85398395
favorite count: 0
has comment: http://stackoverflow.com/comment/85401108
has comment: http://stackoverflow.com/comment/85399538
accepted answer: http://stackoverflow.com/a/49198331
score: 2
type: AnsweredQuestion
tagged with: python-2.7

http://stackoverflow.com/a/49229452
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49229415
has comment: http://stackoverflow.com/comment/85462818
type: Answer
has body: Skip the header column using skiprows=1 and header=None. This automatically loads in a dataframe with integer headers starting from 0 onwards. df = pd.read_csv('test.csv', skiprows=1, header=None).rename(columns=lambda x: x + 1) df 1 2 3 0 0 0 0 The rename call is optional, but if you want your headers to start from 1, you may keep it in. If you have a MultiIndex, use set_levels to set just the 0th level to integer: df.columns = df.columns.set_levels( df.columns.get_level_values(0).astype(int), level=0 )
score: 3

http://stackoverflow.com/q/49231824
has title: How to submit a mock url?
favorite count: 0
has comment: http://stackoverflow.com/comment/85530485
type: Question
has comment: http://stackoverflow.com/comment/85467045
has body: I have a problem, I can't test my forms by using requests. add_playlist = self.client.post(reverse('new-playlist'), data={'url': 'https://dailyiptvlist.com/dl/it-m3uplaylist-2018-03-11-1.m3u'}) I need to create a mock response for 'https://dailyiptvlist.com/dl/fr-m3uplaylist-2018-03-06.m3u' so it will be acceptable to test adding a channel while the url isn't maintained. So, I need to create a mock response for this url. I can't imagine how to do this. Please help me.
tagged with: python
has comment: http://stackoverflow.com/comment/85551453
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85467473
has comment: http://stackoverflow.com/comment/85467293
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49232954
downvote count: 0
tagged with: django
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49232954
answer count: 1

http://stackoverflow.com/comment/85364765
type: QuestionComment
has text: This is not a UTF-8 encoded text file, so your problem is wrong from the start. From those first two bytes showing up as "missing character" glyphs, I'd guess this is BOM-encoded UTF-16.
comment on: http://stackoverflow.com/q/49179633
score: 0
type: Comment

for-loop
tags question: http://stackoverflow.com/q/49221453
tags question: http://stackoverflow.com/q/49203568
tags question: http://stackoverflow.com/q/49219335
tags question: http://stackoverflow.com/q/49159102
tags question: http://stackoverflow.com/q/49261197
tags question: http://stackoverflow.com/q/49134988
tags question: http://stackoverflow.com/q/49241719
tags question: http://stackoverflow.com/q/49134404
tags question: http://stackoverflow.com/q/49178947
tags question: http://stackoverflow.com/q/49221151
tags question: http://stackoverflow.com/q/49188342
tags question: http://stackoverflow.com/q/49262171
tags question: http://stackoverflow.com/q/49279387
tags question: http://stackoverflow.com/q/49143628
tags question: http://stackoverflow.com/q/49174910
tags question: http://stackoverflow.com/q/49216350
tags question: http://stackoverflow.com/q/49169725
type: Tag
tags question: http://stackoverflow.com/q/49269877
tags question: http://stackoverflow.com/q/49237785
tags question: http://stackoverflow.com/q/49191952
tags question: http://stackoverflow.com/q/49271526
tags question: http://stackoverflow.com/q/49181460
tags question: http://stackoverflow.com/q/49193792
tags question: http://stackoverflow.com/q/49202647
tags question: http://stackoverflow.com/q/49247268
tags question: http://stackoverflow.com/q/49148668
tags question: http://stackoverflow.com/q/49166670
tags question: http://stackoverflow.com/q/49224224
tags question: http://stackoverflow.com/q/49236218
tag name: for-loop
tags question: http://stackoverflow.com/q/49278321
tags question: http://stackoverflow.com/q/49235318
tags question: http://stackoverflow.com/q/49152082
tags question: http://stackoverflow.com/q/49242992
tags question: http://stackoverflow.com/q/49275560
tags question: http://stackoverflow.com/q/49145136
tags question: http://stackoverflow.com/q/49260004
tags question: http://stackoverflow.com/q/49203269
tags question: http://stackoverflow.com/q/49275996
tags question: http://stackoverflow.com/q/49216494
tags question: http://stackoverflow.com/q/49224917
tags question: http://stackoverflow.com/q/49258269
tags question: http://stackoverflow.com/q/49131012

http://stackoverflow.com/a/49193346
upvote count: 2
has comment: http://stackoverflow.com/comment/85392553
type: AcceptedAnswer
downvote count: 0
has body: Modern versions of sklearn expect 2D array as X, so try to reshape it as it was suggested in the error message: In [7]: clf.fit(X.reshape(-1,1), y) Out[7]: LogisticRegression(C=100000.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1, penalty='l2', random_state=None, solver='liblinear', tol=0.0001, verbose=0, warm_start=False) BTW, sklearn 0.19.1 gives me a clear error message: In [10]: sklearn.__version__ Out[10]: '0.19.1' In [11]: clf.fit(X, y) ... skipped ... ValueError: Expected 2D array, got 1D array instead: array=[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. UPDATE: full code: In [41]: %paste import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model import sklearn X = np.array([0,1,2,3,4,5,6,7,8,9,10,11]) y = np.array([0,0,0,0,1,0,1,0,1,1,1,1]) print('SkLearn version: {}'.format(sklearn.__version__)) clf = linear_model.LogisticRegression(C=1e5) clf.fit(X.reshape(-1,1), y) ## -- End pasted text -- SkLearn version: 0.19.1 Out[41]: LogisticRegression(C=100000.0, class_weight=None, dual=False, fit_intercept=True, intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1, penalty='l2', random_state=None, solver='liblinear', tol=0.0001, verbose=0, warm_start=False)
answers question: http://stackoverflow.com/q/49193286
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/49193286

http://stackoverflow.com/q/49135929
has title: Keras Binary Classification - Sigmoid activation function
tagged with: sigmoid
tagged with: tensorflow
has answer: http://stackoverflow.com/a/49137346
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/62976198
score: 21
tagged with: python
upvote count: 21
has body: I've implemented a basic MLP in Keras with tensorflow and I'm trying to solve a binary classification problem. For binary classification, it seems that sigmoid is the recommended activation function and I'm not quite understanding why, and how Keras deals with this. I understand the sigmoid function will produce values in a range between 0 and 1. My understanding is that for classification problems using sigmoid, there will be a certain threshold used to determine the class of an input (typically 0.5). In Keras, I'm not seeing any way to specify this threshold, so I assume it's done implicitly in the back-end? If this is the case, how is Keras distinguishing between the use of sigmoid in a binary classification problem, or a regression problem? With binary classification, we want a binary value, but with regression a nominal value is needed. All I can see that could be indicating this is the loss function. Is that informing Keras on how to handle the data? Additionally, assuming Keras is implicitly applying a threshold, why does it output nominal values when I use my model to predict on new data? For example: y_pred = model.predict(x_test) print(y_pred) gives: [7.4706882e-02] [8.3481872e-01] [2.9314638e-04] [5.2297767e-03] [2.1608515e-01] ... [4.4894204e-03] [5.1120580e-05] [7.0263929e-04] I can apply a threshold myself when predicting to get a binary output, however surely Keras must be doing that anyway in order to correctly classify? Perhaps Keras is applying a threshold when training the model, but when I use it to predict new values, the threshold isn't used as the loss function isn't used in predicting? Or is not applying a threshold at all, and the nominal values outputted happen to be working well with my model? I've checked this is happening on the Keras example for binary classification, so I don't think I've made any errors with my code, especially as it's predicting accurately. If anyone could explain how this is working, I would greatly appreciate it. H…
accepted answer: http://stackoverflow.com/a/49137346
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85277052
downvote count: 0
has answer: http://stackoverflow.com/a/62976198
tagged with: neural-network
tagged with: keras

http://stackoverflow.com/comment/85459586
has text: Yeah the stack is retained in memory until the return is complete. I think the code can be made clearer by changing the return statement to be like this `temp = quickSort(smaller) + [lst[0]] + quickSort(larger)` and then `return temp`. Now we can see that the line that calls the functions isn't returning yet, these are being called from within a function. So, 2 new stacks are being created for `smaller` and `larger`. Then the function only returns after those two subcalls are returned.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49227868
type: AnswerComment

http://stackoverflow.com/q/49188162
tagged with: random
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49197763
has comment: http://stackoverflow.com/comment/85383152
linked to: http://stackoverflow.com/q/14933577
has title: Efficiently yield elements from large list in (pseudo) random order
has body: I am experimenting with unrolling a few nested loops for (potentially) better performance at the expense of memory. In my scenario, I would end up with a list of about 300M elements (tuples), which I'd have to yield in (more or less) random order. At this order of magnitude, random.shuffle(some_list) really is not the way to go anymore. The below example illustrates the issue. Be aware, on an x86_64 Linux and CPython 3.6.4, it will eat about 11 GByte of memory. def get_random_element(): some_long_list = list(range(0, 300000000)) for random_item in some_long_list: yield random_item My thinking so far is to simply generate one random index per iteration and yield randomly picked elements (indefinitely) from the list. It may yield certain elements multiple times and totally skip others, which would be a trade-off worth considering. What other options do I have within reasonable bounds of memory and CPU time to possibly yield every element of the list only once?
tagged with: python
score: 11
upvote count: 11
tagged with: generator
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49197763

printing
tags question: http://stackoverflow.com/q/49186864
tags question: http://stackoverflow.com/q/49205128
tags question: http://stackoverflow.com/q/49213807
tags question: http://stackoverflow.com/q/49226391
tags question: http://stackoverflow.com/q/49223576
tags question: http://stackoverflow.com/q/49186115
tags question: http://stackoverflow.com/q/49163978
tags question: http://stackoverflow.com/q/49200523
type: Tag
tags question: http://stackoverflow.com/q/49269631
tags question: http://stackoverflow.com/q/49131630
tag name: printing
tags question: http://stackoverflow.com/q/49245161
tags question: http://stackoverflow.com/q/49229538
tags question: http://stackoverflow.com/q/49271187
tags question: http://stackoverflow.com/q/49271750
tags question: http://stackoverflow.com/q/49204936
tags question: http://stackoverflow.com/q/49137643

http://stackoverflow.com/comment/85424821
type: Comment
comment on: http://stackoverflow.com/q/49209916
type: QuestionComment
has text: I'm sorry I'm a beginner, I don't understand what i'm supposed to do with the `int(' ')` ...
score: 0

http://stackoverflow.com/comment/85408012
type: Comment
type: QuestionComment
has text: Hitting swap is not going to be pleasant, but I would expect the machine to chug along and finish, and not glitch out with no error messages. I was hoping that the SO community could guide me towards debugging this.
comment on: http://stackoverflow.com/q/49201203
score: 0

http://stackoverflow.com/q/49270477
score: 8
type: AnsweredQuestion
has body: Couple of questions about this For occasions when I'd like to do something like the following in Tensorflow (assume I'm creating training examples by loading WAV files): import tensorflow as tf def _some_audio_preprocessing_func(filename): # ... some logic here which mostly uses Tensorflow ops ... with tf.Session(graph=tf.Graph()) as sess: wav_filename_placeholder = tf.placeholder(tf.string, []) wav_loader = io_ops.read_file(wav_filename_placeholder) wav_decoder = contrib_audio.decode_wav(wav_loader, desired_channels=1) data = sess.run( [wav_decoder], feed_dict={wav_filename_placeholder: filename}) return data dataset = tf.data.Dataset.list_files('*.wav') dataset = dataset.map(_some_preprocessing_func) If I have a parse_image() function that uses tensor ops - should this be part of the main Graph? Following the example set in Google's own audio TF tutorial, it looks like they create a separate graph! Doesn't this ruin the point of using Tensorflow to make things faster? Do I use tf.py_func() any time any single line isn't from the tensorflow library? Again, I wonder what the performance implications are and when I should use this... Thanks!
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49279970
tagged with: tensorflow
tagged with: tensorflow-datasets
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49279970
has title: Tensorflow Dataset .map() API
upvote count: 8
tagged with: python

http://stackoverflow.com/comment/85316559
type: Comment
comment on: http://stackoverflow.com/q/49155875
type: QuestionComment
has text: @Geo Yes. Also it's redundant to declare them as globals in the global scope.
score: 0

http://stackoverflow.com/q/49193417
tagged with: ete3
has comment: http://stackoverflow.com/comment/85391675
upvote count: 2
type: UnansweredQuestion
score: 1
answer count: 1
tagged with: etetoolkit
has answer: http://stackoverflow.com/a/53851617
has title: ete3 module on python3 - cannot import TreeStyle, faces, AttrFace, NodeStyle
downvote count: 1
has comment: http://stackoverflow.com/comment/85392057
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
has body: I a linux user and so far I've using ete3 in python2 succesfully. I installed ete3 for python3 and there are certain modules that python3 can't find. I believe I have all the dependencies installed according to the instructions. I can import ete3, and Tree from ete3 but not any other that I've using so far. Any clues on how to resolve this? ~$ python3 Python 3.4.3 (default, Nov 28 2017, 16:41:13) [GCC 4.8.4] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import ete3 &gt;&gt;&gt; from ete3 import Tree &gt;&gt;&gt; from ete3 import TreeStyle Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name 'TreeStyle' &gt;&gt;&gt; from ete3 import faces Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name 'faces' &gt;&gt;&gt; from ete3 import AttrFace Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name 'AttrFace' &gt;&gt;&gt; from ete3 import NodeStyle Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name 'NodeStyle'

http://stackoverflow.com/comment/85543536
has text: I assume there's a reason you can't virtualenv your way out of this, right?
comment on: http://stackoverflow.com/q/49270195
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49201115
has comment: http://stackoverflow.com/comment/85407905
has comment: http://stackoverflow.com/comment/85408276
type: Answer
has body: I take it that the real question is “Why does Python's abs return integer values for integer arguments but floating point values for complex numbers with a plain integer value.” Concerning the argument and result types of abs there are three main cases: argument is integer ⇒ result is integer; so it's safe to say that abs(-5) returns an integer (5). argument is real (floating point) ⇒ result is real; so abs(5.1) returns a floating point number (5.1). argument is complex ⇒ the result is a floating point number but the decision whether it has an exact integer value depends on the values of the real/imaginary parts of the argument. This decision in the last case is far from trivial: abs(5+0i) has an integer value, so has abs(3+4i) (Pythagoras) but abs(5+2i) has not. In other words, it would not make sense to create an "integer complex" type and provide an abs implementation for it; the result would in most cases not be integer. So it is quite sensible not to extend the integer/real distinction into the fields of complex numbers. (It would work for addition but the practical benefit would be close to zero.)
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49200609
score: 3
has comment: http://stackoverflow.com/comment/85409342
has comment: http://stackoverflow.com/comment/85427352

http://stackoverflow.com/comment/85290072
comment on: http://stackoverflow.com/q/49141621
type: QuestionComment
has text: Maybe it is the website you are trying to connect to that is refusing the connection..
type: Comment
score: 0

http://stackoverflow.com/a/49190438
type: Answer
accepted answer of: http://stackoverflow.com/q/49190411
score: 2
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49190411
downvote count: 0
has body: Use str.contains + np.where: df['Call me soon'] = np.where( df.Chat.str.contains('(?&lt;=P1).*?call me soon.*?(?=P2)'), 'Yes', 'No' ) df ID Chat Call me soon 0 1 P1: Please call me soon P2 - will call you Yes 1 2 P2: Please call me soon P1 - will call you No Regex Details (?&lt;=P1) # lookbehind, match P1 .*? # any character - non-greedy call me soon .*? (?=P2) # lookahead, match P2

http://stackoverflow.com/a/49206357
upvote count: 2
answers question: http://stackoverflow.com/q/49206319
type: AcceptedAnswer
downvote count: 0
has body: The simplest option would be a view function (i.e. a function linked to a URL that receives a GET or POST request) in your app which does the scraping and immediately returns the results by rendering a template. For example you could have a starting page with a form and when that form is submitted that will create a POST request which will contain details that the view can use to decide which page to scrape and so on. This doesn't require Javascript or database models. If you're not comfortable with Django yet, consider starting with Flask instead as it's simpler to get going.
type: Answer
accepted answer of: http://stackoverflow.com/q/49206319
score: 2

pipeline
type: Tag
tags question: http://stackoverflow.com/q/49259396
tags question: http://stackoverflow.com/q/49190887
tag name: pipeline

http://stackoverflow.com/comment/85252447
type: Comment
type: QuestionComment
has text: Possible duplicate of [Does Python support short-circuiting?](https://stackoverflow.com/questions/2580136/does-python-support-short-circuiting)
comment on: http://stackoverflow.com/q/49123594
score: 0

http://stackoverflow.com/comment/85364438
has text: You wanted a generator, and you got a generator. What's the problem?
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49179509

http://stackoverflow.com/comment/85412715
has text: Have you tried to repro this on another machine (A VM would also do it)? I remember to have had also some issues with the same Python and Windows version, and discarded it over a third-party IDE.
type: QuestionComment
comment on: http://stackoverflow.com/q/49203567
score: 0
type: Comment

http://stackoverflow.com/comment/85284757
type: Comment
comment on: http://stackoverflow.com/a/49134708
score: 0
type: AnswerComment
has text: It depends when you want to access the `Candle` data. You can access the data while you are in the `for` loop in `constructTrades`; or you can access it outside of your classes after the `g = GatherCandles(...)` reference in another `for` loop. See my post for an example of each...

http://stackoverflow.com/comment/85454496
score: 0
comment on: http://stackoverflow.com/q/49225383
type: Comment
has text: Your example code produces only NaNs. Can you look at it again?
type: QuestionComment

http://stackoverflow.com/comment/85260034
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49126067
has text: i have added a line before the else part in your view, check it and add it

http://stackoverflow.com/comment/85253594
has text: @Nae: What you want to understand ? if it is about global variable or why i do this read [this](http://www.diveintopython.net/html_processing/locals_and_globals.html)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49124158
score: 0

http://stackoverflow.com/a/49191882
type: Answer
has comment: http://stackoverflow.com/comment/85389633
answers question: http://stackoverflow.com/q/49191509
downvote count: 0
upvote count: 1
score: 1
has body: The problem is the redirection. It is not handled by the program but by the shell. So you have 2 options here: spawn a shell to process the indirection: rc = call(cmdline, cwd=dir, shell=True) directly pass the file as standard input to the command cmdline = "mysql --user=root -p new_db" rc = call(cmdline, stdin=open("D:\Test\sprint381.sql"), cwd=dir)

hardware
tags question: http://stackoverflow.com/q/49169474
tag name: hardware
type: Tag

http://stackoverflow.com/a/49238432
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
has body: The pdfminer function is set up to skip key errors, (the calling function is in a try except that passes after a key error) but misses the error when it's an out of range error. You can fix this by changing the original function, as follows: import re from pdfminer.psparser import PSLiteral from pdfminer.glyphlist import glyphname2unicode from pdfminer.latin_enc import ENCODING STRIP_NAME = re.compile(r'[0-9]+') def edit_name2unicode(name): """Converts Adobe glyph names to Unicode numbers.""" if name in glyphname2unicode: return glyphname2unicode[name] m = STRIP_NAME.search(name) # print('name: '+name) # print('m: '+str(m)) if not m or m&gt;110000: raise KeyError(name) return unichr(int(m.group(0))) pdfminer.encodingdb.name2unicode = edit_name2unicode Note at the end that you have to set the old function to the new function, after having imported pdfminer for the document as a whole. This is a runtime workaround, for a process you have to complete more than once, I'd change the source document instead, especially since pdfminer doesn't have good class structure that you can inherit and overwrite easily. IF, however, there are key errors for characters you want to keep, you can add them to the pypdf glyphlist or add another character set encoding, here.
accepted answer of: http://stackoverflow.com/q/49238324
answers question: http://stackoverflow.com/q/49238324
score: 1

http://stackoverflow.com/q/49126375
has answer: http://stackoverflow.com/a/49126904
tagged with: python
has comment: http://stackoverflow.com/comment/85257614
has comment: http://stackoverflow.com/comment/85257672
has comment: http://stackoverflow.com/comment/85257518
type: AnsweredQuestion
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85257534
accepted answer: http://stackoverflow.com/a/49126904
tagged with: directory
has comment: http://stackoverflow.com/comment/85257625
has title: read all files in a subfolder python
has comment: http://stackoverflow.com/comment/85257839
type: Question
has comment: http://stackoverflow.com/comment/85257600
has body: I have a folder structure as &gt;root &gt; foldername1 &gt; subfoldername1 &gt; subfoldername2 &gt; subfoldername3 &gt; foldername2 &gt; subfoldername1 &gt; subfoldername2 &gt; subfoldername3 &gt; foldername3 &gt; subfoldername1 &gt; subfoldername2 &gt; subfoldername3 I would like to list all the file contained in the 'subfoldername3' of 'foldername2' I approached the problem as follow, but since I have an incredible number of folders, subfolders, and files it takes forever to come to a conclusion.... is there a fastest way to do the same? all_folders = [x[0] for x in walk(root)] sub_folder = [s for s in all_folders if 'foldername2' in s] matching_sub_path = [s for s in sub_folder if 'subfoldername3' in s] matching_sub_path = //root//foldername2//subfoldername3
linked to: http://stackoverflow.com/q/3207219
has comment: http://stackoverflow.com/comment/85257433
has comment: http://stackoverflow.com/comment/85258747
has comment: http://stackoverflow.com/comment/85258380

http://stackoverflow.com/a/49180990
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49177473
type: Answer
answers question: http://stackoverflow.com/q/49177473
has body: As the error suggests you need to set the DJANGO_SETTINGS_MODULE environment variable. It's value should be something like mysite.settings (check what it is in manage.py). You can set it in the Dockerfile ENV DJANGO_SETTINGS_MODULE mysite.settings Or in the environment when you docker exec -it -e "DJANGO_SETTINGS_MODULE=mysite.settings" $DOCKER_ID python /tmp/e2esetup.py Or in the script itself. import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') django.setup()
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/a/49179554
type: Answer
has comment: http://stackoverflow.com/comment/85366066
has comment: http://stackoverflow.com/comment/85366567
accepted answer of: http://stackoverflow.com/q/49178853
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85366088
has body: You could use your own function to determine the largest item in each column and then create a suitable table: def write_table(data): col_spacer = " | " # added between columns widths = [0] * len(data[0]) for row in data: widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)] return '\n'.join(col_spacer.join("{:&lt;{width}}".format(col, width=widths[index]) for index, col in enumerate(row)) for row in data) techs = ["name1", "name2", "name3", "name4", "name5", "name6", "name7", "name8", "name9"]; table = 'Tech', 'Total', 'Average' for tech in techs: current_tech = get_ticket_count(FHD_start,BHN_end,tech) tech_total = str(current_tech[0]) tech_average = current_tech[1] table.append([tech, tech_total, tech_average]) print write_table(table) Giving you: Tech | Total | Average name1 | 69 | 17 name2 | 30 | 7 name3 | 0 | 0 As you are using spaces to pad out each row, you would need to ensure that the font being used to display the email is fixed width, otherwise it would still look wrong due to the proportional spacing.
answers question: http://stackoverflow.com/q/49178853

http://stackoverflow.com/comment/85284749
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49139665
has text: As you can see in my post, I did reset the index ... the output table did not give me the result I was hoping for post index reset
score: 0

http://stackoverflow.com/a/49235826
upvote count: 0
type: AcceptedAnswer
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49235379
answers question: http://stackoverflow.com/q/49235379
type: Answer
score: -1
has body: lis = lis.remove(num) will set your list to 'None' because the remove method does not return anything. So just using lis.remove(num) might solve your problem - whatever your problem is. Your post doesn't really contain a clear question.

http://stackoverflow.com/a/49263140
score: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/49262888
upvote count: 2
has body: From the docs: Note hash() truncates the value returned from an object’s custom hash() method to the size of a Py_ssize_t. This is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds. 93792909800245310080479536979750034401273674738852415427366199722413460820022 is way above those limits. Try this: class C(): def __hash__(self): return 93792909800245310080479536979750034401273674738852415427366199722413460820022 a = C() b = C() print(hash(a)) print(hash(b)) Output: 377513311013302392 377513311013302392
answers question: http://stackoverflow.com/q/49262888
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/49279319
tagged with: matlab
type: Question
has answer: http://stackoverflow.com/a/49298650
score: 0
has body: This question relates to the situation where only MATLAB runtime is present - the computer does not have a full MATLAB license. A MATLAB function has been compiled for use by Python as described here: These instructions have been used successfully to call a user defined MATLAB function from Python and get a return value where parameters are int or float. However, if I call a user defined MATLAB function f(matrixParam) which has a parameter of MATLAB type matrix then no matter what data type I use in Python for it, I get wrong type errors. I tried the following Python types: list of lists ([[1,2],[3,4]]), Pandas.DataFrame and NumPy.matrix - nothing works. In MATLAB a variable a of type matrix may be defined like this: a = [1 2 3; 4 5 6; 7 8 10]. Would anyone know how I would define in Python a variable that would be acceptable by a MATLAB function as being of type matrix?
tagged with: python
has title: calling MATLAB function from Python, what is Python's equivalent of MATLAB 'matrix' datatype?
accepted answer: http://stackoverflow.com/a/49298650
has comment: http://stackoverflow.com/comment/85567150
has comment: http://stackoverflow.com/comment/85571104
type: AnsweredQuestion
answer count: 1

http://stackoverflow.com/a/49266990
has comment: http://stackoverflow.com/comment/85706342
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/95430724
type: Answer
answers question: http://stackoverflow.com/q/49264652
has body: In the standard environment you need to install all your dependencies inside your application. See Using third-party libraries. Whatever you have installed in the local environment (virtual or not) doesn't matter, GAE doesn't know how to use those and your app might not work properly locally and definitely won't work when deployed on GAE. You traceback indicates that you're loading the datastore library from your virtual env, not from your app, which is most likely why it doesn't work: .../env/local/lib/python2.7/site-packages/google/cloud/datastore/__init__.py You need to fix your app dependency installation. This discussion might be of interest as well: No module named warnings when starting GAE inside virtualenv locally
accepted answer of: http://stackoverflow.com/q/49264652

http://stackoverflow.com/q/49179549
score: 1
tagged with: spyder
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85365184
has title: Label Encoder is not creating dummy variables
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
has body: import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset=pd.read_csv('Churn_Modelling.csv') X=dataset.iloc[:, 3:13] Y=dataset.iloc[:, 13] from sklearn.preprocessing import LabelEncoder label_en1=LabelEncoder() X.values[:, 1]=label_en1.fit_transform(X.values[:, 1]) label_en2=LabelEncoder() X.values[:, 2]=label_en2.fit_transform(X.values[:, 2]) I tried creating dummy variables but it is not happening. I am using X.values int the encoding section because the version of Spyder that I have does not support object arrays so let X and Y be dataframes. I added .values because it dataframes do not support slice terminology. Where might I have gone wrong ? I created a similar program before for creating dummy variables and it worked then. I don't understand why it is not happening for this one.
has answer: http://stackoverflow.com/a/49179773
tagged with: deep-learning

http://stackoverflow.com/comment/85548534
type: QuestionComment
comment on: http://stackoverflow.com/q/49272851
score: 0
has text: @jezrael, input for last row as in??
type: Comment

http://stackoverflow.com/comment/85482104
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49182302
has text: @Ben.T Solution Verified. Thank you!

http://stackoverflow.com/q/49156393
has comment: http://stackoverflow.com/comment/85317639
type: Question
accepted answer: http://stackoverflow.com/a/49156627
has comment: http://stackoverflow.com/comment/85317745
possible better answer: http://stackoverflow.com/a/49156445
has answer: http://stackoverflow.com/a/49156627
has comment: http://stackoverflow.com/comment/85318110
has answer: http://stackoverflow.com/a/49156445
tagged with: python
score: -2
has comment: http://stackoverflow.com/comment/85317622
has comment: http://stackoverflow.com/comment/85317429
type: AnsweredQuestion
answer count: 2
tagged with: pandas
has title: Is there a quick way to find all unique identifiers in dataframe?
upvote count: 0
downvote count: 2
has body: I have a dataframe with over 100 columns, I would like to check all pairs to see which are unique identifiers.
favorite count: 0

http://stackoverflow.com/a/49126625
has comment: http://stackoverflow.com/comment/91777864
type: Answer
accepted answer of: http://stackoverflow.com/q/49124736
has comment: http://stackoverflow.com/comment/85279333
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/49124736
has comment: http://stackoverflow.com/comment/91771935
type: AcceptedAnswer
downvote count: 0
has body: It seems you can add custom headers to your post request : https://github.com/paypal/PayPal-Python-SDK/blob/master/paypalrestsdk/api.py#L270 Given that you just have to add you csrf token to the headers : https://docs.djangoproject.com/en/2.0/ref/csrf/#setting-the-token-on-the-ajax-request And your server should give you access
has comment: http://stackoverflow.com/comment/85275284

http://stackoverflow.com/comment/85352077
comment on: http://stackoverflow.com/a/49159063
type: Comment
type: AnswerComment
has text: Thanks a lot! This is what I was looking for!
score: 0

http://stackoverflow.com/a/60875946
has body: What I would suggest is to increase your pagefile. I had the same problem and increasing my pagefile worked. You can do that if you open your Control Panel. Click "System," then "Advanced system settings," and then "Settings" in the "Performance" tab. By default, Windows give only 0.5GB for pagefile. I increased my pafefile to 16GB and my code worked like a charm. Hope this helps.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49157075

http://stackoverflow.com/comment/85411773
score: 0
comment on: http://stackoverflow.com/a/49203158
has text: I did not call clean() by myself. And Model.clean_fields() is called before Model.clean(), that's at least what the docs say: "This method calls Model.clean_fields(), Model.clean(), and Model.validate_unique() (if validate_unique is True), in that order ..."
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85455944
type: QuestionComment
has text: this div is inside a script, for that reason soup can't find it
type: Comment
comment on: http://stackoverflow.com/q/49225943
score: 0

http://stackoverflow.com/comment/85436103
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49215929
score: 0
has text: Can you explain what you're expecting the new block of code to accomplish? In particular, what is `k`?

http://stackoverflow.com/comment/85452181
type: Comment
type: QuestionComment
has text: Yes, i want to do that
comment on: http://stackoverflow.com/q/49222992
score: 0

http://stackoverflow.com/comment/85266118
score: 0
type: Comment
has text: A slight change: `for i in df.index.unique():`
type: QuestionComment
comment on: http://stackoverflow.com/q/49130834

testing
tags question: http://stackoverflow.com/q/49228666
tags question: http://stackoverflow.com/q/49177228
type: Tag
tags question: http://stackoverflow.com/q/49128015
tag name: testing
tags question: http://stackoverflow.com/q/49213392
tags question: http://stackoverflow.com/q/49254777
tags question: http://stackoverflow.com/q/49163975

http://stackoverflow.com/a/49233501
upvote count: 1
answers question: http://stackoverflow.com/q/49232492
score: 1
type: Answer
has body: The problem here is pretty unique. To get the new value from the textarea an onKeyup event was required, which populated an array. The content of this array is used for submission. I simply needed to add a random key event so the values which have been populated by selenium will be added to the arrays. I added this key event after a textarea element was populated: driver.execute_script('arguments[0].value = arguments[1]', textarea_elem, i[col_count].value) textarea_elem.send_keys(Keys.DOWN)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49232492
downvote count: 0
has comment: http://stackoverflow.com/comment/129074757

http://stackoverflow.com/q/49265766
linked to: http://stackoverflow.com/q/44273037
has body: I'm trying to create a flag variable (i.e. a new column with binary values, like 1 for True, 0 for False) - I've tried both np.where (as per this post) and df.where to no avail. With df.where using: df.where(((df['MOSL_Rating'] == 'Highly Effective') &amp; (df['MOTP_Rating'] == 'Developing')) | ((df['MOSL_Rating'] == 'Highly Effective') &amp; (df['MOTP_Rating'] == 'Ineffective')) | ((df['MOSL_Rating'] == 'Effective') &amp; (df['MOTP_Rating'] == 'Ineffective')) | ((df['MOSL_Rating'] == 'Ineffective') &amp; (df['MOTP_Rating'] == 'Highly Effective')) | ((df['MOSL_Rating'] == 'Ineffective') &amp; (df['MOTP_Rating'] == 'Effective')) | ((df['MOSL_Rating'] == 'Developing') &amp; (df['MOTP_Rating'] == 'Highly Effective')), df['disp_rating'], 1, axis=1) but this returns ValueError: For argument "inplace" expected type bool, received type int. If I change my code from df['disp_rating'], 1, axis=1 to df['disp_rating'], True, axis=1 it returns TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value I've also tried np.where but that returns ValueError: either both or neither of x and y should be given I've also read this question, which looks similar. However when I use the solution presented there it returns: KeyError: 'disp_rating' If I create the variable in advance (to avoid the Key Error) I just get another error about something else. I assumed it would be pretty simple to create a new variable based on some basic conditions, but I've been stuck on this for a while and am not really making any progress despite reading the documentation and lots of SO posts. edit: Just to be extra clear, I'm trying to create a new column (named 'disp_rating') based on whether or not the values in 2 other columns ('MOSL_Rating and 'MOTP_Rating') within the same df meet certain conditions. I only have 1 dataframe, so I'm not trying to compare 2 dataframes. In SQL I would use a CASE WHEN statement, in SAS I would use an IF/THEN/ELSE statement. My df generally looks l…
answer count: 2
has comment: http://stackoverflow.com/comment/101856582
tagged with: pandas
upvote count: 3
has answer: http://stackoverflow.com/a/49279447
downvote count: 0
linked to: http://stackoverflow.com/q/33266344
has comment: http://stackoverflow.com/comment/85535041
tagged with: python
has comment: http://stackoverflow.com/comment/85535176
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85535126
has comment: http://stackoverflow.com/comment/85560642
has title: Using np.where to create a new column in pandas df based on conditions
score: 3
has comment: http://stackoverflow.com/comment/85536371
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49266586

http://stackoverflow.com/comment/85454836
has text: When would you expect `vw_q != vw_q`? Also note that your code isn't consistent in use of whitespace, parentheses, etc.; I'd recommend following [PEP-8](http://www.python.org/dev/peps/pep-0008/) as a baseline.
comment on: http://stackoverflow.com/q/49225602
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/comment/85308145
score: 0
has text: Thanks! This helps so much yet again!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49149022

http://stackoverflow.com/comment/106441147
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/52664522
has text: @Aran-Fey ping on updating your answer :)

http://stackoverflow.com/comment/85619817
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49265682
has text: Okay so I'm trying to append the commands. the p command is in learntris.py and the g command is in wahtever.py but I'm not sure if they're appending. the only way for me to see output in the script is to run it in the shell with the testris.py file required for testing. then it just sends the failed output results to the other script. and when I try just a regular '>' it just deletes the file and doesn't replace it. What am I doing wrong?
type: Comment

http://stackoverflow.com/q/49169982
has comment: http://stackoverflow.com/comment/85345377
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85345939
tagged with: random
has comment: http://stackoverflow.com/comment/85345378
has body: I have three sets of data: item1 = 'carrot' property1 = 'vegetable' item2 = 'apple' property2 = 'fruit' item3 = 'steak' property3 = 'meat' And so on... Now I want to combine these to sets of data, that should be randomly chosen. combination1 = item1 + property1 combination2 = item2 + property2 combination3 = item3 + property3 So that I can use them randomly: random.choice(combination1, combination2, combination3) In the end the combination has to fit in here: Client(args.item, args.property) Problem is, that always the set of item1+property1, item2+property2, aso. has to be taken. I can only manage to pick random combinations of items and properties, but don't know how to combine sets of them. Can anyone help?
has answer: http://stackoverflow.com/a/49170411
possible better answer: http://stackoverflow.com/a/49170411
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49170251
accepted answer: http://stackoverflow.com/a/49170251
has title: Random Choose set of data
has comment: http://stackoverflow.com/comment/85345201

http://stackoverflow.com/comment/85494767
type: Comment
comment on: http://stackoverflow.com/a/49244957
score: 0
type: AnswerComment
has text: I'm not sure I understand. When the page first loads, it is not a POST, so where is that value supposed to be coming from?

http://stackoverflow.com/q/49250968
has comment: http://stackoverflow.com/comment/92168944
has answer: http://stackoverflow.com/a/49782469
has answer: http://stackoverflow.com/a/49251270
upvote count: 7
score: 7
tagged with: python
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
downvote count: 0
has title: Error with pip install git (after switching to python 3.6)
type: UnansweredQuestion
has body: I just changed my project's interpreter to python 3.6 and have to install git library again. When i run the command "pip install --proxy=some_proxy git" i get the following error message: "Could not find a version that satisfies the requirement git (from versions: ) No matching distribution found for git". Why does it happen ?

http://stackoverflow.com/comment/85510154
type: AnswerComment
has text: @Mikeh12 When you will be done, and if the answer has helped you : I invite you to close it by accepting the answer.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49253102

http://stackoverflow.com/q/49258553
favorite count: 0
type: Question
tagged with: numpy
tagged with: http://stackoverflow.com/tag/zip
downvote count: 0
answer count: 1
tagged with: python
upvote count: 7
has body: The function numpy.savez() allows to store numpy objects in a file. Storing the same same object in two files results in two different files: import numpy as np some_array = np.arange(42) np.savez('/tmp/file1', some_array=some_array) np.savez('/tmp/file2', some_array=some_array) The two files differ: $ diff /tmp/file1.npz /tmp/file2.npz Binary files /tmp/file1.npz and /tmp/file2.npz differ Why aren't the files identical? Is there some random behavior, filename or time stamp included? Can this be workaround or fixed? (Is it a bug?) Note that this is not the case for np.save(). Files produced by np.save() are identical for identical inputs. So I guess it is related to zipping of the data. AFAICS there are only two bits different: $ xxd /tmp/file1.npz &gt; /tmp/file1.hex $ xxd /tmp/file2.npz &gt; /tmp/file2.hex $ diff -u0 /tmp/file1.hex /tmp/file2.hex --- /tmp/file1.hex 2018-03-13 13:39:12.235897095 +0100 +++ /tmp/file2.hex 2018-03-13 13:39:08.743927081 +0100 @@ -1 +1 @@ -0000000: 504b 0304 1400 0000 0000 ce6c 6d4c 9c9d PK.........lmL.. +0000000: 504b 0304 1400 0000 0000 cf6c 6d4c 9c9d PK.........lmL.. @@ -30 +30 @@ -00001d0: 1403 1400 0000 0000 ce6c 6d4c 9c9d 6ad9 .........lmL..j. +00001d0: 1403 1400 0000 0000 cf6c 6d4c 9c9d 6ad9 .........lmL..j. I can't find any good hint in the implementation of the function, but I haven't checked the zipping code yet (also Python 3.6 might make a difference). Note: Tested with Python 2.7 and numpy 1.9.2.
type: AnsweredQuestion
score: 7
accepted answer: http://stackoverflow.com/a/49259403
has answer: http://stackoverflow.com/a/49259403
has title: Why does numpy.savez() output non reproducible files?

http://stackoverflow.com/q/49163975
has body: I have downloaded videos and ground truth data from here and I am trying to use it to test out the results of my background subtraction algorithm. I can't for the life of me how they have labelled the ground truth data so which image lines up with which frame of the image/timestamp. As for how to use I am unsure, but I was thinking of perhaps subtracting the frame from the image somehow. perhaps cv.subtract( in openCV. Then for true positives and negatives and false positives and negatives? Am I on the right track?
downvote count: 0
tagged with: image-processing
upvote count: 1
favorite count: 0
type: Question
has title: How to use ground truth images for background subtraction
tagged with: opencv
tagged with: testing
type: UnansweredQuestion
tagged with: python
tagged with: video-processing
answer count: 0
score: 1

http://stackoverflow.com/comment/85315293
has text: `tag:stardog:api:context:default` indeed does the trick. I am not bound to `rdflib` and am more than happy to use the `sparqlwrapper`. Would it be much work for you to adapt the above's code to make use of it or could you point me to a code sample where also the credentials are set?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49155203
type: AnswerComment

http://stackoverflow.com/q/49159238
tagged with: ordereddictionary
has answer: http://stackoverflow.com/a/49159335
upvote count: 14
has body: According to PEP 468: Starting in version 3.6 Python will preserve the order of keyword arguments as passed to a function. To accomplish this the collected kwargs will now be an ordered mapping. Note that this does not necessarily mean OrderedDict. In that case, why does this ordered mapping fail to respect equality comparison with Python's canonical ordered mapping type, the collections.OrderedDict: &gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; data = OrderedDict(zip('xy', 'xy')) &gt;&gt;&gt; def foo(**kwargs): ... return kwargs == data ... &gt;&gt;&gt; foo(x='x', y='y') # expected result: True True &gt;&gt;&gt; foo(y='y', x='x') # expected result: False True Although iteration order is now preserved, kwargs seems to be behaving just like a normal dict for the comparisons. Python has a C implemented ordered dict since 3.5, so it could conceivably have been used directly (or, if performance was still a concern, a faster implementation using a thin subclass of the 3.6 compact dict). Why doesn't the ordered mapping received by a function respect ordering in equality comparisons?
has comment: http://stackoverflow.com/comment/85323770
answer count: 4
type: Question
has title: Why does the **kwargs mapping compare equal with a differently ordered OrderedDict?
score: 12
has comment: http://stackoverflow.com/comment/85323733
tagged with: function
has answer: http://stackoverflow.com/a/49159521
downvote count: 2
has comment: http://stackoverflow.com/comment/85323652
accepted answer: http://stackoverflow.com/a/49161835
tagged with: keyword-argument
tagged with: python
tagged with: python-3.6
possible better answer: http://stackoverflow.com/a/49159268
has answer: http://stackoverflow.com/a/49161835
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49159268

http://stackoverflow.com/q/49176095
has body: import serial.tools.list_ports ports = serial.tools.list_ports.comports() print(ports) #[&lt;serial.tools.list_ports_common.ListPortInfo object at 0x000001D48771C9B0&gt;, &lt;serial.tools.list_ports_common.ListPortInfo object at 0x000001D48866FB00&gt;] As you can see the comports are not readable, I can make it readable through for loops but I need it in list with readable word, eg. ["COM1","COM2","COM3"] Anyone has any idea to change it? I tried create a new list and append in the loop also no luck. When I print out the result is the same. UPDATES: I think what I did last time was appending each object together again. I am able to get the specific information I want which is COM with the code below: import serial.tools.list_ports ports = serial.tools.list_ports.comports() available_ports = [] for p in ports: available_ports.append(p.device) print(available_ports)
possible better answer: http://stackoverflow.com/a/52317693
tagged with: python
accepted answer: http://stackoverflow.com/a/49176245
answer count: 4
has answer: http://stackoverflow.com/a/52317693
favorite count: 0
has answer: http://stackoverflow.com/a/62287341
score: 5
tagged with: pyserial
tagged with: python-3.5
downvote count: 0
has title: Pyserial in Python(List out available comports without for loop)
type: Question
has answer: http://stackoverflow.com/a/49176245
type: AnsweredQuestion
tagged with: port
upvote count: 5
has answer: http://stackoverflow.com/a/49176398

http://stackoverflow.com/q/49223697
type: AnsweredQuestion
upvote count: 1
tagged with: matrix
score: 1
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49223837
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85451145
tagged with: python
has comment: http://stackoverflow.com/comment/85451234
has answer: http://stackoverflow.com/a/49223837
has title: How to make a lower triangular matrix with steps of two positions
tagged with: triangular
has body: I have a matrix that looks like: x=[[a,b,c,d,e,f], [g,h,i,j,k,l], [m,n,o,p,q,r]] with a,b,c numbers. I am however only interested in the numbers at the lower left half and would like to creat a lower triangular matrix that goes by steps of two positions and thus looks like this: x2=[[a,b,0,0,0,0], [g,h,i,j,0,0], [m,n,o,p,q,r]] I could of course multiply x with: x3=[[1,1,0,0,0,0], [1,1,1,1,0,0], [1,1,1,1,1,1]] But is there a way to do this without manually creating x3? And would it be possible to create a script where the steps are bigger then 2 zeros at a time?

http://stackoverflow.com/comment/85452038
score: 2
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49224224
has text: don't do those horrible statements. Use a dictionary to convert the months to values, and your problem will probably go away (and the code will be much much faster)

http://stackoverflow.com/q/49234367
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49235253
downvote count: 0
upvote count: 1
has body: I try to follow this tutorial to install basemap. I downloaded the basemap zip data and unpacked it and then tried to install geos-3.3.3. I created the environment variable and run the configure file, but I get this output: checking build system type... x86_64-unknown-linux-gnu checking host system type... x86_64-unknown-linux-gnu checking target system type... x86_64-unknown-linux-gnu checking for a BSD-compatible install... /usr/bin/install -c checking whether build environment is sane... yes checking for a thread-safe mkdir -p... /bin/mkdir -p checking for gawk... gawk checking whether make sets $(MAKE)... yes checking whether to enable maintainer-specific portions of Makefiles... no checking for gcc... gcc checking whether the C compiler works... yes checking for C compiler default output file name... a.out checking for suffix of executables... checking whether we are cross compiling... no checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ISO C89... none needed checking for style of include used by make... GNU checking dependency style of gcc... gcc3 checking how to print strings... printf checking for a sed that does not truncate output... /bin/sed checking for grep that handles long lines and -e... /bin/grep checking for egrep... /bin/grep -E checking for fgrep... /bin/grep -F checking for ld used by gcc... /usr/bin/ld checking if the linker (/usr/bin/ld) is GNU ld... yes checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm -B checking the name lister (/usr/bin/nm -B) interface... BSD nm checking whether ln -s works... yes checking the maximum length of command line arguments... 1572864 checking whether the shell understands some XSI constructs... yes checking whether the shell understands "+="... yes checking how to convert x86_64-unknown-linux-gnu file names to x86_64-unknown-linux-gnu format... func_convert_file_noop checking…
score: 1
answer count: 1
tagged with: python
has title: trying to install geos for basemap python // Python bindings: false
favorite count: 0
type: Question
tagged with: geos

http://stackoverflow.com/comment/85357404
score: 0
type: Comment
type: AnswerComment
has text: It's hard to say if most of them are written in OOP, but it is certainly a very common programming paradigm, and it is usually preferred nowdays for bigger projects, unless there is a reason to write procedurally.
comment on: http://stackoverflow.com/a/49155659

http://stackoverflow.com/comment/85426698
score: 0
has text: python 2 or 3? .
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49211172

http://stackoverflow.com/comment/85364005
has text: youre trying to call a method on the python file, I think you intended to call it on an object, which you don't have because there is no class in the subreddit_score.py file. Try just using d = main() instead and have your function return the dictionary. also maybe rename the main() function to something more descriptive like get_subreddit_data_dictionary() or whatever
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49179052

http://stackoverflow.com/comment/85276753
type: AnswerComment
has text: @Philip556677 - I updated my answer to include the queryable solutions.
type: Comment
comment on: http://stackoverflow.com/a/49135203
score: 0

http://stackoverflow.com/comment/85436763
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49216348
has text: I tried : def popupmsg(msg): popup = Toplevel() popup.wm_title("!") label = ttk.Label(popup, text=msg) label.pack(side="top", fill="x", pady=10) B1 = ttk.Button(popup, text="Okay", command = popup.destroy) B1.pack() same result.

http://stackoverflow.com/q/49160512
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: indexing
has body: I created a list h with the contents of the new file, however, when I try to run the code I get: IndexError: list index out of range This is what I have, is my code not creating a list? def lab6 (fname): """writes in new file with text from existing file""" f = open('lab6.txt','a+') s = open(fname, 'r', encoding = "ISO-8859-1") sc = s.readlines() #creates a list with items in s f.write(sc[0]) #copy first line #skip next 18 lines f.write(str(sc[19:28])) #copy next 9 lines to lab6 h = f.readlines() #puts contents of lab6 into list print(h) #prints that list t = h [2] #retrieve 3rd item in list print(t.range(0,3)) #print 1st 3 letters of 3rd item in list
tagged with: python
has answer: http://stackoverflow.com/a/49160569
has comment: http://stackoverflow.com/comment/85328110
type: AnsweredQuestion
has title: Index out of range, file readlines
tagged with: list
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49160569
tagged with: file
tagged with: fwrite

http://stackoverflow.com/comment/108327050
comment on: http://stackoverflow.com/a/49170179
has text: Nice work -- what is the zip file was a URL? Apparently read_excel method can't accept a URL that is also a zip (with an embedded .xlsx in it)
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85333641
comment on: http://stackoverflow.com/a/49163933
score: 0
type: Comment
has text: Note: If you'll end up running out one of the `tee`d generators to exhaustion before even beginning to iterate the other, you're better off constructing a `list`/`tuple` from the original generator and iterating it an arbitrary number of times. `tee` would have to store the same data as the `list`/`tuple`, but imposes additional overhead; the overhead is only worth it if you're advancing the `tee`-ed generators in parallel (or close to it) where the cache stays small. In this case, just doing `z = tuple(zip(t1, t2))`, then `print(list(z))`, `print(dict(z))` makes more sense.
type: AnswerComment

http://stackoverflow.com/q/49242521
score: 0
type: UnansweredQuestion
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/49282246
has body: Running into something guys and was hoping to get some ideas/help. I have a database with the tree structure where leaf can participate in the several parents as a foreign key. The typical example is a city, which belongs to the country and to the continent. Needless to say that countries and continents should not be repeatable, hence before adding another city I need to find an object in the DB. If it doesn't exist I have to create it, but if for instance country doesn't exist yet, then I have to check for the continent and if this one doesn't exist then I have to have creation process for it. So far I got around with the creation of a whole bunch of items if I run it from the single file, but if I push the SQL alchemy code into module the story becomes different. For some reason meta scope becomes limited and if the table doesn't exist yet, then the code start throwing ProgrammingError exceptions if I query for the foreign key presence (from the city for the country). I have intercepted it and in the __init__ class constructor of the class I am looking for (country) I am checking if the table exists and creating it if doesn't. Two things I have a problem with and need an advice on: 1) Verification of the table is inefficient - I am working with the Base.metadata.sorted_tables array through which I have to look through and figure out if the table structure is the one that matches my class __tablename__. Such as: for table in Base.metadata.sorted_tables: # Find a right table in the list of tables if table.name == self.__tablename__: if __DEBUG__: print 'DEBUG: Found table {} that equal to the class table {}'.format(table.name, self.__tablename__) if not table.exists(): session.get_bind().execute(table.create()) Needless to say, this takes time I am looking for more efficient way to do the same. 2) The second issue is with the inheritance of the declarative base (declarative_base()) with respect to the OOP in Python. I want to take some of the code repetitions away a…
tagged with: python
tagged with: sqlalchemy
has title: SQL Alchemy ORM tables on-demand

http://stackoverflow.com/comment/85324370
type: Comment
score: 0
type: QuestionComment
has text: Vaguely thinking maybe [fping](https://fping.org/) though it's for a different use case than yours really I guess.
comment on: http://stackoverflow.com/q/49159493

http://stackoverflow.com/a/49192610
has comment: http://stackoverflow.com/comment/85391099
has comment: http://stackoverflow.com/comment/85390587
has comment: http://stackoverflow.com/comment/85391206
has body: If you want to iterate Multiple lists you can use "zip". For example for a,b in zip(listA,ListB): c = square(a) + b listC.append(c);
type: Answer
has comment: http://stackoverflow.com/comment/85391303
has comment: http://stackoverflow.com/comment/85391490
answers question: http://stackoverflow.com/q/49192542
score: 0

http://stackoverflow.com/q/49162657
type: Question
type: UnansweredQuestion
answer count: 1
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/85332899
tagged with: opencv
score: 0
has body: I am encountering a weird problem with cv2.fitEllipse. When I try to get this ellipse of this form, that can be defined (sorry for the long list of definition) as: import numpy as np test=np.zeros((400,1000)) test[241, 113]=1 test[241, 114]=1 test[242, 112]=1 test[242, 113]=1 test[242, 114]=1 test[242, 115]=1 test[242, 116]=1 test[242, 118]=1 test[242, 119]=1 test[242, 120]=1 test[242, 121]=1 test[243, 111]=1 test[243, 112]=1 test[243, 113]=1 test[243, 114]=1 test[243, 115]=1 test[243, 116]=1 test[243, 117]=1 test[243, 118]=1 test[243, 119]=1 test[243, 120]=1 test[243, 121]=1 test[244, 110]=1 test[244, 111]=1 test[244, 112]=1 test[244, 113]=1 test[244, 114]=1 test[244, 115]=1 test[244, 116]=1 test[244, 117]=1 test[244, 118]=1 test[244, 119]=1 test[244, 120]=1 test[245, 109]=1 test[245, 110]=1 test[245, 111]=1 test[245, 112]=1 test[245, 113]=1 test[245, 114]=1 test[245, 115]=1 test[245, 116]=1 test[245, 117]=1 test[245, 118]=1 test[245, 119]=1 test[245, 120]=1 test[246, 109]=1 test[246, 110]=1 test[246, 111]=1 test[246, 112]=1 test[246, 113]=1 test[246, 114]=1 test[246, 115]=1 test[246, 116]=1 test[246, 117]=1 test[246, 118]=1 test[246, 119]=1 test[247, 109]=1 test[247, 110]=1 test[247, 111]=1 test[247, 112]=1 test[247, 113]=1 test[247, 114]=1 test[247, 115]=1 test[247, 116]=1 test[247, 117]=1 test[247, 118]=1 test[247, 119]=1 test[248, 108]=1 test[248, 109]=1 test[248, 110]=1 test[248, 111]=1 test[248, 112]=1 test[248, 113]=1 test[248, 114]=1 test[248, 115]=1 test[248, 116]=1 test[248, 117]=1 test[248, 118]=1 test[248, 119]=1 test[249, 109]=1 test[249, 110]=1 test[249, 111]=1 test[249, 112]=1 test[249, 113]=1 test[249, 114]=1 test[249, 115]=1 test[249, 116]=1 test[249, 117]=1 test[249, 118]=1 test[249, 119]=1 test[250, 109]=1 test[250, 110]=1 test[250, 111]=1 test[250, 112]=1 test[250, 113]=1 test[250, 114]=1 test[250, 115]=1 test[250, 116]=1 test[250, 117]=1 test[250, 118]=1 test[250, 119]=1 test[250, 120]=1 test[251, 109]=1 test[251, 110]=1 test[251, 111]=1 test[2…
tagged with: python
tagged with: ellipse
has title: Why does cv2.fitEllipse considers contours as side of ellipse?
has answer: http://stackoverflow.com/a/49179543

http://stackoverflow.com/comment/85441505
has text: Seeing as I want module a to do the importing for module b, this isn't working.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49218761

http://stackoverflow.com/a/49234347
has body: You can not pass "#" in to querystring value. You have to replace # with its UTF-8 value (%23). See the example below http://127.0.0.1:5000/input?text=some text%23blah blah blah It works for me.
type: Answer
has comment: http://stackoverflow.com/comment/85473281
accepted answer of: http://stackoverflow.com/q/49233689
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/49233689
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/85458628
has text: When debugging, the first thing you need to do is verify your assumptions. You were assuming that `read_from_db` was being executed when it was not. You can verify your assumptions simply by putting print statements inside of functions to verify they run, and use print statements to very that your variables contain the values you think they do. Once the program is working, you can remove the print statements.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49227336
type: Comment

http://stackoverflow.com/comment/85474258
has text: In effect, you are right. https://unicode.org/charts/normalization/chart_Number-Other.html (index in http://unicode.org/charts/normalization/). Now I'm looking where `<compact>` is added. I overlooked it on explaination.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49233978
type: AnswerComment

http://stackoverflow.com/comment/85438108
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49215772
type: Comment
has text: thanks for pointing out the formatting. I took that directly from Miguel Grinberg's Flask tutorial, which is very good. His formatting mirrors the SQLAlchemy documentation, and that is consistent with the error I get with `df = pd.DataFrame(LPRRank.query.all(), columns=['candid', 'rank', 'user_id'])`:

http://stackoverflow.com/comment/85275399
comment on: http://stackoverflow.com/q/49135308
type: QuestionComment
score: 0
has text: Since you tagged pandas, I've closed as a duplicate.
type: Comment

http://stackoverflow.com/q/49263029
upvote count: 1
has comment: http://stackoverflow.com/comment/85531577
has comment: http://stackoverflow.com/comment/85531247
favorite count: 0
type: AnsweredQuestion
has body: I'm getting an auth error with my google api test, the code to set the environmental variable works alone, however when used in conjunction with the google test code the auth fails. I was also able to get the test code to work by running an EXPORT command in shell. For convenience, I'd like to be able to set the auth in my scripts. #This program will test the google speech api #while setting the environmental variable for the #authentication .json file and then authenticating import os # Imports the Google Cloud client library from google.cloud import language from google.cloud.language import enums from google.cloud.language import types # My code sets the authentication env variable os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = str('home/kyle/Security/test.json') # Instantiates a client client = language.LanguageServiceClient() # The text to analyze text = u'Hello, world!' document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) # Detects the sentiment of the text sentiment = client.analyze_sentiment(document=document).document_sentiment print('Text: {}'.format(text)) print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude)) The error: File "/home/kyle/python projects/googleSpeech/test/venv/lib/python3.5/site-packages/google/auth/_default.py", line 142, in _get_explicit_environ_credentials os.environ[environment_vars.CREDENTIALS]) File "/home/kyle/python projects/googleSpeech/test/venv/lib/python3.5/site-packages/google/auth/_default.py", line 67, in _load_credentials_from_file 'File {} was not found.'.format(filename)) google.auth.exceptions.DefaultCredentialsError: File home/kyle/Security/test.json was not found. EDIT now exporting the json file doesnt work I ran this code to test reading the .json file fd = open(‘/home/kyle/Security/test.json’) dat = fd.read() fd.close() Result: SyntaxError: Non-ASCII character '\xe2' in file testRead.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
score: 1
tagged with: google-speech-api
tagged with: python
has comment: http://stackoverflow.com/comment/85529861
possible better answer: http://stackoverflow.com/a/49264983
accepted answer: http://stackoverflow.com/a/49267475
has title: Setting Environmental variable issue
has answer: http://stackoverflow.com/a/49264983
has answer: http://stackoverflow.com/a/49267475
type: Question
answer count: 2
downvote count: 0
tagged with: authentication

http://stackoverflow.com/comment/85539936
has text: @PeterDolan Cool, How would it be implemented into 'my' code then?
comment on: http://stackoverflow.com/q/49268117
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85443921
type: QuestionComment
comment on: http://stackoverflow.com/q/49220111
has text: I mean that I want to save all images' pixels and labels into two different dataset files and call them on python to use for training and testing purposes.
score: 0
type: Comment

http://stackoverflow.com/comment/85375335
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49184256
has text: Thanks for chiming in. I tried what you suggested and it did not alleviate the issue. Basically if I have any value assigned for DEFAULT_FILE_STORAGE I get this error. For example: DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' or DEFAULT_FILE_STORAGE = ' ' To be honest, I'm totally stuck on troubleshooting this. What other information could I provide to be helpful?
type: AnswerComment

http://stackoverflow.com/comment/85476647
comment on: http://stackoverflow.com/q/49236655
type: Comment
type: QuestionComment
has text: Sure, but I was correcting the lack of parenthesis following `super`.
score: 1

http://stackoverflow.com/q/49214474
accepted answer: http://stackoverflow.com/a/49214655
type: Question
has title: Overlapping bars in pandas plot are not perfectly centered over each other when they have different width
tagged with: pandas
upvote count: 3
answer count: 1
downvote count: 0
has body: I am wondering if there is a way to center bars that overlap in a bar plot when using the plotting provided by pandas. When using twiny, we get bars corresponding to the different plots to overlap, which is really practical. When they have the same width they will be centered perfectly over each other. However when one changes the width of one of the sets, they won't center anymore, which makes the plot look messy as can be seen here: The first black bar of cat 1 and cat 2 is perfectly centered on the corresponding blue bars. However the next black bar is not centered on the orange bar, same with the third black bar which is not centered over the green bar. As can be seen here they are perfectly centered when they have the same width. So how can they be centered in the same way when they don't have the same width?: This is the code that creates the current uncentered plot: from io import StringIO import pandas as pd import matplotlib.pyplot as plt txt = '''Category COLUMN1 COLUMN2 COLUMN3 A 0.5 3 Cat1 B 0.3 5 Cat1 C 0.7 4 Cat1 A 0.4 3 Cat2 B 0.8 5 Cat2 C 0.3 4 Cat2 ''' df = pd.read_table(StringIO(txt), sep="\s+") order = ['Cat1', 'Cat2'] fig, ax = plt.subplots() ax2 = ax.twiny() col1 = pd.pivot_table(df,index='COLUMN3',columns='Category',values='COLUMN1').reindex(order) col1.plot(kind='bar', ax=ax, edgecolor='Black', lw=1, color='black') col2 = pd.pivot_table(df,index='COLUMN3',columns='Category',values='COLUMN2').reindex(order) col2.plot(kind='bar', ax=ax2, legend=False, alpha=0.7) ax2.xaxis.set_visible(False) plt.show() EDIT Here is a picture of what is desired, please excuse the "bad graphic editing".:
favorite count: 0
type: AnsweredQuestion
score: 3
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/49214655

http://stackoverflow.com/a/49180246
accepted answer of: http://stackoverflow.com/q/49180006
score: 1
type: Answer
has body: The code you posted works, if there is an image called bg.jpg within the same directory where you are running the code. Anyway, you could try to reference the full path to the image: import os img_path = os.path.join(os.getcwd(), 'bg.jpg') img = cv2.imread(img_path,cv2.IMREAD_GRAYSCALE)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49180006
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49180779
favorite count: 0
type: Question
tagged with: tuples
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/49182450
tagged with: arrays
has answer: http://stackoverflow.com/a/49182450
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has title: compress large ranges into shorter ranges in python while maintaining the labels
answer count: 1
downvote count: 0
upvote count: 1
score: 1
has body: My code reads a sequence of predictions and converts them into tuples (e.g. [start,end,label]) based on majority %age(>x) as follows: Sample_predictions = [0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,1,1,1,1,0,0,0,0] Actual prediction values are here. The top few rows of current output looks like : (0.0, 1.3931972789115648, 'not-music') (1.3931972789115648, 2.7863945578231295, 'not-music') (2.7863945578231295, 4.179591836734694, 'not-music') (4.179591836734694, 5.572789115646259, 'not-music') (5.572789115646259, 6.965986394557823, 'not-music') (6.965986394557823, 8.359183673469389, 'not-music') (8.359183673469389, 9.752380952380953, 'not-music') (9.752380952380953, 11.145578231292518, 'not-music') (11.145578231292518, 12.538775510204083, 'not-music') (12.538775510204083, 13.931972789115646, 'not-music') (13.931972789115646, 15.32517006802721, 'not-music') (15.32517006802721, 16.718367346938777, 'not-music') (16.718367346938777, 18.11156462585034, 'not-music') (18.11156462585034, 19.504761904761907, 'not-music') (19.504761904761907, 20.89795918367347, 'not-music') (20.89795918367347, 22.291156462585036, 'not-music') (22.291156462585036, 23.6843537414966, 'not-music') (23.6843537414966, 25.077551020408166, 'not-music') (25.077551020408166, 26.470748299319727, 'not-music') (26.470748299319727, 27.86394557823129, 'not-music') (27.86394557823129, 29.257142857142856, 'not-music') (29.257142857142856, 30.65034013605442, 'not-music') (30.65034013605442, 32.04353741496599, 'music') (32.04353741496599, 33.436734693877554, 'music') (33.436734693877554, 34.82993197278912, 'music') ISSUE: How do I consolidate this output so that it is as realistic as possible? For example, a human would have simply said , 0, 30.65, 'not-music' 30.65, 34.82, 'music Thank you.

http://stackoverflow.com/a/49209820
type: Answer
answers question: http://stackoverflow.com/q/49209773
score: 2
has comment: http://stackoverflow.com/comment/85424262
has body: Because in your loop . is also a character which can't be converted. Just corrected you syntax wise: s = "1.1,2,3,4,5,6,7,8,9" v = 0 r = 0 for i in s.split(','): if i != ",": v+= float(i) else: v = 0 r += v print(r) Sum for decimal numbers code s = "1.1,2,3,4,5,6,7,8,9" v = 0 for i in s.split(','): v+= float(i) print(v) Or s = "1.1,2,3,4,5,6,7,8,9" print(sum(map(float,s.split(','))))
has comment: http://stackoverflow.com/comment/85424285
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85424295

matplotlib-basemap
type: Tag
tag name: matplotlib-basemap
tags question: http://stackoverflow.com/q/49158130
tags question: http://stackoverflow.com/q/49152116
tags question: http://stackoverflow.com/q/49198240
tags question: http://stackoverflow.com/q/49134634

http://stackoverflow.com/q/49253272
has answer: http://stackoverflow.com/a/49254289
tagged with: kivy
score: 1
has title: Python/Kivy : Can i call function on double click on Label
favorite count: 0
tagged with: kivy-language
type: Question
downvote count: 0
upvote count: 1
tagged with: python
answer count: 1
has body: Can someone tell me how to call function def demo() on double click of Label Item1,Item2 ? test.py from kivy.app import App from kivy.lang import Builder from kivy.uix.screenmanager import Screen def convert_data(data): l = [] for item in data: for key, value in item.items(): l.append({'text': key, 'value': value}) return l class test(): def demo(self): print('Demo') class Invoice(Screen): def abc(self): arr = ({'Item1': ''},{'Item2': 1000}) self.rv.data = convert_data(arr) class MyApp(App): def build(self): return Builder.load_file('test.kv') if __name__ == '__main__': MyApp().run() test.kv <Button@Button>: font_size: 15 size_hint_y:None height: 30 <Label@Label>: font_size: 15 size_hint_y:None height: 30 <Item@GridLayout>: cols: 2 text: "" value: 0 padding : 5, 0 spacing: 10, 0 Label: size_hint_x: .35 text: root.text halign: 'left' valign: 'middle' canvas.before: Color: rgb: .6, .6, .6 Rectangle: pos: self.pos size: self.size Label: size_hint_x: .15 text: str(root.value) halign: 'right' valign: 'middle' canvas.before: Color: rgb: .6, .6, .6 Rectangle: pos: self.pos size: self.size Invoice: rv: rv BoxLayout: orientation: "vertical" padding : 15, 15 BoxLayout: orientation: "vertical" padding : 5, 5 size_hint: .6, None pos_hint: {'x': .18,} BoxLayout: orientation: "horizontal" padding : 5, 5 spacing: 10, 10 size: 800, 40 size_hint: 1, None Button: text: "Show" size_hint_x: .05 spacing_x: 30 on_press:root.abc() BoxLayout: orientation: "horizontal" size_hint: 1, 1 BoxLayout: orientation: "vertical" size_hint: .5, 1 padding : 0, 15 spacing: 10, 10 size: 500, 30 BoxLayout: RecycleView: id: rv viewclass: 'Item' RecycleBoxLayout: default_size: None, dp(30) default_size_hint: 1, None size_hint_y: None height: self.minimum_height orientation: 'vertical'
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/49254289
type: AnsweredQuestion

http://stackoverflow.com/q/49275996
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/49276998
tagged with: pandas
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49276840
has body: I'm working with a huge dataframe in python and sometimes I need to add an empty row or several rows in a definite position to dataframe. For this question I create a small dataframe df in order to show, what I want to achieve. &gt; df = pd.DataFrame(np.random.randint(10, size = (3,3)), columns = &gt; ['A','B','C']) &gt; A B C &gt; 0 4 5 2 &gt; 1 6 7 0 &gt; 2 8 1 9 Let's say I need to add an empty row, if I have a zero-value in the column 'C'. Here the empty row should be added after the second row. So at the end I want to have a new dataframe like: &gt;new_df &gt; A B C &gt; 0 4 5 2 &gt; 1 6 7 0 &gt; 2 nan nan nan &gt; 3 8 1 9 I tried with concat and append, but I didn't get what I want to. Could you help me please?
answer count: 4
has title: How to add an empty row after a definite row in python dataframe?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49277122
tagged with: for-loop
tagged with: concatenation
upvote count: 3
has answer: http://stackoverflow.com/a/49277122
possible better answer: http://stackoverflow.com/a/49277164
downvote count: 0
has answer: http://stackoverflow.com/a/49277164

http://stackoverflow.com/comment/85318491
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49156687
has text: If there is a better way to pull these, then yes it does have to do with attachments given that one possible solution would be to add an argument in the for loop that checks for attachment on each email I'm iterating through. The _core_ issue I'm trying to solve is using the for loop to pull attachments out of recent emails, and take the latest one. `if item.Subject == sub_today and item.SentOn > time.time.today()- 2 weeks and item.Attachments is not null` I'm tripped up on filtering SentOn date, and checking that there is an attachment
score: 0

http://stackoverflow.com/q/49140663
has comment: http://stackoverflow.com/comment/85287218
score: 0
answer count: 0
has body: Not sure if anyone plays with this API before, but would like to seek your help on understanding something. URL as below : https://www.eventfinda.co.nz/api/v2/end-points http://api.eventfinda.co.nz/v2/events.json?rows=10&amp;offset=10 There's a thing call offset in the API as per description below Specifies an offset into the search results. Combined with the rows parameter, this will let you return any subset of the full results. This will allow you to page through results. /events.xml?rows=10&amp;offset=0 /events.xml?rows=10&amp;offset=10 /events.xml?rows=10&amp;offset=20 Can anyone explain to me what's this about? I have been cracking it for days and yet I don't understand anything. EDIT , code as below : def download(offset): url = 'http://api.eventfinda.co.nz/v2/locations.json?rows=10&amp;offset=%d'%(offset) username = 'test'; password = 'test123'; request = urllib2.Request(url) base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') request.add_header("Authorization", "Basic %s" % base64string) result = urllib2.urlopen(request) data = json.load(result) with open("./data/locations.json", "a") as fd: fd.write(json.dumps(data) + "\n") fd.close() def loop_offset(): # total number is 23234 for offset in range(0, 23234, 10): print(offset) download(offset) loop_offset()
has comment: http://stackoverflow.com/comment/85287485
has comment: http://stackoverflow.com/comment/85287420
type: Question
has comment: http://stackoverflow.com/comment/85287539
has comment: http://stackoverflow.com/comment/85287254
has comment: http://stackoverflow.com/comment/85286665
tagged with: python
type: UnansweredQuestion
has title: Eventfinda API understanding

http://stackoverflow.com/q/49147325
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/49147420
answer count: 1
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49147420
favorite count: 0
type: Question
tagged with: python
has body: I am having two dataframe and I am trying to join them on a key and at certain row doesn't have matching row so I am using bfill method but its filling the values from the output I want to fill it the next value from the other dataframe. df1: rcd_date 2012-01-30 2012-02-29 2012-03-30 2012-04-30 df2: nav_date mfv_gross 2012-01-30 10.00 2012-01-31 10.00 2012-02-01 10.17 2012-02-06 10.50 2012-02-29 11.06 2012-03-31 10.68 2012-04-01 10.76 2012-04-28 10.87 2012-04-29 10.94 2012-04-30 10.97 my code : joined = cash_df.set_index('rcd_date').join(nav_data.set_index('nav_date')).fillna(method='bfill') output: rcd_date mfv_gross 2012-01-30 10.00 2012-02-29 11.06 2012-03-30 10.97 2012-04-30 10.97 desired output: rcd_date mfv_gross 2012-01-30 10.00 2012-02-29 11.06 2012-03-30 10.68 2012-04-30 10.97
type: AnsweredQuestion
has title: How to replace the values from next row if values doesn't match in dataframe join

http://stackoverflow.com/comment/88552196
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/50772298
has text: Python 2 does not add the module's directory to `sys.path`. What happens is that when the `p1.file1` module executes `from file2 import B`, Python 2 will first attempt to interpret that as `from p1.file2 import B`, and it will only look for a top-level `file2` module if it finds no `p1.file2`.
score: 0

http://stackoverflow.com/q/49151474
tagged with: python
tagged with: plot
favorite count: 0
has title: plotly url issue when plotting
downvote count: 0
score: 1
upvote count: 1
tagged with: plotly
has body: When running the following code to try and produce a parallel coordinate plot: import plotly.plotly as py import plotly.graph_objs as go import numpy as np import pandas as pd df = pd.read_csv('PublicHealthEngland-DataSPLIT.csv') data = [ go.Parcoords( line = dict(color = 'blue'), dimensions = list([ dict(range = [int(np.min(df['Male'][1:])),int(np.max(df['Male'][1:]))], label = str(df['Male'][0]), values = df['Male'][1:]), dict(range = [int(np.min(df['Male.1'][1:])),int(np.max(df['Male.1'][1:]))], label = str(df['Male.1'][0]), values = df['Male.1'][2:]) ]) ) ] py.iplot(data) I get the following error: PlotlyError: Because you didn't supply a 'file_id' in the call, we're assuming you're trying to snag a figure from a url. You supplied the url, '', we expected it to start with 'https://plot.ly'. Run help on this function for more information. The same occurs when trying to use the tutorial codeline: py.iplot(data, filename = 'PublicHealthEngland-DataSPLIT') Not sure how this is trying to pull data from a URL.. The data looks like this: Unnamed: 0 Male Male.1 Male.2 Male.3 \ 0 CCG Name 0-4 5-9 10-14 15-19 1 NHS Airedale, Wharfdale And Craven CCG 4278 5001 4833 4589 2 NHS Ashford CCG 3981 4281 4066 4289 3 NHS Aylesbury Vale CCG 6488 7054 6596 6280 4 NHS Barking And Dagenham CCG 9626 10117 8338 6852 5 NHS Barnet CCG 13274 14082 12297 10765 6 NHS Barnsley CCG 7518 8075 7181 6797 7 NHS Basildon And Brentwood CCG 8711 8916 8331 7919 8 NHS Bassetlaw CCG 3162 3334 3119 3191 9 NHS Bath And North East Somerset CCG 5043 5517 5466 7039 10 NHS Bedfordshire CCG 14839 15623 14077 13324 11 NHS Bexley CCG 7850 8231 7243 7123 12 NHS Birmingham Crosscity CCG 24428 26217 23811 23238 13 NHS Birmingham South And Central CCG 12050 12832 11755 11062 14 NHS Blackburn With Darwen CCG 5898 6364 6085 5773 15 NHS Blackpool CCG 4697 4690 4652 4503 16 NHS Bolton CCG 10088 10986 10056 9480 17 NHS Bracknell And Ascot CCG 4042 4629 4617 4394 18 NHS Bradford City CCG 5518 5935 5530 5198 Link to the pa…
type: Question
answer count: 0
has comment: http://stackoverflow.com/comment/85323148
type: UnansweredQuestion
tagged with: url

http://stackoverflow.com/comment/85523098
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49256838
type: Comment
has text: Added solution I needed, thanks for the input. Works great!

http://stackoverflow.com/a/49225167
has comment: http://stackoverflow.com/comment/85488721
has comment: http://stackoverflow.com/comment/85489710
has body: You're getting the page_source the moment the URL is fetched, which means you'll likely see only and exactly what the server sends to the browser—no more and no less. That initial source includes the following HTML snippet: Appearances 230 It isn't until a few moments later, after some JavaScript has downloaded and executed, that it changes to the following: Appearances 30 In order to get that data, then, you'll need to wait for it. That means you'll need to wait for some indication that the necessary JavaScript has executed. If you can find something that (1) consistently appears after the JavaScript has executed and (2) is a constant, predictable value, you can use Selenium's WebDriverWait() to wait for it. Then you'll know that it's safe to fetch the data you want. In your case, it looks like you want to wait until the "Filter by Season" dropdown has appeared and is populated and its target button is displaying the "2017/18" season: from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait wait = WebDriverWait(driver, 10) wait.until( EC.element_to_be_clickable( (By.XPATH, "//*[@role='button'][text()='2017/18']")))
has comment: http://stackoverflow.com/comment/85488934
type: Answer
has comment: http://stackoverflow.com/comment/85542393
accepted answer of: http://stackoverflow.com/q/49224279
has comment: http://stackoverflow.com/comment/85489362
score: 0
has comment: http://stackoverflow.com/comment/85488515
has comment: http://stackoverflow.com/comment/85489034
answers question: http://stackoverflow.com/q/49224279
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85488823
has comment: http://stackoverflow.com/comment/85488631

http://stackoverflow.com/q/49150327
favorite count: 0
has title: Lazy loading properties, @property decorator
type: Question
has comment: http://stackoverflow.com/comment/103022063
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49150473
has body: I want to implement lazy loaded properties in a class. I thought it is easy and implemented it like this: class Foo: def __init__(self): self._bar = None @property def bar(self): if not self._bar: self._bar = longTimeLoadedData() return self._bar But now I am surprised that after init the _bar variable contains the longTimeLoadedData even Foo.bar was never called... Could someone explain the behaviour to me? Thank you in advance!
has comment: http://stackoverflow.com/comment/85305023
upvote count: 2
score: 0
downvote count: 2
answer count: 1

http://stackoverflow.com/comment/85298928
comment on: http://stackoverflow.com/q/49147103
type: Comment
score: 0
type: QuestionComment
has text: Same as in the link above, except that you will be merging on 2 columns, not one. This is similar to your previous question, correct?

http://stackoverflow.com/comment/116389676
comment on: http://stackoverflow.com/a/55198799
type: Comment
has text: Libtesseract is an OCR engine written in C. I don't have any experience with this one, but for PyOCR I guess you could start with Python wrapper like this one https://github.com/virtuald/python-tesseract-sip.
type: AnswerComment
score: 1

http://stackoverflow.com/a/49204836
type: Answer
has body: Have you tried to make it return a list instead of an expression? Something like this: def profile(): posts_to_chose=[] for i in range(29): posts_to_chose.append((data[i] + str(i))) i+=1 return posts_to_chose return render_template("profile.html", posts_to_chose)
answers question: http://stackoverflow.com/q/49204634
score: 0

http://stackoverflow.com/comment/85265029
has text: @goodvibration yes, python ints have no limit besides your system memory.
comment on: http://stackoverflow.com/a/49130218
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/85510606
score: 0
type: AnswerComment
has text: How I can get `backref` name generated by automap?
comment on: http://stackoverflow.com/a/49250626
type: Comment

http://stackoverflow.com/q/49140849
has body: I'm working on a project with python-3.6.4 and django-2.0.2. For simplicity, I'm explaining the situation in short. Suppose, there are three apps:- "problems", "solve_activities" and "profiles" having three models(mentioned below) inside them. I have a "DetailView" page for each problem. I want to show if the logged in user has solved the problem or not. The django template tag that I wanted to do use was something like this: {% if user.is_authenticated and problem.solved.all.filter(solver={{user.username}}) %} Here are the above mentioned files: "problems/models.py": class Problem(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(allow_unicode=True, max_length=100, unique=True) def __str__(self): return self.name def get_absoulte_url(self): return reverse('problems') return reverse('problems:problem_detail', kwargs={'slug':self.slug}) I've used the urlpatterns in 'problems/urls.py' as "path('/', views.ProblemDetail.as_view(), name='problem_detail')". "profiles/models.py"(inherited from auth.models.User): class User(auth.models.User, auth.models.PermissionsMixin): def __str__(self): return self.username "solve_activities/models.py": class Solve(models.Model): problem = models.ForeignKey(Problem, on_delete=models.CASCADE, related_name="solved") solver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="solved") I'm only creating this object when the user solves a problem. Now, my ProblemDetail view on problems/views.py: class ProblemDetail(generic.DetailView): model = Problem template_name = 'problems/problem_detail.html' And the "problems/problem_detail.html" file where I'm facing the complexity basically: {{problem}} Solve Status: {% if user.is_authenticated and problem.solved.all.filter(solver={{user.username}}) %}Solved{% else %}Unsolved{% endif %} Again, {% if user.is_authenticated and problem.solved.all.filter(solver={{user.username}}) %} is what I want to do, but I couldn't find any useful resource on how to do it corr…
type: Question
accepted answer: http://stackoverflow.com/a/49141146
has title: Django Template syntax/tag to filter and check if a related data exists in that model
has comment: http://stackoverflow.com/comment/85287558
tagged with: django
tagged with: python
upvote count: 2
type: AnsweredQuestion
score: 2
tagged with: django-templates
has answer: http://stackoverflow.com/a/49141146
downvote count: 0
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/85381199
comment on: http://stackoverflow.com/a/49187887
has text: Thanks for the code. But it's not my question, whole points for each line aren't available at the beginning, for example at t=3 points for a line is [(1,0),(2,3), (3,6)] and in t=4 a new point comes [(1,0),(2,3), (3,6), (4, 9)]. I can plot one line in this situation. But I have no Idea for several lines.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49219822
downvote count: 0
tagged with: django
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49221179
has answer: http://stackoverflow.com/a/49219944
possible better answer: http://stackoverflow.com/a/49219944
tagged with: http://stackoverflow.com/tag/json
has title: Django: How do I return data from db along with the foreign key entities to the user as JSON?
tagged with: python
has body: I have two models as such, class Foo(models.Model): name = models.CharField(max_length=100, unique=True) city = models.CharField(max_length= 50) .... and class Bar(models.Model): Foo = models.ManyToManyField(Foo) name = models.CharField(max_length=20, unique=True) I have a view that returns Foo objects as JSON, def list_by_city(request, city): foo_list = Foo.objects.filter(city=city).values() return JsonResponse({"Foo": list(foo_list)}) But this returns only the attributes from Foo. I want to add the attributes from Bar as well, which are related to Foo. How do I do that? EDIT: The resulting JSON should be somewhat like, { "Foo":[ { "id":1, "name":"A", "city":"B", "Bars":[ { "name":"A" }, { "name":"B" } ] }, { "id":2, "name":"C", "city":"B", "Bars":[ { "name":"D" } ] } ] }
favorite count: 0
type: Question
answer count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/49221179

http://stackoverflow.com/comment/85415415
score: 0
comment on: http://stackoverflow.com/q/49204378
type: Comment
type: QuestionComment
has text: The code you've tried is not wrong. Can you share the url from where you are scraping? Many times Javascript modifies the class name of an element. So, the tag you're seeing in inspection might not be the same as page source.

http://stackoverflow.com/a/49220205
score: 0
answers question: http://stackoverflow.com/q/49220097
type: Answer
has body: Here is a 1-liner but does not take care of the 4 input restriction (in case you need): lst = list(map(int, input().split())) ''' 3 4 5 6 [3, 4, 5, 6] '''

http://stackoverflow.com/q/49211791
answer count: 1
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85428155
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85428151
accepted answer: http://stackoverflow.com/a/49211901
has comment: http://stackoverflow.com/comment/85428309
has body: I've a 1GB json file with very long lines, when I try to load a line from the file I get this error from PyCharm console: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2017.3.3\helpers\pydev\pydev_run_in_console.py", line 53, in run_file pydev_imports.execfile(file, globals, locals) # execute the script File "......... .py", line 26, in &lt;module&gt; for line in f: MemoryError PyDev console: starting. Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32 I'm on a Windows Server machine with 64GB of RAM. My code is: import numpy as np import json import sys import re idRegEx = re.compile(r".*ID=") endElRegEx = re.compile(r"'.*") ratingsFile = sys.argv[1] tweetsFile = sys.argv[2] outputFile = sys.argv[3] tweetsMap = {} with open(tweetsFile, "r") as f: for line in f: tweetData = json.loads(line) tweetsMap[tweetData["key"]] = tweetData output = open(outputFile, "w") with open(ratingsFile, "r") as f: header = f.next() for line in f: topicData = line.split("\t") topicKey = topicData[0] topicTerms = topicData[1] ratings = topicData[2] reasons = topicData[3] ratings = map(lambda x: int(x.strip().replace("'", "")), ratings.replace("[", "").replace("]", "").split(",")) ratings = np.array(ratings) tweetsMap[topicKey]["ratings"] = ratings.tolist() tweetsMap[topicKey]["mean"] = ratings.mean() topicMap = tweetsMap[topicKey] print topicMap["key"], topicMap["mean"] json.dump(topicMap, output, sort_keys=True) output.write("\n") output.close() Line 26 in the error message refers to tweetData = json.loads(line) while line 53 refers to json.dump(topicMap, output, sort_keys=True) The strange thing is that I forked this code from GitHub and so I think it should work.
tagged with: python
linked to: http://stackoverflow.com/q/10187072
type: AnsweredQuestion
has title: Memory error while reading a very long line in a json file with Python
has comment: http://stackoverflow.com/comment/85428268
has answer: http://stackoverflow.com/a/49211901
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/2400643

http://stackoverflow.com/q/49249675
has body: Here is a file called subtitles.ass. If you have a look at it, you will find I define {font_size} and {sentence[0}. Obviously I want to format them with my input data. [Script Info] ; Script generated by FFmpeg/Lavc57.107.100 ScriptType: v4.00+ PlayResX: 384 PlayResY: 288 [V4+ Styles] Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding Style: sorry,Arial,{font_size},&amp;H00FFFFFF,&amp;H000000FF,&amp;H00000000,&amp;H00000000,0,0,0,0,100,100,0,0,1,2,1,2,10,10,12,1 [Events] Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text Dialogue: 0,0:00:00.97,0:00:01.50,sorry,,0,0,0,,{sentence[0]} Dialogue: 0,0:00:03.11,0:00:04.39,sorry,,0,0,0,,{sentence[1]} Dialogue: 0,0:00:05.18,0:00:07.26,sorry,,0,0,0,,{sentence[2]} Dialogue: 0,0:00:07.26,0:00:09.91,sorry,,0,0,0,,{sentence[3]} Dialogue: 0,0:00:10.00,0:00:11.26,sorry,,0,0,0,,{sentence[4]} Dialogue: 0,0:00:11.63,0:00:12.70,sorry,,0,0,0,,{sentence[5]} Dialogue: 0,0:00:13.61,0:00:16.01,sorry,,0,0,0,,{sentence[6]} Dialogue: 0,0:00:18.08,0:00:19.60,sorry,,0,0,0,,{sentence[7]} Dialogue: 0,0:00:19.60,0:00:21.60,sorry,,0,0,0,,{sentence[8]} First I read data from subtitles.ass. with open(subtitles_file, 'r') as file: subtitles = file.read() And now input data comes. { "font_size": "47", "sentences": [ .... ] } Finally I want to format subtitles with above json data. Simply, I want to replace {font_size} with 47. data is above json. subtitles.format(data.get('font_size'), data.get('sentences')) However I got an error. Traceback (most recent call last): File "iemoji.py", line 17, in subtitles.format(data.get('font_size'), data.get('sentences')) KeyError: 'font_size' EDIT for data I load data like this. data = json.load(file)
has comment: http://stackoverflow.com/comment/85502956
upvote count: 1
has comment: http://stackoverflow.com/comment/85502934
has answer: http://stackoverflow.com/a/49249769
has comment: http://stackoverflow.com/comment/85502845
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85504568
has comment: http://stackoverflow.com/comment/85502723
has title: Format string using json
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85502890
has comment: http://stackoverflow.com/comment/85502747
accepted answer: http://stackoverflow.com/a/49250637
type: AnsweredQuestion
favorite count: 0
has answer: http://stackoverflow.com/a/49250637
score: 1
possible better answer: http://stackoverflow.com/a/49249769
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/a/49130468
accepted answer of: http://stackoverflow.com/q/49130121
type: Answer
has comment: http://stackoverflow.com/comment/85275794
score: 4
answers question: http://stackoverflow.com/q/49130121
upvote count: 4
has comment: http://stackoverflow.com/comment/85270216
type: AcceptedAnswer
downvote count: 0
has body: You are creating a generator function. Calling the generator function returns a generator object: &gt;&gt;&gt; def read_file(fp): ... with open(filepath) as fr: ... for line in fr.readlines(): ... yield line ... &gt;&gt;&gt; read_file('asd') &lt;generator object read_file at 0x10554ee08&gt; The open call (which should raise FileNotFoundError) will not be called until you loop over the generator. Then you will see &gt;&gt;&gt; g = read_file('asd') &gt;&gt;&gt; for x in g: ... pass ... Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 2, in read_file NameError: name 'filepath' is not defined I am guessing that you half-changed fp to filepath before posting here. You can fix that but either way you won't see any error from read_file unless you consume the returned generator by iterating over it. EDIT: I don't recommend using a with statement inside a generator like this. The reason is that there is no guarantee that the file will be closed. To understand this consider what the purpose of with is. Before context managers you would open a file like f = open(filename) f.read(4) # etc f.close() The problem with this is that the file may not get closed if something happens (e.g. an exception or return etc) between the open and the close. You can fix this with try/finally i.e. f = open(filename) try: f.read(4) # etc finally: f.close() This is cumbersome so we have the with statement to shorten it to with open(filename) as f: f.read(4) # etc This is good because it reduces clutter and there's no way to leave the with statement without the file being closed. However when you do it in a generator like your read_file above someone might call the generator with for line in read_file(filename): if line.startswith('#'): break Now after the break the generator is suspended at the yield it has no way to know that it will not be iterated on again so it waits there. The yield inside the with block allows you to leave the conte…
has comment: http://stackoverflow.com/comment/85270347

http://stackoverflow.com/comment/85323843
has text: … or you could use a wrapper function that just calls the recursive function and returns the result. In that wrapper, instead of making `fib` a parameter with a default value, just make it a local variable inside the function. That way you get a new list each time you call the wrapper.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49158987
score: 0

http://stackoverflow.com/comment/104049900
type: AnswerComment
type: Comment
has text: @Oli Yeah..you were right. Thanks for the correction and I have updated the answer :)
comment on: http://stackoverflow.com/a/49190645
score: 0

http://stackoverflow.com/a/49274707
has body: The python installer should be in /{matlab_root}/extern/engines/python. Then python setup.py install Hope it helps
answers question: http://stackoverflow.com/q/49270176
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/49256000
tagged with: setuptools
answer count: 1
downvote count: 0
upvote count: 1
has body: Below is my setup file to setup a python wrapper. The issue I am having is that in my c code I am writing is making calls to clock_gettime for profiling reasons. The thing is when I try to import the module I get the following: error undefined symbol: clock_gettime. I understand that I need to compile with -lrt, but obviously my compiler is not getting that flag. What am I doing wrong? from distutils.core import setup, Extension import os module1 = Extension('relaymod', extra_compile_args = ["-lrt"], #flag so compiler links to realtime lib sources=['relaymodule.c'] ) setup (name = 'relaymod', version = '1.0', description = "CTec Relay Board controller", author='Richard Kelly', url='site', ext_modules=[module1]) EDIT: looking at the distutils.core documentation I believe I need to set extra_link_args Below is my new change, but I am now getting this error: NameError: name 'extra_link_args' is not defined EDIT2: ok the code below is now working. Had a few things going on. after I removed the build folder and rebuilt this worked. from distutils.core import setup, Extension import os module1 = Extension('relaymod', extra_link_args=["-lrt"], sources=['relaymodule.c'] ) setup (name = 'relaymod', version = '1.0', description = "CTec Relay Board controller", author='Richard Kelly', url='site', ext_modules=[module1])
favorite count: 0
type: Question
tagged with: linux
score: 1
has title: setting compile arguments in setup.py file (Or linker arguments? -lrt?)
has answer: http://stackoverflow.com/a/49257000
tagged with: python
accepted answer: http://stackoverflow.com/a/49257000
type: AnsweredQuestion
tagged with: python-2.7
tagged with: wrapper

http://stackoverflow.com/comment/85412797
type: AnswerComment
comment on: http://stackoverflow.com/a/49203671
type: Comment
has text: this is really interesting!
score: 0

http://stackoverflow.com/comment/85559070
comment on: http://stackoverflow.com/q/49246856
score: 0
has text: As @Eliethesaiyan says, just reference our global features data in the custom scorer. The order of the features and the labels should match,
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85548106
comment on: http://stackoverflow.com/q/49272584
score: 0
type: Comment
type: QuestionComment
has text: you can specify the numbers in \d+ like \d{3}. see my answer.

http://stackoverflow.com/comment/86460640
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49216247
has text: Well I tried all that but got nowhere, so I just switched over to Linux. Thanks for trying.
score: 0

http://stackoverflow.com/comment/85423155
comment on: http://stackoverflow.com/q/49185332
type: Comment
type: QuestionComment
score: 0
has text: I've pushed latest code, and I still can't find anything wrong...

http://stackoverflow.com/q/49240581
downvote count: 0
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
favorite count: 0
possible better answer: http://stackoverflow.com/a/53164243
type: Question
has body: When initializing my postgres database with sqalchemy, I am getting an AttributeError: can't set attribute error: Traceback (most recent call last): File "manage.py", line 567, in &lt;module&gt; manager.run() File "/usr/local/lib/python3.6/site-packages/flask_script/__init__.py", line 417, in run result = self.handle(argv[0], argv[1:]) File "/usr/local/lib/python3.6/site-packages/flask_script/__init__.py", line 386, in handle res = handle(*args, **config) File "/usr/local/lib/python3.6/site-packages/flask_script/commands.py", line 216, in __call__ return self.run(*args, **kwargs) File "manage.py", line 26, in initdb password="passwo", File "&lt;string&gt;", line 4, in __init__ File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/state.py", line 417, in _initialize_instance manager.dispatch.init_failure(self, args, kwargs) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__ compat.reraise(exc_type, exc_value, exc_tb) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 187, in reraise raise value File "/usr/local/lib/python3.6/site-packages/sqlalchemy/orm/state.py", line 414, in _initialize_instance return manager.original_init(*mixed[1:], **kwargs) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/ext/declarative/base.py", line 700, in _declarative_constructor setattr(self, k, kwargs[k]) File "/usr/local/lib/python3.6/site-packages/sqlalchemy/ext/hybrid.py", line 873, in __set__ raise AttributeError("can't set attribute") AttributeError: can't set attribute The table is defined like this: class User(db.Model, UserMixin): """ A user who has an account on the website. """ __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True, nullable=False, unique=True, autoincrement=True) first_name = db.Column(db.String) last_name = db.Column(db.String) phone = db.Column(db.String) email = db.Column(db.String, unique=True) photo = db.Column(db.String, default="No Picture") _password = …
tagged with: python-3.x
has answer: http://stackoverflow.com/a/53164243
tagged with: python
accepted answer: http://stackoverflow.com/a/49298539
has answer: http://stackoverflow.com/a/49298539
has comment: http://stackoverflow.com/comment/117815279
tagged with: postgresql
type: AnsweredQuestion
score: 3
answer count: 2
upvote count: 3
has title: Sqalchemy postgres: AttributeError: can't set attribute

http://stackoverflow.com/comment/85450266
has text: Good, use [`[,;" ](.+?\/.+?)(?=[,"; ])`](https://regex101.com/r/GeM7ks/2). What is your programming language?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49223238

http://stackoverflow.com/a/50302183
type: AcceptedAnswer
has body: The following seems to work: !wget -c https://repo.continuum.io/archive/Anaconda3-5.1.0-Linux-x86_64.sh !chmod +x Anaconda3-5.1.0-Linux-x86_64.sh !bash ./Anaconda3-5.1.0-Linux-x86_64.sh -b -f -p /usr/local !conda install -y --prefix /usr/local -c &lt;&lt;&lt;your wish&gt;&gt;&gt;&gt; import sys sys.path.append('/usr/local/lib/python3.6/site-packages/')
score: 26
upvote count: 26
accepted answer of: http://stackoverflow.com/q/49202649
type: Answer
answers question: http://stackoverflow.com/q/49202649
downvote count: 0

http://stackoverflow.com/a/49149147
type: Answer
answers question: http://stackoverflow.com/q/49139968
has comment: http://stackoverflow.com/comment/85358552
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: The annotate functionality does exactly what you want. (See also the annotate intro) Given the example you linked, you could just add the following to annotate selected nodes. (It depends on the positions dictionary pos to know where the nodes are located). ax = plt.gca() ax.annotate("3", xy=pos.get('B'), xytext=(0, 40), textcoords='offset points', arrowprops=dict(facecolor='black', shrink=0.15), bbox=dict(boxstyle="round", fc="cyan")) ax.annotate("4", xy=pos.get('F'), xytext=(0, 40), textcoords='offset points', arrowprops=dict(facecolor='black', shrink=0.15), bbox=dict(boxstyle="round", fc="cyan")) So that this answer is self-contained, Full code including linked example: import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph() G.add_edges_from( [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'), ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')]) val_map = {'A': 1.0, 'D': 0.5714285714285714, 'H': 0.0} values = [val_map.get(node, 0.25) for node in G.nodes()] # Specify the edges you want here red_edges = [('A', 'C'), ('E', 'C')] edge_colours = ['black' if not edge in red_edges else 'red' for edge in G.edges()] black_edges = [edge for edge in G.edges() if edge not in red_edges] # Need to create a layout when doing # separate calls to draw nodes and edges pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), node_color = values, node_size = 500) nx.draw_networkx_labels(G, pos) nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True) nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False) # add annotations for selected nodes. ax = plt.gca() ax.annotate("3", xy=pos.get('B'), xytext=(0, 40), textcoords='offset points', arrowprops=dict(facecolor='black', shrink=0.15), bbox=dict(boxstyle="round", fc="cyan")) ax.annotate("4", xy=pos.get('F'), xytext=(0, 40), textcoords='offset points', arrowprops=dict(facecolor='black', shrink=0.15), bbox=dict(boxstyle="round", fc="cyan")) plt.show()
accepted answer of: http://stackoverflow.com/q/49139968

http://stackoverflow.com/a/49162181
has comment: http://stackoverflow.com/comment/85336006
type: Answer
has comment: http://stackoverflow.com/comment/85358403
has body: That's how I would do it. Take the following table, named chords: +--+-----+---+-----+ |id|chord|...|count| +--+-----+---+-----+ |01|Amaj |...|27 | +--+-----+---+-----+ |02|Bmin |...|32 | +--+-----+---+-----+ And a flask route that looks something like this: @app.route('/chord/&lt;chord_id&gt;', methods=['GET']) def chord_info(chord_id): db = MySQLdb.connect("host", "un", "pw", "db") cur = db.cursor() cur.execute("SELECT * FROM chords WHERE id = '%s'" % chord_id) data = cur.fetchone() cur.execute("UPDATE chords SET count = count + 1 WHERE id = '%s'" % chord_id) try: db.commit() except: db.rollback() cur.close() #do something with data This method will give you an easily queried count that is updated everytime the endpoint is accessed.
answers question: http://stackoverflow.com/q/49143160
score: 0

http://stackoverflow.com/q/49175688
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49175749
has comment: http://stackoverflow.com/comment/85357192
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/49178606
has comment: http://stackoverflow.com/comment/85363615
has comment: http://stackoverflow.com/comment/85357092
tagged with: django-templates
has body: I have the line in my template: &lt;div class="class1 class2 class3 {{ foo_classes }}"&gt; If the foo_classes is empty I get class="class1 class2 class3 ". What I want to get is class="class1 class2 class3" with no additional space at the end of the classes list. &lt;div class="class1 class2 class3{{ foo_classes }}"&gt; If I delete the space (look at the line above) then I get class="class1 class2 class3class4 class5", which is no better. How do I pass additional classes to avoid getting unnecessary space at the end of the classes section if the foo_classes is empty?
has title: How to pass custom elements list to the class attribute properly?
answer count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: django
score: 1

http://stackoverflow.com/comment/85289769
has text: @user2357112 Are you sure? I know Python reserves the right to skip any of the different steps for any special method lookup, but CPython does different things for three different groups of them. and I thought numeric methods were in the `type(obj).__getattribute__` group?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49142031
type: Comment

http://stackoverflow.com/q/49127834
answer count: 20
has answer: http://stackoverflow.com/a/60741669
has answer: http://stackoverflow.com/a/60951654
has answer: http://stackoverflow.com/a/51331513
has comment: http://stackoverflow.com/comment/95567426
has answer: http://stackoverflow.com/a/54644465
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/72456811
has answer: http://stackoverflow.com/a/59968387
has answer: http://stackoverflow.com/a/69568584
tagged with: python
has answer: http://stackoverflow.com/a/58147879
tagged with: jupyter
has answer: http://stackoverflow.com/a/49128056
has answer: http://stackoverflow.com/a/56120498
has answer: http://stackoverflow.com/a/65964857
tagged with: conda
score: 942
has answer: http://stackoverflow.com/a/49127971
has answer: http://stackoverflow.com/a/70561986
upvote count: 944
has body: I want to remove a certain environment created with conda. How can I achieve that? Let's say I have an active testenv environment. I tried, by following documentation, with: $ conda env remove CondaEnvironmentError: cannot remove current environment. deactivate and run conda remove again I then deactivate it: $ source deactivate I try running again the command to remove it and I still get the same error. What is going wrong here?
linked to: http://stackoverflow.com/q/34644612
has answer: http://stackoverflow.com/a/61869691
has answer: http://stackoverflow.com/a/75053549
downvote count: 2
has answer: http://stackoverflow.com/a/53240095
has answer: http://stackoverflow.com/a/67074740
has answer: http://stackoverflow.com/a/59678369
has title: Removing Conda environment
has answer: http://stackoverflow.com/a/55476732
favorite count: 0
type: Question
tagged with: environment
has answer: http://stackoverflow.com/a/56311739

http://stackoverflow.com/comment/85516349
comment on: http://stackoverflow.com/q/49254573
score: 0
type: Comment
has text: @DanielRoseman crsf also apply to PUT, DELETE, etc
type: QuestionComment

http://stackoverflow.com/a/49271672
has body: Keys need to be unique. You Have keys = [18, 34, 30, 30, 18] Repeated keys 18 and 30 can not be used twice. Try your script with unique keys and it works fine. Keys read right to left. Notice you get the first key 18 and the first key 30, but the second of each key is passed over
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49268016

http://stackoverflow.com/q/49243360
tagged with: angular
has body: Set Up I am having an odd problem. I have a website and I am hoping to run a python script when someone presses a button. So, I have followed this tutorial: https://www.npmjs.com/package/python-shell Question: My console prints this: ReferenceError: require is not defined on this line: var PythonShell = require('python-shell'); This is the first line in my .js function. I added this line after the npm install step. How do I overcome this error? Potentially Helpful Notes My script looks like this: angular.module('MYApp') .controller('MyTypeController', function ($scope, $http, $stateParams, $state) { $scope.runPythonRoutine = function () { console.log("Error 1"); var PythonShell = require('python-shell'); var myshell = new PythonShell.run('hello.py', function (err, results) { console.log("Error 2"); // script finished }); }; ... My package.json contains: ... "node-uuid": "1.4.7", "python-shell": "^0.5.0", ...
answer count: 1
has answer: http://stackoverflow.com/a/49243930
type: Question
has title: Angular python-shell fails on first line
tagged with: npm
has comment: http://stackoverflow.com/comment/85490623
accepted answer: http://stackoverflow.com/a/49243930
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85490792
score: 0

http://stackoverflow.com/comment/85435479
score: 0
type: Comment
has text: Perfect! Thank you!
type: AnswerComment
comment on: http://stackoverflow.com/a/49215465

http://stackoverflow.com/comment/85497404
type: AnswerComment
comment on: http://stackoverflow.com/a/49246452
has text: Hey sorry I think I wasn't very clear in my description of the desired output. The desired output would be [[['P1'], 20], [['P2'], 20], [['P3'], 10], [['P4'], 0], [['P5'], 0]]
type: Comment
score: 0

http://stackoverflow.com/a/49246630
score: 3
answers question: http://stackoverflow.com/q/49246442
type: Answer
has body: If you want your script to run some outside program, passing in an argument, the way to do that is the subprocess module. Exactly which function to call depends on what exactly do you want to do. Just start it in the background and ignore the result? Wait for it to finish, ignore any output, but check that it returned success? Collect output so you can log it? I'm going to pick one of the many options arbitrarily, but read the linked docs to see how to do whichever one you actually want. for thingy in your_loop: fileName = your_filename_creating_logic(thingy) try: subprocess.run(['program', 'arg1', fileName], check=True) print(f'program ran on {filename} successfully') except subprocess.CalledProcessError as e: print(f'program failed on {filename} with #{e.returncode}') Notice that I'm passing a list of arguments, with the program name (or full path) as the first one. You can throw in hardcoded strings like arg1 or --breakfast=spam, and variables like fileName. Because it's a list of strings, not one big string, and because it's not going through the shell at all (at least on Mac and Linux; things are a bit more complicated on Windows, but mostly it "just works" anyway), I don't have to worry about quoting filename in case it has spaces or other funky characters. If you're using Python 3.4 or 2.7, you won't have that run function; just change it to check_call (and without that check=True argument).
has comment: http://stackoverflow.com/comment/85498176
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/49166156
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy
possible better answer: http://stackoverflow.com/a/49179287
has answer: http://stackoverflow.com/a/49179287
has body: I have a square 2d array of of size n, filled with numeric values. For each entry, I sum that entry's row and column, but subtract the original entry away. while 1: new = np.copy(next) for i in xrange(n): for j in xrange(n): val = new[i][j] rowsum = np.sum(new[i]) colsum = np.sum(new[:,j]) next[i][j] = rowsum+colsum-val-val Accomplishes what I want, but after some iterations, entries often get too large (since they are nearly doubling). I would like to periodically scale down my values, but I want to do so such that I don't lose information. The important information is the percentage difference between any two entries. I want to avoid scaling in a way that makes entries negative. The range of input is not limited in any way. It would be especially great if I could scale it in some way so that negative entries would become positive. I thought that normalizing the matrix might work, but it ended up pushing values together and after some amount of loops all of the values were pretty much equal.
tagged with: python
tagged with: data-science
accepted answer: http://stackoverflow.com/a/49166480
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85341211
has title: How to scale down the values in my 2d numpy array without losing information
answer count: 2
has answer: http://stackoverflow.com/a/49166480
tagged with: matrix
tagged with: math
upvote count: 1

http://stackoverflow.com/comment/85518609
type: QuestionComment
comment on: http://stackoverflow.com/q/49257761
score: 1
has text: Try `df2 = df2.reset_index()`
type: Comment

http://stackoverflow.com/comment/85315646
score: 0
type: Comment
has text: That doesn't seem to work. I have a `CountVectorizer cv`, a list of strings `text`, and a `MultinomialNB predictor`. If I do `dtm = cv.transform(text)` and then `prediction = predictor.predict(dtm)`, I get as many predictions as there are words in the text. It seems it's assigning a class to each word in the text. I don't want that. I have a text that I'd like to have classified as a whole (and so I expect 1 prediction). Am I doing something wrong?
type: QuestionComment
comment on: http://stackoverflow.com/q/49152607

http://stackoverflow.com/q/49173146
has answer: http://stackoverflow.com/a/49174876
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85353986
score: 0
has body: I'm using python 3.5 with bs 4.6, selenium 3.6 and phantomjs to scrape this one site. The script runs on my server which is located in the US and I want to scrape a german site. But I ran into kind of a problem. The html I download looks like this: &lt;div class="col-md-40 product-highlights-container"&gt;&lt;div class="product-filters"&gt;&lt;select class="colorfilter__select"&gt;&lt;option value="{&amp;quot;ebootisId&amp;quot;:&amp;quot;HW102581-1&amp;quot;,&amp;quot;color&amp;quot;:&amp;quot;Midnight Black&amp;quot;,&amp;quot;colorCode&amp;quot;:&amp;quot;000000&amp;quot;,&amp;quot;colorGroup&amp;quot;:&amp;quot;Schwarz&amp;quot;,&amp;quot;colorGroupCode&amp;quot;:&amp;quot;000000&amp;quot;,&amp;quot;deliveryTime&amp;quot;:&amp;quot;2-3 Werktage&amp;quot;,&amp;quot;default&amp;quot;:true,&amp;quot;images&amp;quot;:[{&amp;quot;small&amp;quot;:&amp;quot;/img/dist/HW102581-1_ZU102869_S_1.png&amp;quot;,&amp;quot;medium&amp;quot;:&amp;quot;/img/dist/HW102581-1_ZU102869_M_1.png&amp;quot;,&amp;quot;large&amp;quot;:&amp;quot;/img/dist/HW102581-1_ZU102869_L_1.png&amp;quot;}],&amp;quot;storage&amp;quot;:&amp;quot;64&amp;quot;,&amp;quot;tariffs&amp;quot;:{&amp;quot;TF102910&amp;quot;:{&amp;quot;ebootisId&amp;quot;:&amp;quot;TF102910&amp;quot;,&amp;quot;price&amp;quot;:49,&amp;quot;url&amp;quot;:&amp;quot;/smartphones/samsung/galaxy-s8-inkl-gear-sport?farbe=midnight-black&amp;amp;speicher=64&amp;amp;carrier=vodafone&amp;amp;tarif=comfort-allnet&amp;quot;},&amp;quot;TF101415&amp;quot;:{&amp;quot;ebootisId&amp;quot;:&amp;quot;TF101415&amp;quot;,&amp;quot;price&amp;quot;:49,&amp;quot;url&amp;quot;:&amp;quot;/smartphones/samsung/galaxy-s8-inkl-gear-sport?farbe=midnight-black&amp;amp;speicher=64&amp;amp;carrier=telekom&amp;amp;tarif=comfort-allnet&amp;quot;}},&amp;quot;stock&amp;quot;:1086,&amp;quot;url&amp;quot;:&amp;quot;/smartphones/samsung/galaxy-s8-inkl-gear-sport?farbe=midnight-black&amp;amp;speicher=64&amp;amp;carrier=vodafone&amp;amp;tarif=comfort-allnet&amp;quot;,&amp;qu…
tagged with: http://stackoverflow.com/tag/html
answer count: 1
has comment: http://stackoverflow.com/comment/85353831
type: Question
accepted answer: http://stackoverflow.com/a/49174876
tagged with: beautifulsoup
has title: malformed html with python and beautiful soup
tagged with: web-scraping
tagged with: python

http://stackoverflow.com/comment/85353603
has text: Again, I do not have your tables, nor your data. I cannot know. Please stop using a single question and answer as a generic support service.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49128472

http://stackoverflow.com/a/49147441
upvote count: 1
has comment: http://stackoverflow.com/comment/85627160
has comment: http://stackoverflow.com/comment/85627177
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49134404
has body: Based on Ignacio's answer fitted for your problem. You can first reshape your list into a list of arrays containing 3 elements: import pandas as pd import numpy as np import itertools mylist = [1,2,3,4,5,6,7,8,9,10] _reshaped = np.reshape(mylist[:len(mylist)-len(mylist)%3],(-1,3)) print(_reshaped) [[1 2 3] [4 5 6] [7 8 9]] Note that it works since your list contains multiple of 3 elements (so you need to drop the last elements in order to respect this condition, mylist[:len(mylist)-len(mylist)%3]) - Understanding slice notation See UPDATE section for a reshape that fits to your question. Then apply Ignacio's solution on the reshaped list for value, iden in zip(_reshaped, itertools.cycle(('A', 'B', 'C'))): print(value, iden) [1 2 3] A [4 5 6] B [7 8 9] C UPDATE You can use @NedBatchelder's chunk generator to reshape you array as expected: def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] mylist = [1,2,3,4,5,6,7,8,9,10] _reshaped = list(chunks(mylist, 3)) print(_reshaped) [[1 2 3] [4 5 6] [7 8 9] [10]] Then: for value, iden in zip(_reshaped, itertools.cycle(('A', 'B', 'C'))): print(value, iden) [1 2 3] A [4 5 6] B [7 8 9] C [10] A Performances Your solution : 1.32 ms ± 94.3 µs per loop With a reshaped list : 1.32 ms ± 84.6 µs per loop You notice that there is no sensitive difference in terms of performances for an equivalent result.
downvote count: 0

http://stackoverflow.com/comment/85582394
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49219402
has text: Hey Captivader, happy to hear that it helped you. So if your issue is solved, please accept this answer so that everyone can see this has been solved.
type: Comment

http://stackoverflow.com/a/49176245
has comment: http://stackoverflow.com/comment/98876127
accepted answer of: http://stackoverflow.com/q/49176095
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49176095
has comment: http://stackoverflow.com/comment/85358066
has body: You can iterate through the list and get the names: import serial.tools.list_ports ports = serial.tools.list_ports.comports() print([port.name for port in ports])
score: 3
upvote count: 3
type: Answer

http://stackoverflow.com/comment/85535804
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49264812
has text: Your problem appears linear, so you should be able to solve it to a certain optimum with `scipy.optimize.linprog`, all other methods implemented give you a local optimum, not necessarily the global.

http://stackoverflow.com/comment/85286934
type: AnswerComment
comment on: http://stackoverflow.com/a/49140733
score: 0
type: Comment
has text: You are welcome (-: But be aware of potential performance https://stackoverflow.com/questions/49094885/rolling-grouped-cumulative-sum/49095493?noredirect=1#comment85205072_49095493

http://stackoverflow.com/comment/85418301
comment on: http://stackoverflow.com/a/49204699
has text: I think vba is.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85514148
comment on: http://stackoverflow.com/q/49255374
score: 0
type: Comment
type: QuestionComment
has text: got it. I provided a solution below which should deal with the issue.

http://stackoverflow.com/comment/85312303
has text: It seems there might be something related in the answer of the question, but I'm not sure if it's directly applicable: https://stackoverflow.com/questions/17486578/how-can-you-bundle-all-your-python-code-into-a-single-zip-file
type: Comment
comment on: http://stackoverflow.com/q/49151938
type: QuestionComment
score: 0

http://stackoverflow.com/q/49260014
has answer: http://stackoverflow.com/a/49260305
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49260499
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has title: BeautifulSoup returns empty td tags
tagged with: http://stackoverflow.com/tag/html
accepted answer: http://stackoverflow.com/a/49260499
tagged with: python
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49260305
has body: I'm trying to get some info from this url "http://baloncestoenvivo.feb.es/Game/1881578". And I want to get all the info that there is inside a table which is inside a div with this id = "keyfacts-playbyplay-content-scroll" I access to this table with this code: table = page_soup.find(id="keyfacts-playbyplay-content-scroll").findAll("table", {"class" : "twelve even"}) Then, print "table" to see what I get and I get one tr with no data. However, using firefox or chrome console we can see that there are 799 table rows with data!!! This is what a I get when I print "table" in python console: >> table Tiempo Cuarto Puntuación Acción And this is what we can see in the console: Why don't get the same? All the tr tags with their td tags with information? What am I doing wrong?
answer count: 2

http://stackoverflow.com/a/49121725
has body: Mapping a series if often efficient for a single column. df1 = pd.DataFrame({'col_1': [3, 4, 5], 'col_2': [7, 8, 5]}) df2 = pd.DataFrame({'col_1': [4, 5], 'col_3': [78, 89]}) df1['col_3'] = df1['col_1'].map(df2.set_index('col_1')['col_3']).fillna(0) # col_1 col_2 col_3 # 0 3 7 0.0 # 1 4 8 78.0 # 2 5 5 89.0
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85249642
score: 2
answers question: http://stackoverflow.com/q/49121631
upvote count: 2

http://stackoverflow.com/comment/85538614
comment on: http://stackoverflow.com/q/49267376
score: 0
has text: The csv reader module doesn't care about that. Each row will be an inner list in a 2D nested list, perfect for then using `writerows` to write it back out. No different than `split(",")` there when you then just append the varying-length list to another list, but it will account for carriage returns for you. The reader is still an iterable.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/76879034
type: Answer
has body: You must simply try doing - conda install jupyterlab (Perhaps, Anaconda team have updated the command in recent years or so). Above command works well on Windows/Ubuntu.
score: 0
answers question: http://stackoverflow.com/q/49141525

http://stackoverflow.com/comment/85587324
score: 0
has text: @AdamHarrison Tahnks for your reply, i try the code and its woring.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49185065

http://stackoverflow.com/q/49261615
has title: Error in OpenCV code saying missing module 'face'
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49263363
has comment: http://stackoverflow.com/comment/85526833
tagged with: python
tagged with: opencv
upvote count: 0
answer count: 1
downvote count: 1
score: -1
linked to: http://stackoverflow.com/q/44633378
favorite count: 0
tagged with: face-recognition
type: Question
has body: I am trying to implement face recognition code using Python 2.7 and OpenCV 3.4.1, but I get an error when running the code: face_recognizer = cv2.face.LBPHFaceRecognizer_create() The error message: AttributeError: 'module' object has no attribute 'face' How can I resolve this?

http://stackoverflow.com/comment/85429295
type: AnswerComment
comment on: http://stackoverflow.com/a/49210889
score: 0
has text: If its GTK you are referring you, and your using a Microsoft Windows OS, then you may find the GTK all in one installer useful: http://www.pygtk.org/downloads.html I believe the installer provided by pygtk supports up to 2.7
type: Comment

http://stackoverflow.com/a/49133063
has comment: http://stackoverflow.com/comment/85270954
has comment: http://stackoverflow.com/comment/85282930
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85272056
answers question: http://stackoverflow.com/q/49132151
has body: You should add elephas library as an argument to your spark-submit command. Citing official guide: For Python, you can use the --py-files argument of spark-submit to add .py, .zip or .egg files to be distributed with your application. If you depend on multiple Python files we recommend packaging them into a .zip or .egg. Official guide
type: Answer

http://stackoverflow.com/a/56564933
answers question: http://stackoverflow.com/q/49186886
score: 1
type: Answer
has body: I could solve the issue with the following steps: Increase memory size of the lambda function in the zappa_settings.json: { "dev": { "memory_size": 3008, } } I had to use a newer version of tqdm. Per default it was version 4.19 which had these issues as described here: https://github.com/tqdm/tqdm/issues/466 The described issue is fixed in a newer version. Its only to add tqdm to my requirements.txt and execute a pip upgrade of the package: pip install -U tqdm When I execute zappa deploy dev I get now the following message: (tqdm 4.32.1 (/var/task/ve/lib/python3.6/site-packages), Requirement.parse('tqdm==4.19.1'), {'zappa'}) tqdm 4.19.1 was the default version of zappa and tqdm 4.32.1 is the new version containing the fix.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49275560
has comment: http://stackoverflow.com/comment/85553643
type: UnansweredQuestion
tagged with: brute-force
has body: I am trying to generate all possible keys on a known key_length on Python. Keys are defined as a list of integers between 0 and 255. I am having trouble to generate all the possible keys... If key_length were a constant number such as 2, I would have known how to handle this - it's just 2 for-loops, you know. However, when it's in a variable then I don't know how many for-loops I need to write. I guess I need a different approach. That's what makes it difficult for me.
has title: Generate keys in a brute force way in python
tagged with: python
score: -1
tagged with: cryptography
upvote count: 0
answer count: 2
tagged with: for-loop
has comment: http://stackoverflow.com/comment/85553651
downvote count: 1
has comment: http://stackoverflow.com/comment/85553518
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49275663
has answer: http://stackoverflow.com/a/49275792

http://stackoverflow.com/comment/85435339
type: QuestionComment
has text: @mkrieger1 oh wow, sorry I missed that! Thanks for clarifying!
comment on: http://stackoverflow.com/q/49215384
score: 0
type: Comment

http://stackoverflow.com/q/49152437
has body: I'm trying to filter some log files that are in the format of a table/dataset but .endswith() and .startswith() are not meeting my requirments. I'm using an anonymous function but need to adapt my Python code to check if a string contains .jpg logfilejpg = sc.textFile("/loudacre/logs/*.log").filter(lambda line: line.endswith('.jpg'))
type: AnsweredQuestion
has title: Does Python have a string function to find a section of a string
has comment: http://stackoverflow.com/comment/85309042
has answer: http://stackoverflow.com/a/49152567
upvote count: 1
accepted answer: http://stackoverflow.com/a/49152464
has comment: http://stackoverflow.com/comment/85309528
has comment: http://stackoverflow.com/comment/85309314
possible better answer: http://stackoverflow.com/a/49152497
has comment: http://stackoverflow.com/comment/85309055
favorite count: 0
has comment: http://stackoverflow.com/comment/85309108
has answer: http://stackoverflow.com/a/49152464
has comment: http://stackoverflow.com/comment/85309065
has comment: http://stackoverflow.com/comment/85309873
answer count: 4
has comment: http://stackoverflow.com/comment/85309484
type: Question
has answer: http://stackoverflow.com/a/49152710
tagged with: python
downvote count: 5
score: -4
has answer: http://stackoverflow.com/a/49152497
has comment: http://stackoverflow.com/comment/85310356

http://stackoverflow.com/comment/85361821
has text: When you are calling the script, use `python file.py /home/usr/chris/folder/otherfile.py` etc. Just pass the absolute path of the file.
type: Comment
comment on: http://stackoverflow.com/a/49165069
type: AnswerComment
score: 1

http://stackoverflow.com/a/49220687
has body: As an alternative to kabanus' answer (which uses O(len(x)) dict lookup), this is an approach that use dict values view: x={'a': [{1: 55}, {'c': 43}], 'b': [{1: 43}, {'c': 40}]} for a in x.values(): a.sort(key=lambda i: list(i.values())[0]) print(x) prints {'a': [{'c': 43}, {1: 55}], 'b': [{'c': 40}, {1: 43}]} Try it online! I have not measured the performance of this method, but I expect it would be faster.
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49220428
score: 1
type: Answer

http://stackoverflow.com/q/49270932
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85544931
tagged with: django
tagged with: python
tagged with: post
tagged with: get
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85544977
has title: Display User Profile getting ERROR: 'AnonymousUser' object has no attribute '_meta'
has answer: http://stackoverflow.com/a/49280447
tagged with: django-forms
has answer: http://stackoverflow.com/a/49273259
has comment: http://stackoverflow.com/comment/85544980
type: Question
has comment: http://stackoverflow.com/comment/85544841
has body: I have a simple view that is suppose to check if there is post data, if so update the user data using UserChangeForm. Else get the form data of user and display. Issue: AttributeError at /profile/edit 'AnonymousUser' object has no attribute '_meta' I think it might be this line in the edit_profile view # Handles the get request - if no post info is submitted then get the form and display it on the edit profile page. else: form = UserChangeForm(instance=request.user) args = {'form': form} return render(request, 'accounts/profile_edit.html', args) Not sure what. Here is the view.py edit_profile def edit_profile(request): # Handle post request - if the user submits a form change form details and pass the intance user if request.method == 'POST': form = UserChangeForm(request.POST, intance=request.user) if form.is_valid(): form.save() return redirect('accounts/profile') # Handles the get request - if no post info is submitted then get the form and display it on the edit profile page. else: form = UserChangeForm(instance=request.user) args = {'form': form} return render(request, 'accounts/profile_edit.html', args) profile_edit.html {% extends 'base.html' %} {% block head %} Profile {% endblock %} {% block body %} {% csrf_token %} {{ form.as_p }} Save Changes {% endblock %}

http://stackoverflow.com/q/49205801
has title: wkhtmltopdf with pdfkit not working on VPS server
type: Question
answer count: 0
downvote count: 0
upvote count: 1
has body: I've installed wkhtmltopdf and xvfb. It's working fine in server with command line as well as in django/python shell but with uwsgi+nginx it throwing the below error wkhtmltopdf exited with non-zero code 127. error: /usr/bin/xvfb-run: 25: /usr/bin/xvfb-run: awk: not found /usr/bin/xvfb-run: 97: /usr/bin/xvfb-run: getopt: not found Django Version: 1.11.6 Exception Type: OSError Exception Value: wkhtmltopdf exited with non-zero code 127. error: /usr/bin/xvfb-run: 25: /usr/bin/xvfb-run: awk: not found /usr/bin/xvfb-run: 97: /usr/bin/xvfb-run: getopt: not found Exception Location: /home/dev/env3/lib/python3.5/site-packages/pdfkit/pdfkit.py in to_pdf, line 159 Python Executable: /usr/bin/uwsgi-core Python Version: 3.5.2 in terminal which awk /usr/bin/awk which getopt /usr/bin/getopt Thanks.
type: UnansweredQuestion
tagged with: django
tagged with: ubuntu
favorite count: 0
tagged with: wkhtmltopdf
tagged with: pdfkit
score: 1
tagged with: python

http://stackoverflow.com/comment/85455440
score: 3
has text: Python isn't great for performance critical code. I wouldn't be surprised if it can't hit your NIC line rate with one core. Try running multiple copies at once. If that increase your throughput, you have little choice but to re-write the loop in something faster - e.g. C. On the other hand, if it makes no odds, you've hit the packet rate for your NIC.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49170605

http://stackoverflow.com/a/49148592
accepted answer of: http://stackoverflow.com/q/49147875
has comment: http://stackoverflow.com/comment/85301647
has comment: http://stackoverflow.com/comment/85302286
type: Answer
has body: This should work for you. tested on python 3.6 chess = "♔ ♕ ♖ ♗ ♘ \u2655 \u2656 \u2657 \u2658 \u2659 \u265a" f = open('file', 'wb') f.write(chess.encode('utf8')) f.close() f = open('file', 'rb') print (f.read().decode('utf-8'))
has comment: http://stackoverflow.com/comment/85302371
score: 0
has comment: http://stackoverflow.com/comment/85302068
has comment: http://stackoverflow.com/comment/85302391
answers question: http://stackoverflow.com/q/49147875
type: AcceptedAnswer

http://stackoverflow.com/comment/85348427
type: Comment
has text: I guess you are trying to ask about [tag:numpy]? If so, please [edit] the tags (probably remove the chaff with [tag:list] and possibly others).
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49171412

http://stackoverflow.com/a/49176088
type: Answer
score: 5
accepted answer of: http://stackoverflow.com/q/49175832
type: AcceptedAnswer
downvote count: 0
has body: The relevant part of the documentation on assignment statements is: If the target list is a comma-separated list of targets, or a single target in square brackets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets. (Emphasis mine: that's how the order is determined.)
answers question: http://stackoverflow.com/q/49175832
upvote count: 5

http://stackoverflow.com/q/49195348
has answer: http://stackoverflow.com/a/49195506
tagged with: python
has title: How to ignore some part of a line using python?
type: AnsweredQuestion
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/85395958
has body: S1C(SCC1)C1=COC2C(C{OC}C3C(OC=C3)C2)C1=O In the above string, I want the program to ignore {OC} or technically anything in between these flower brackets but work normally with rest of the string. I have a file which thousands of such strings. Some strings have more than one set of flower brackets. How should it be done? Presently I use python 2.5 version.
type: Question
has answer: http://stackoverflow.com/a/49195514
has comment: http://stackoverflow.com/comment/85395457
possible better answer: http://stackoverflow.com/a/49195506
accepted answer: http://stackoverflow.com/a/49195480
has comment: http://stackoverflow.com/comment/85396417
has answer: http://stackoverflow.com/a/49195480

http://stackoverflow.com/comment/85432318
type: AnswerComment
has text: My reason for wanting to binarize the data, is because I wanted to try using a convolutional variational auto-encoder similar to [here](https://github.com/blei-lab/edward/blob/master/examples/vae_convolutional.py). I did not mention this in my original post because I was interested in finding out valid methods for binarising image data
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49211238

http://stackoverflow.com/comment/85478322
comment on: http://stackoverflow.com/q/49224425
has text: @JahKnows I found the issue. cuDNN 7.1.1 doesn't work yet with tensorflow-gpu. I downgraded cuDNN to 7.0.5 and now the code works as expected.
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/103725821
comment on: http://stackoverflow.com/q/49232231
type: QuestionComment
type: Comment
has text: @BennettBrown What would that look like?
score: 0

http://stackoverflow.com/comment/85357249
score: 0
type: QuestionComment
has text: I don't know the exact answer, but I think one step would be to change the type of `b` to `ctypes.c_void_p`
comment on: http://stackoverflow.com/q/49175959
type: Comment

http://stackoverflow.com/a/49261255
score: 0
type: Answer
has body: I know I can just print pickle.load again but what if I have an unknown number of items in my pickle file with a number of Datatypes (e.g: lists, tuples, dictionaries, strings....) There are several ways around this: Pack all of the items into a single list or tuple, and pickle that instead of pickling them individually. You can then unpack on the other side. Pickle an integer describing the number of items first. That then tells you how many times to call pickle.load(). Just keep unpickling until you hit EOF.
answers question: http://stackoverflow.com/q/49261006

http://stackoverflow.com/q/49168887
has body: have plotted a graph which has time on x axis and delta time on y axis. when the graph is saved as html using mpld3 maximum value on y axis is changed. how to have save graph as html without changing the value on y axis. import matplotlib.pyplot as plt,mpld3 import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas as pd import datetime from datetime import datetime css = """ text.mpld3-text, div.mpld3-tooltip { font-family: 'Lato', sans-serif; font-weight: 80; font-size: 10px; border: 5px; } """ with open('k.html', 'w') as f: date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013', '7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013', '11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013'] time = ['0:0:04', '00:00:20', '0:0:40', '00:00:55', '00:48:00', '00:49:00', '00:00:7', '00:00:50', '00:00:10', '00:00:30', '00:1:01', '00:01:04'] time2=[] for i in range(0,len(time)): time2.append(datetime.strptime(time[i], '%H:%M:%S')) ax=plt.gca() # Convert to matplotlib's internal date format. line1 = ax.plot(pd.to_datetime(date),time2, linewidth=1, marker=".", markerfacecolor="none", markeredgecolor="g") plt.show() plt.title("x") plt.ylabel('Delta Time (SBX)') mpld3.save_html(plt.gcf(), f, template_type='simple',figid='fig01') #plt.show() mpld3.save_html(plt.gcf(), f, template_type='simple',figid='fig01') f.write('\n\n\n \n') f.write('var f1=') mpld3.save_json(plt.gcf(), f) f.write(';\n\n')
score: 0
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85347006
type: Question
has comment: http://stackoverflow.com/comment/85380224
answer count: 0
type: UnansweredQuestion
has title: 60 seconds is shown as 12:01 on y axis when the matplotlib plot is saved as html using mpld3
tagged with: mpld3
tagged with: python

http://stackoverflow.com/comment/85438395
comment on: http://stackoverflow.com/a/49214124
type: Comment
score: 0
type: AnswerComment
has text: Thanks for the explanation.But i need youtube comments for my project.So i just learned basics of selenium to scrap with python.Can you provide a code with a youtube link that can give the comment of that video

http://stackoverflow.com/comment/85455833
has text: @StevenTautonico search in SO with [tkinter] tag. There is plenty of info here. Google would probably send you over here anyway. Find a good tutorial on tkinter. Try here http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html. tkinter can be confusing at first. Search for python tutorials too. Learning tkinter without knowing python basics well will be much more intriguing.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49225757

http://stackoverflow.com/a/49175818
answers question: http://stackoverflow.com/q/49174452
type: Answer
has body: I installed Spyder which is an opensource and found the option that I was looking for.
score: 0

http://stackoverflow.com/q/49197821
tagged with: python
tagged with: regex
type: Question
score: 2
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49197951
has answer: http://stackoverflow.com/a/49197951
downvote count: 0
possible better answer: http://stackoverflow.com/a/49198399
favorite count: 0
tagged with: pattern-matching
has answer: http://stackoverflow.com/a/49198399
type: AnsweredQuestion
has title: Using Regex to extract a specific word followed by certain syntax (such as parentheses)
has body: I have a very large document containing section references in different formats. I want to extract these references using Python &amp; regex. Examples of the string formats: 1) Section 23 2) Section 45(3) 3) point (e) of Section 75 4) Sections 21(1), 54(2), 78(1) Right now, I have the following code: s = "This is a sample for Section 231" m = re.search('Section\\W+(\\w+)', s) m.group(0) The output is: Section 231 This works perfectly, except that it does not account for the other formatting cases. Is there any way to indicate that for 231(1), the (1) should also be extracted? Or to include the following section numbers if several others are listed? I'm also open to using other libraries if you think Regex is not the best in this case. Thank you!

http://stackoverflow.com/a/49810442
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49228232
has body: This is how we do it in typescript. You could translate it into your python code. import * as watson from "watson-developer-cloud"; let speechToText = new watson.SpeechToTextV1({ username: &lt;your_service_username&gt;, password: &lt;your_service_password&gt;, version: &lt;your_service_version&gt; }); speechToText.recognize(&lt;your_options_here&gt;, &lt;callback_function_here&gt;);

http://stackoverflow.com/a/49241754
has comment: http://stackoverflow.com/comment/119358478
score: 8
has comment: http://stackoverflow.com/comment/120416758
answers question: http://stackoverflow.com/q/49185538
type: Answer
has comment: http://stackoverflow.com/comment/108954510
has comment: http://stackoverflow.com/comment/119345447
accepted answer of: http://stackoverflow.com/q/49185538
downvote count: 2
has comment: http://stackoverflow.com/comment/108955353
type: AcceptedAnswer
has body: Call your progress function inside the Youtube class yt = YouTube(video_link, on_progress_callback=progress_function) This is your progress function def progress_function(self,stream, chunk,file_handle, bytes_remaining): size = stream.filesize p = 0 while p &lt;= 100: progress = p print str(p)+'%' p = percent(bytes_remaining, size) This computes the percentage converting the file size and the bytes remaining def percent(self, tem, total): perc = (float(tem) / float(total)) * float(100) return perc
upvote count: 10

http://stackoverflow.com/a/49210781
answers question: http://stackoverflow.com/q/49209385
has body: The surface answer to your question is fairly simple, The queued_writer process is still waiting for entries to be written to the queue when the main process ends, sending an EOF to the open blocking connection that self.queue.get opened. That raises the question of why the atexit.register didn't seem to do it's job, but of that I do not know the reason for.
score: 0
type: Answer

http://stackoverflow.com/comment/85376886
has text: @JamesPhillips Sorry for being dense, but what question would you like to have asked?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49163685

http://stackoverflow.com/q/49245180
score: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49245251
tagged with: pyenv
tagged with: python
favorite count: 0
type: Question
upvote count: 4
has body: I'm trying to run a python web app on Apache server. I have installed mod_wsgi: sudo apt-get install libapache2-mod-wsgi. This is my site config file: &lt;virtualhost *:80&gt; ServerName 192.168.60.144 WSGIDaemonProcess myapp.dev processes=1 threads=1 python-home="/home/user/.pyenv/versions/3.6.1" python-path="/home/user/API" home='/home/user/API' WSGIProcessGroup myapp.dev WSGIScriptAlias / /home/user/API/config_files/myservice.wsgi.py &lt;Directory /home/user/API&gt; Order allow,deny Allow from all &lt;/Directory&gt; DocumentRoot /home/user/API/myservice/testdir &lt;Directory /&gt; AllowOverride None Require all granted &lt;/Directory&gt; &lt;/virtualhost&gt; However, when trying to access the web app, I get "Internal server error". This is the error from logs: [Mon Mar 12 13:34:04.054636 2018] [wsgi:error] [pid 6762:tid 139768980616960] [remote 10.10.30.13:34438] mod_wsgi (pid=6762): Target WSGI script '/home/user/API/config_files/myservice.wsgi.py' cannot be loaded as Python module. [Mon Mar 12 13:34:04.054665 2018] [wsgi:error] [pid 6762:tid 139768980616960] [remote 10.10.30.13:34438] mod_wsgi (pid=6762): Exception occurred processing WSGI script '/home/user/API/config_files/myservice.wsgi.py'. [Mon Mar 12 13:34:04.054693 2018] [wsgi:error] [pid 6762:tid 139768980616960] [remote 10.10.30.13:34438] Traceback (most recent call last): [Mon Mar 12 13:34:04.054717 2018] [wsgi:error] [pid 6762:tid 139768980616960] [remote 10.10.30.13:34438] File "/home/user/API/config_files/myservice.wsgi.py", line 6, in [Mon Mar 12 13:34:04.054752 2018] [wsgi:error] [pid 6762:tid 139768980616960] [remote 10.10.30.13:34438] from pathlib import Path [Mon Mar 12 13:34:04.054775 2018] [wsgi:error] [pid 6762:tid 139768980616960] [remote 10.10.30.13:34438] ImportError: No module named pathlib I have checked the pyenv python installation, and it has the pathlib module installed. This means that probably, not the right version of Python is being used. How can I check which Python version is…
tagged with: mod-wsgi
tagged with: apache
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49245251
has title: Run mod_wsgi with pyenv

http://stackoverflow.com/a/49139350
type: Answer
answers question: http://stackoverflow.com/q/49138786
score: 0
has comment: http://stackoverflow.com/comment/85285137
has comment: http://stackoverflow.com/comment/85286633
has comment: http://stackoverflow.com/comment/85284731
has body: I'm assuming you want the files sorted by the number directly preceding the file extension. import re files = os.listdir(os.getcwd()) sorted_files = sorted(files,key=lambda x: int(re.sub(r'\D','',x.strip())[3:])) print(sorted_files)
has comment: http://stackoverflow.com/comment/85290328
has comment: http://stackoverflow.com/comment/85284672

http://stackoverflow.com/a/73174935
downvote count: 1
answers question: http://stackoverflow.com/q/49218802
has body: I think the difference can be understood with the following example . Let's say a college A has maxmimum seats available are 200 in CS Stream and college B has maximum seats 500 for CS stream for this scenerio field validation at serializers makes sense Now let's assume if there is a restriction on the number of student that are allowed in CS Stream for all colleges the we should use the Model level field validation I hope this helps
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/q/49277795
has body: I came across some answers regarding the possibility of image recognition (and further matching) in Python and other languages, as well as papers describing a machine learning process for matching signatures*, but none in R regarding the possibility of recognizing signatures. In Python, a language in which I might try a hand at, I found the OpenCV library for face recognition. But still is not exactly what I need. For an R user (and someone willing to instruct himself in Python), what is the best strategy -- considering time, nothing that it would take more than a few days of learning -- to create an algorithm for signature matching in R or Python?
downvote count: 0
tagged with: image-processing
favorite count: 0
type: Question
score: 3
has comment: http://stackoverflow.com/comment/85561228
type: UnansweredQuestion
tagged with: python
has title: Image Matching and Recognition in R (document signatures)
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/85571347
answer count: 0
upvote count: 3

http://stackoverflow.com/q/49278686
answer count: 0
upvote count: 2
tagged with: http://stackoverflow.com/tag/pdf
downvote count: 0
has comment: http://stackoverflow.com/comment/85613721
tagged with: python-requests
favorite count: 0
tagged with: beautifulsoup
type: Question
has title: Download Multiple PDF files from a webpage
type: UnansweredQuestion
tagged with: python
score: 2
has body: So I am trying to download a few eBooks that I have purchased through humble bundle. I am using beautifulsoup and requests to try and parse the html and get the href links for the pdfs. Python import requests from bs4 import BeautifulSoup r = requests.get("https://www.humblebundle.com/downloads?key=fkuzzq6R8MA8ydEw") soup = BeautifulSoup(r.content, "html.parser") links = soup.find_all("div", {"class": "js-all-downloads-holder"}) print(links) I am going to put a imgar link to the site and html layout because I don't believe you can access the html page without prompting a login(Which might be one of the reason I am having this issue to start with.) https://i.sstatic.net/RFjWU.jpg HTML PDF PDF So the print statement should output to contents of the div but that is not the case. Output python3 pdf_downloader.py [] Sorry for the long post, I have just been up all night working on this and at this point it would have just been easier to hit the download button 20+ times but that is not how you learn.
has comment: http://stackoverflow.com/comment/85563710

http://stackoverflow.com/comment/85339958
comment on: http://stackoverflow.com/q/49166873
score: 2
has text: Not accepting answers that do answer your questions as solutions, can make users that are able to help you less eager to really help you. This is one such case.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85315249
type: Comment
score: 0
has text: depends on the functions of A or B this may or may not work as intended hence we should ask OP for clarification...
type: AnswerComment
comment on: http://stackoverflow.com/a/49155331

http://stackoverflow.com/q/49135880
score: 1
tagged with: svm
favorite count: 0
type: Question
answer count: 0
downvote count: 0
tagged with: classification
type: UnansweredQuestion
tagged with: naivebayes
tagged with: python
has body: Training data: csv image Prediction data: csv image I need to produce accuracy and confusion matrix of svm and naive-bayes classification in python. Thanks in advance.
tagged with: confusion-matrix
has title: How to get svm and naive-bayes classification accuracy and confusion matrix from csv UTF-8 (comma delimited) in python
upvote count: 1

http://stackoverflow.com/a/49138599
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/49138499
has comment: http://stackoverflow.com/comment/85282503
type: Answer
has comment: http://stackoverflow.com/comment/85282974
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49138499
has body: I think it can be done by .loc data.loc[data['holiday']==1,'settle'] += pd.tseries.offsets.BDay(1)

http://stackoverflow.com/a/49171580
answers question: http://stackoverflow.com/q/49171535
type: Answer
has body: Looks like you are running this from a Python Interpreter. Enter exit() and then paste the command again
score: 2
accepted answer of: http://stackoverflow.com/q/49171535
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49238522
type: Question
has comment: http://stackoverflow.com/comment/86924021
has comment: http://stackoverflow.com/comment/85481237
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85515206
tagged with: python
tagged with: design-patterns
has comment: http://stackoverflow.com/comment/85482291
tagged with: model-view-controller
has body: I'm working on a small python (3.6.4) application (for mac os) and I'm having some trouble with implementing a controller/model relationship. I'm kind of new to python and MVC (and design patterns in general for that matter). The program creates zip files that can be written to tape. Three folders that are used: input_folder - Where the user can copy Project folders to. process_folder - Where Projects are copied to and processed by the program. output_folder - Contains projects with zip files created by the program. Basic steps of the program: The program watches the input folder for "Project folders". The Project folders contain one or more "Episode folders" that each have some files in them. The program checks if the name of a project folder is present in a database (user is responsible for adding project names) and creates a matching Project folder in the process folder with a formatted name (lowercase_without_spaces). Episode folders for each episode are also checked. (In this case if they haven't been archived before) Episodes are copied from the input folder to the process folder once the files they contain are complete. (i.e. Filesize stays the same for 3 seconds) For each Project, episodes are zipped from the process folder and moved to the corresponding Project folder in the output folder. I have a Project and Episode class. Both classes contain their folder name from the input folder and their formatted name upon which the folder names in the process folder are based. Each Project object contains a list of Episode objects and eventually every Episode object contains a list of File objects. (Probably very bad...) Currently I have a controller that takes care of both Projects and Episodes within projects so control remains in a central place. For example: project.add_episodes(Episode('sometitle')) project.process_episodes() A couple of questions: Is my single controller approach the correct way to do this? What could be a good design pattern for my Project/E…
has comment: http://stackoverflow.com/comment/85481219
score: 0
has comment: http://stackoverflow.com/comment/85481848
answer count: 0
has comment: http://stackoverflow.com/comment/85481899
has title: Python: MVC implementation with complex model interaction
tagged with: macos
has comment: http://stackoverflow.com/comment/85507761

http://stackoverflow.com/comment/133320827
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49254599
has text: Thanks for answer ! How to change the fontsize ?
type: AnswerComment

http://stackoverflow.com/comment/85280525
type: QuestionComment
comment on: http://stackoverflow.com/q/49137560
score: 0
has text: Hey so i updated the code
type: Comment

http://stackoverflow.com/q/49130476
type: Question
has comment: http://stackoverflow.com/comment/85266387
has comment: http://stackoverflow.com/comment/85269701
has title: Python Introspection: How do I find out what functions can be applied to instances of classes
type: UnansweredQuestion
score: 0
answer count: 1
has body: For example: air_passengers.rolling_window(window = 12).mean().plot() How do I find out that mean() can be applied to a rolling_window()? How do I find out that plot() can be applied to a mean()? Is there something equivalent to doc for this?
linked to: http://stackoverflow.com/q/1911281
has answer: http://stackoverflow.com/a/49130565
tagged with: introspection
tagged with: python
has comment: http://stackoverflow.com/comment/85273396

http://stackoverflow.com/q/49206406
tagged with: python
tagged with: flask
tagged with: put
score: 0
has comment: http://stackoverflow.com/comment/85418540
answer count: 0
has comment: http://stackoverflow.com/comment/85433041
has comment: http://stackoverflow.com/comment/85417865
has title: Using Python Flask and SQLite, how do I update certain fields using a CURL command?
tagged with: flask-sqlalchemy
type: Question
tagged with: python-3.x
has body: I am trying to create an API using Python Flask and SQLite. I currently have implemented a post method, where I set each data parameter in the curl command to be a different variable. However, for a put method, I could possibly want only a few fields updated. How would I implement this? For reference, this is what I have so far: from flask import Flask, request from flask_restful import Resource, Api from sqlalchemy import create_engine from json import dumps from flask_jsonpify import jsonify db = create_engine('sqlite:///employees.db') app = Flask(__name__) api = Api(app) conn = db.connect() class EmployeeID(Resource): def get(self, employeeid): query = conn.execute("SELECT * FROM employees WHERE EmployeeId =%d " %int(employeeid)) result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]} return jsonify(result) def delete(self, employeeid): conn.execute("DELETE FROM employees WHERE EmployeeId = %d " %int(employeeid)) return "Employee Deleted" def put(self, employeeid): #Trying to figure out how to do this query = conn.execute("SELECT * FROM employees WHERE EmployeeId =%d " %int(employeeid)) return "Employee Updated" api.add_resource(EmployeeID, '/employees/&lt;employeeid&gt;') For example: curl -X PUT -H "Content-Type: application/json" -d '{"key1":"value", "key2":"value2"}' "MY_URL" I would want to update only key1 and key2. How would I access specifically these two keys of the employee without touching the rest? Keep in mind it will not always be key1 and key2. Thanks for any help!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85418419

http://stackoverflow.com/comment/85390925
type: Comment
type: QuestionComment
has text: Forget to mention, the response list will be in json format.
comment on: http://stackoverflow.com/q/49193097
score: 0

http://stackoverflow.com/q/49195816
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85398104
has comment: http://stackoverflow.com/comment/85398155
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85397988
has answer: http://stackoverflow.com/a/49211649
favorite count: 0
type: Question
tagged with: time-series
has comment: http://stackoverflow.com/comment/85397060
has comment: http://stackoverflow.com/comment/85398132
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/20672236
tagged with: python
has comment: http://stackoverflow.com/comment/85398009
has comment: http://stackoverflow.com/comment/85399114
has title: Time Series decomposition in Python withouth datetimeindex
accepted answer: http://stackoverflow.com/a/49211649
has comment: http://stackoverflow.com/comment/85396632
has body: I am trying to decompose a Time Series, however my data does not have Dates, it is composed of entries taken at regular (and unknown) time intervals. This solution is great and exactly what I want, however it assumed that my series has a datetime index, which it does not. I can estimate the frequency parameter in this specific case, however this will need to be automated for different data, and as such I can not use the freq parameter of the seasonal_decompose function (unless there is some way to automatically calculate this) to make do for the fact that my series lacks a datetime index.
has comment: http://stackoverflow.com/comment/85397008

http://stackoverflow.com/comment/85449166
score: 0
has text: Set v as a variable at the top and do v += value. Then get rid of sum ()
comment on: http://stackoverflow.com/q/49222813
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49263841
has comment: http://stackoverflow.com/comment/85531885
answers question: http://stackoverflow.com/q/49263271
has body: The recurrent layer takes inputs of shape (batch_size, timesteps, input_features). Since the shape of x is (1, 50, 4), the data should be interpreted as a single batch of 50 timesteps, each containing 4 features. When initializing the first layer of a model, you pass an input_shape: a tuple specifying the shape of the input, excluding the batch_size dimension. In the case of LSTM layers, you can pass None as the timesteps dimension. Hence, this is how the first layer of the network should be initialized: model.add(LSTM(32, return_sequences=True, input_shape=(None, 4))) The second LSTM layer is followed by a dense layer. So you don't need to return sequences for this layer. Hence, this is how you should initialize the second LSTM layer: model.add(LSTM(32)) Every batch of 50 time steps in x is supposed to be mapped to a single action vector in y. Therefore, since the shape of x is (1, 50, 4), the shape of y must be (1, num_actions). Make sure y doesn't have the timesteps dimension. Therefore, under the assumption that x and y have the right shapes, the following code should work: model = Sequential() model.add(LSTM(32, return_sequences=True, input_shape=(None, 4))) model.add(LSTM(32)) model.add(Dense(num_actions)) model.compile(sgd(lr=.2), "mse") # x.shape == (1, 50, 4) # y.shape == (1, num_actions) history = model.fit(x, y)
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85531533
has comment: http://stackoverflow.com/comment/85535799
type: Answer
accepted answer of: http://stackoverflow.com/q/49263271
score: 2

http://stackoverflow.com/q/49178024
has body: I'd like for a child factory to extend the Params of its parent. I think extending params is preferable to duplicating them. I've tried by making the Params in the subclass literally inherit from the parent Params, like so: import factory class BaseFactory(factory.Factory): class Params: configuration_one = True class MyFactory(BaseFactory): class Params(BaseFactory.Params): configuration_two = False This is failing with the exception: AttributeError Traceback (most recent call last) &lt;ipython-input-5-cc609d2c781d&gt; in &lt;module&gt;() 6 configuration_one = True 7 ----&gt; 8 class MyFactory(BaseFactory): 9 class Params(BaseFactory.Params): 10 configuration_two = False &lt;ipython-input-5-cc609d2c781d&gt; in MyFactory() 7 8 class MyFactory(BaseFactory): ----&gt; 9 class Params(BaseFactory.Params): 10 configuration_two = False 11 AttributeError: type object 'BaseFactory' has no attribute 'Params' What is causing this error, and is there an idiomatic way to accomplish my goal? Versions Python - 2.7.12 factory_boy - 2.9.2
tagged with: factory-boy
has answer: http://stackoverflow.com/a/54840006
downvote count: 0
has title: Inherit Params from parent factory with factory_boy
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/54840678
answer count: 2
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2

http://stackoverflow.com/comment/85369466
type: QuestionComment
score: 0
has text: @abarnert or https://stackoverflow.com/questions/7082027/python-get-selected-text
type: Comment
comment on: http://stackoverflow.com/q/49181697

http://stackoverflow.com/a/49209790
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85424493
has body: Apparently I've just been informed that Python 3.4.2 isn't available for my distro
answers question: http://stackoverflow.com/q/49194523

http://stackoverflow.com/a/55210905
downvote count: 0
has body: I've written an example layer in keras which calls the tensorflow padding backend. import keras.backend as K from keras.layers import Layer class SymmetricPadding2D(Layer): def __init__(self, output_dim, padding=[1,1], data_format="channels_last", **kwargs): self.output_dim = output_dim self.data_format = data_format self.padding = padding super(SymmetricPadding2D, self).__init__(**kwargs) def build(self, input_shape): super(SymmetricPadding2D, self).build(input_shape) def call(self, inputs): if self.data_format is "channels_last": #(batch, depth, rows, cols, channels) pad = [[0,0]] + [[i,i] for i in self.padding] + [[0,0]] elif self.data_format is "channels_first": #(batch, channels, depth, rows, cols) pad = [[0, 0], [0, 0]] + [[i,i] for i in self.padding] if K.backend() == "tensorflow": import tensorflow as tf paddings = tf.constant(pad) out = tf.pad(inputs, paddings, "REFLECT") else: raise Exception("Backend " + K.backend() + "not implemented") return out def compute_output_shape(self, input_shape): return (input_shape[0], self.output_dim) if __name__ == "__main__": from keras.models import Sequential import numpy as np #Set Image image = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] # Pad to "channels_last format # which is [batch, width, height, channels]=[1,4,4,1] image = np.expand_dims(np.expand_dims(np.array(image),2),0) #Build Keras model model = Sequential() model.add(SymmetricPadding2D(1, input_shape=(4,4,1))) model.build() # To simply apply existing filter, we use predict with no training out = model.predict(image) print(out[0,:,:,0])
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49189496

http://stackoverflow.com/q/49244969
answer count: 2
has title: Custom TensorFlow metric: true positive rate at given false positive rate
has answer: http://stackoverflow.com/a/68209981
possible better answer: http://stackoverflow.com/a/68209981
tagged with: python
tagged with: keras
has answer: http://stackoverflow.com/a/49265081
accepted answer: http://stackoverflow.com/a/49265081
type: AnsweredQuestion
score: 3
upvote count: 3
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has body: I have a binary classification problem with categories background (bg) = 0, signal (sig) = 1, for which I am training NNs. For monitoring purposes, I am trying to implement a custom metric in Keras with TensorFlow backend that does the following: 1) Calculate the threshold on my NN output which would result in a false positive rate (classifying bg as signal) of X (in this case X = 0.02, but it could be anything). 2) Calculate the true positive rate at this threshold. Given numpy arrays y_true, y_pred, I would write a function like: def eff_at_2percent_metric(y_true, y_pred): #Find list of bg events bg_list = np.argwhere(y_true &lt; 0.5) #Order by the NN output ordered_bg_predictions = np.flip(np.sort(y_pred[bg_list]),axis=0) #Find the threshold with 2% false positive rate threshold = ordered_bg_predictions[0.02*round(len(ordered_bg_list))] #Find list of signal events sig_list = np.argwhere(y_true &gt; 0.5) #Order these by NN output ordered_sig_predictions = np.sort(y_pred[sig_list]) #Find true positive rate with this threshold sig_eff = 1 - np.searchsorted(ordered_sig_predictions,threshold)/len(ordered_sig_predictions) return sig_eff Of course, this does not work because to implement a custom metric, y_true and y_pred are supposed to be TensorFlow tensors rather than numpy arrays. Is there any way I can make this work correctly?

http://stackoverflow.com/q/49199414
score: 0
accepted answer: http://stackoverflow.com/a/49199685
possible better answer: http://stackoverflow.com/a/49199497
has answer: http://stackoverflow.com/a/49199685
has answer: http://stackoverflow.com/a/49199497
type: Question
answer count: 2
tagged with: python
has body: I know pandas can automatically join rows and get the sum of the rows using groupby() function. But how to combine two or more rows which don't have common values. Consider the following example data set. Col1 Col2 Col3 Col4 0 11 13 5.5 0.9 1 14 6 3.1 0.7 2 18 7 5.5 0.1 3 9 2 7.0 0.2 4 17 10 2.3 1.1 5 15 3 6.9 2.7 6 11 4 3.5 2.9 7 13 11 4.6 0.2 Let's say I want to combine rows 3,4 adding the values together (sum) and also combine rows 6,7 same way separately (i.e. sum). How can I achieve this in pandas?
has title: How to combine only given rows in python pandas?
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/a/49191214
accepted answer of: http://stackoverflow.com/q/49191064
has body: Because not_completed running in import time @not_completed def test_not_completed(a, b): print("invoke test", a+b) is def test_not_completed(a, b): print("invoke test", a+b) test_not_completed = not_completed(test_not_completed) So not_completed is not running inside the resource manager
has comment: http://stackoverflow.com/comment/85436473
type: Answer
answers question: http://stackoverflow.com/q/49191064
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49152221
tagged with: hdf5
has answer: http://stackoverflow.com/a/49152415
has answer: http://stackoverflow.com/a/76511534
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85308622
has comment: http://stackoverflow.com/comment/85308756
has answer: http://stackoverflow.com/a/50094640
tagged with: hdf5storage
tagged with: python
has title: Memory Error : Training large dataset
tagged with: keras
possible better answer: http://stackoverflow.com/a/50094640
type: AnsweredQuestion
score: 0
answer count: 3
accepted answer: http://stackoverflow.com/a/49152415
has body: memory error My dataset have 70k images which i want to train through Conv2D but it is throwing memory error when i tried to load the dataset. I just have 4GB RAM, how i can resolve this issue through HDF5 matrix by creating a dataset in HDF5? and then loading it to train, i guess it will take less memory then. I tried some tutorial to create HDF5 dataset but this processes comes after where the error is occurring. What i am doing wrong? Please ask if question is not clear. datagen=ImageDataGenerator(rotation_range=40, width_shift_range=0.2, height_shift_range=0.2, rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) batch_size=28 num_classes=37 epochs=100 os.chdir("E:"); path="Dataset/One"; classes=os.listdir(path) x=[]#Datapoints y=[]#labels for fol in classes: imgfiles=os.listdir(path+u'\\'+fol); for img in imgfiles: im=Image.open(path+u'\\'+fol+u'\\'+img); im=numpy.asarray(im)/255; x.append(im) y.append(fol) x=numpy.array(x) y=numpy.array(y) #memory error#################################################### x=x.reshape((-1,100,100,1)) n=x.shape[0] randomize=numpy.arange(n) numpy.random.shuffle(randomize) randomize x=x[randomize] y=y[randomize]

http://stackoverflow.com/q/49134554
tagged with: python
has comment: http://stackoverflow.com/comment/85274494
linked to: http://stackoverflow.com/q/17843596
duplicate of: http://stackoverflow.com/q/22739382
has comment: http://stackoverflow.com/comment/85274431
has comment: http://stackoverflow.com/comment/85274206
has body: I have a Python script that contains the following modules: from tkinter import * from tkinter import ttk from tkinter import filedialog When I run the code in IDLE by pressing F5 the script runs fine and starts my app. However, when I go to the command prompt and type python ScannerApp.py I get the following error: File "tkinterTest.py", line 1, in &lt;module&gt; from tkinter import * ImportError: No module named tkinter How do I get rid of this error? The ultimate goal being to make this script into a .exe. One thought is that python is not added to my environmental variables under Path, it is added as it's own variable. Could that be causing the issue? My question does not pertain to the difference between Tkinter and tkinter. My question was about why when I ran code through the command line I was getting an error. The issue happened to be that my environmental variable python was set to run python 2.7 instead of the necessary python 3.6 (which uses tkinter).
score: 0
has comment: http://stackoverflow.com/comment/85274325
answer count: 3
has comment: http://stackoverflow.com/comment/85274141
has answer: http://stackoverflow.com/a/49134866
linked to: http://stackoverflow.com/q/1093322
has answer: http://stackoverflow.com/a/49134747
has comment: http://stackoverflow.com/comment/85274217
tagged with: command-line
type: Question
tagged with: tkinter
has answer: http://stackoverflow.com/a/49135074
has comment: http://stackoverflow.com/comment/85274418
type: UnansweredQuestion
has title: Running Python file from command line does not load modules
has comment: http://stackoverflow.com/comment/85274120

http://stackoverflow.com/comment/85540977
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49268770
has text: colon missing in directive `elif days >= 3:`
score: 0

http://stackoverflow.com/comment/85269354
type: Comment
type: QuestionComment
has text: Rather than edit the question to add the solution, post it as answer! [Answering your own question is not forbidden](https://meta.stackoverflow.com/a/250208/4733879), but [officially encouraged](https://stackoverflow.com/help/self-answer). (there is even an option to answer the question directly at the [Ask a Question](https://stackoverflow.com/questions/ask) page)
comment on: http://stackoverflow.com/q/49131888
score: 1

http://stackoverflow.com/q/49201765
type: Question
score: 0
tagged with: python
has body: I'm trying to format my x-axis to show only dates. Here's my code: start = datetime(2017, 1, 1) end = datetime(2018, 3, 9) stock = web.DataReader('AAPL', 'morningstar', start, end) daily_close = stock'Close' stock['Close'].plot(figsize=(12,8)) plt.xlabel('Date') plt.xticks(rotation=30) plt.show()
tagged with: stock
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85409468
has title: formatting the x-axis in Python
has answer: http://stackoverflow.com/a/49202565
tagged with: pandas
tagged with: date
tagged with: charts

http://stackoverflow.com/a/49182612
answers question: http://stackoverflow.com/q/49182568
has comment: http://stackoverflow.com/comment/85371797
downvote count: 0
has body: The key point here is that str.split() returns a list, it doesn't affect the string itself. So y = x.split() is setting y to the list returned by the function, but x itself is unaffected.
upvote count: 5
score: 5
type: Answer

http://stackoverflow.com/q/49143513
type: UnansweredQuestion
tagged with: python
has body: My Dataframe is in this format Time AvgDiff 07:00:00 7.750782 07:01:00 9.306567 07:02:00 13.225209 07:03:00 18.346431 07:04:00 10.049761 07:05:00 18.567049 07:06:00 -4.903014 07:07:00 -10.66217 I did the following to create a synthetic date, the date is not important as my AvgDiff is the average of all dates for the particular time value my_day = datetime.date(2018, 1, 15) x_dt = [ datetime.datetime.combine(my_day, t) for t in df['Time'] ] x = x_dt y1 = df['AvgDiff'] plt.bar(x,y1, label='AvgDiff BPS', width=0.001) #bar to plot plt.legend(loc='best') plt.title('AvgDiff BPS') plt.ylabel('BPS') plt.xlabel('Time') plt.gcf().autofmt_xdate() plt.show() This shows It shows both the Date and Hours behind (in the X-Axis), However I need it to show just the Hours and Minutes. I tried FMT = '%H:%M:%S' df['Time'] = df['Time'].map(lambda x: datetime.strptime(str(x), FMT)) df['Time'] = df['Time'].map(lambda x: x.replace(day=date, month=month, year=year)) plt.gcf().autofmt_xdate() plt.show() But it produces the exact same chart, why is that so?
score: 7
tagged with: matplotlib
answer count: 1
downvote count: 0
upvote count: 7
has title: Plot Time Only in Matplotlib (Instead of DateTime)
has answer: http://stackoverflow.com/a/49143760
favorite count: 0
type: Question

pre-trained-model
tag name: pre-trained-model
tags question: http://stackoverflow.com/q/49206482
type: Tag
tags question: http://stackoverflow.com/q/49259361

http://stackoverflow.com/comment/85553935
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49144000
has text: Nice explanation but I think the simplest solution, if they just want to re-create `zip` in Py 3 with `map()` is `list(map(lambda *x: x, 'abc', [1, 2, 3]))`

http://stackoverflow.com/a/49141943
downvote count: 1
has comment: http://stackoverflow.com/comment/85289626
has body: Your code could be as compact as below (juanpa.arrivillaga suggested to return NotImplemented instead of raising an exception): def __mul__(self, other): #Vector([1, 2, 3]) * 5 =&gt; Vector([5, 10, 15]) try: return Vector([i * other for i in self.l]) except TypeError: return NotImplemented
upvote count: 10
score: 9
answers question: http://stackoverflow.com/q/49141878
type: Answer

http://stackoverflow.com/q/49201149
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49201530
possible better answer: http://stackoverflow.com/a/49201464
has answer: http://stackoverflow.com/a/49201530
has answer: http://stackoverflow.com/a/49201464
type: Question
has title: Getting Unique Values in XML Data
has body: Sort of a two part question. First here is the code I'm currently trying to work with. I'd like to stick with lxml over BS. import requests import lxml.etree from requests.auth import HTTPBasicAuth r= requests.get("https://somelinkhere/folder/?parameter=abc", auth=HTTPBasicAuth('username', 'password')) root = lxml.etree.fromstring(r.content) results = root.findall('entry') textnumbers = [r.find('updated').text for r in results] print (textnumbers) Output just gives me [] and the XML data I'm working with: <feed xmlns="http://www.w3.org/2005/Atom" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:apple-wallpapers="http://www.apple.com/ilife/wallpapers" xmlns:g-custom="http://base.google.com/cns/1.0" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:georss="http://www.georss.org/georss/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:cc="http://web.resource.org/cc/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:g-core="http://base.google.com/ns/1.0"> Feed from some link here https://somelinkhere/folder/?parameter=abc 2018-03-06T17:48:09Z <dc:creator>company.com</dc:creator> <dc:date>2018-03-06T17:48:09Z</dc:date> <opensearch:totalResults>4</opensearch:totalResults> <opensearch:startIndex>1</opensearch:startIndex> 123456789 usernameHere https://somelink/ticket/123456789 2018-02-28T13:27:33Z short_description$$$someTextHere some summary here <dc:creator>usernameHere</dc:creator> 123456799 usernameHere https://somelink/ticket/123456799 2018-03-20113:27:33Z short_description$$$someTextHere some summary here <dc:creator>usernameHere</dc:creator> First thing I'm trying to do is just get the dates from the -> field. Second part is to count the unique dates…

http://stackoverflow.com/a/49140181
answers question: http://stackoverflow.com/q/49139939
has comment: http://stackoverflow.com/comment/85286378
has body: It may be best to use two functions: one to check if a simple increment of the last position would suffice and another to perform the recursion should the previous attempt fail: vals = [[1, 0, 1], [1,1,1], [1,0,0,1]] def update_full(d): if all(i in [1, 0] for i in d): return d start = [i for i, a in enumerate(d) if a &gt; 1] return update_full([1]+[0 if i &gt; 1 else i for i in d] if not start[0] else [a+1 if i == start[0] -1 else 0 if i == start[0] else a for i, a in enumerate(d)]) def increment(d): if not d[-1]: return d[:-1]+[1] return update_full(d[:-1]+[2]) print(list(map(increment, vals))) Output: [[1, 1, 0], [1, 0, 0, 0], [1, 0, 1, 0]]
score: 0
has comment: http://stackoverflow.com/comment/85285930
type: Answer

http://stackoverflow.com/comment/85274876
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49135101
has text: Sorry, I have to update it. It may missing some sentence

http://stackoverflow.com/q/49179509
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85364438
tagged with: function
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/85364539
tagged with: class
tagged with: generator
has answer: http://stackoverflow.com/a/49179774
has answer: http://stackoverflow.com/a/49179783
answer count: 2
downvote count: 4
has body: I have tried implementing the "yield" into the code so it would return a generator, but it's returning: &lt;generator object PText.possible at 0x000001C9F4E03DB0> I essentially need to use a generator because the txt file that I am using is VERY long and creating the list takes a while and is slow, so I need to implement a generator somehow to make it so that it won't take as much time. I wrote all the code using return statements and tried plugging in yield instead but it's not working. Am I missing something? I believe there's two instances in the code where a generator is needed but I can't figure it out. This is one continuous code and I labelled where I used yield: WORD_LIST_FILE = 'English_words_by_usage_rank.txt' # this is just a file with a list of words class PText(object): keyMap = {'1': "'-", '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} wordsByPrefix = None rankByWord = None def __init__(self): self.keys = [] def add(self, keys_typed): """ Append a new key press (or a sequence of them) onto current word. keyPress -- '2', '3', ..., '9' from telephone keypad. &gt;&gt;&gt; pt= Ptext() &gt;&gt;&gt; pt.add('345') &gt;&gt;&gt; pt.keys ['3', '4', '5'] """ for key in keys_typed: if key in PText.keyMap: self.keys.append(key) def backspace(self): """Remove last key press from current word (backspace).""" if len(self.keys) &gt; 0: self.keys.pop() def match(self, word): """See if word might be what the phone user is trying to type.""" if len(word) &lt; len(self.keys): return False for i in range(len(self.keys)): letter = word[i] keystroke = self.keys[i] ok_letters = PText.keyMap[keystroke] if letter not in ok_letters: return False # if all the keys matched the corrresponding letters in word return True I used a yield in this part: def possiblePrefixes(self): """ Generate a list of all 3-char prefixes that can be gernerated from the beginning key presses. """ if len(self.keys) &lt; 3: raise ValueError("not enough ke…
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85364499
has title: Python: Classes: Need to turn my list into a generator
has comment: http://stackoverflow.com/comment/85364484

http://stackoverflow.com/q/49134404
has answer: http://stackoverflow.com/a/49134627
answer count: 4
type: AnsweredQuestion
has body: I'm working on the following code: mylist = [1,2,3,4,5,6,7,8,9,10.....] for x in range(0, len(mylist), 3): value = mylist[x:x + 3] print(value) Basically, I'm taking 3 items in mylist at a time, the code is bigger than that, but I'm doing a lot of things with them returning a value from it, then it takes the next 3 items from mylist and keep doing it till the end of this list. But now I have a problem, I need to identify each iteration, but they follow a rule: The first loop are from A, the second are from B and the third are from C. When it reaches the third, it starts over with A, so what I'm trying to do is something like this: mylist[0:3] are from A mylist[3:6] are from B mylist[6:9] are from C mylist[9:12]are from A mylist[12:15] are from B...... The initial idea was to implement a identifier the goes from A to C, and each iteration it jumps to the next identifier, but when it reaches C, it backs to A. So the output seems like this: [1,2,3] from A [4,5,6] from B [6,7,8] from C [9,10,11] from A [12,13,14] from B [15,16,17] from C [18,19,20] from A..... My bad solution: Create identifiers = [A,B,C] multiply it by the len of mylist -> identifiers = [A,B,C]*len(mylist) So the amount of A's, B's and C's are the same of mylist numbers that it needs to identify. Then inside my for loop I add a counter that adds +1 to itself and access the index of my list. mylist = [1,2,3,4,5,6,7,8,9,10.....] identifier = ['A','B','C']*len(mylist) counter = -1 for x in range(0, len(mylist), 3): value = mylist[x:x + 3] counter += 1 print(value, identifier[counter]) But its too ugly and not fast at all. Does anyone know a faster way to do it?
possible better answer: http://stackoverflow.com/a/49134655
tagged with: list
has title: Iterate though list on each for loop iteration
tagged with: for-loop
score: 1
linked to: http://stackoverflow.com/q/312443
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/509211
has comment: http://stackoverflow.com/comment/85273525
favorite count: 0
has comment: http://stackoverflow.com/comment/85273756
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49147441
has answer: http://stackoverflow.com/a/49134655
accepted answer: http://stackoverflow.com/a/49134627
tagged with: python
has answer: http://stackoverflow.com/a/49134852

http://stackoverflow.com/comment/85302481
type: AnswerComment
comment on: http://stackoverflow.com/a/49147483
has text: The problem is that for col a in both the dataframes i have the same values.
score: 0
type: Comment

http://stackoverflow.com/comment/85449587
type: Comment
type: QuestionComment
has text: @AndreyTyukin Can you elaborate a bit further on how it doesn't make sense? There will only ever be one of the variables I created (represented by the strings under #counter identifiers) present within a row. Therefore I would only expect one of them to increment in every row. Can you clarify whether or not it is correct syntax to say elif googlebot_mobile_string in row. I'll look into arrays to make things easier to read.
comment on: http://stackoverflow.com/q/49220146
score: 1

http://stackoverflow.com/a/49235850
upvote count: 0
downvote count: 2
type: AcceptedAnswer
has body: I've answered my own question, using the redirect URL, and then I've applied it the StackExchange login procedure.
score: -2
type: Answer
answers question: http://stackoverflow.com/q/49211026
accepted answer of: http://stackoverflow.com/q/49211026

http://stackoverflow.com/comment/85541152
type: AnswerComment
comment on: http://stackoverflow.com/a/49268856
has text: I understand. Now my question is just with tf.variable_scope() I can access to the variables in the train part, so why do I need `tf.train.Saver()`. I updated my question to clarify it more. @David Parks
type: Comment
score: 0

http://stackoverflow.com/comment/85282481
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49138450
type: QuestionComment
has text: @tdelaney The .bin file only contains numbers in binary, nothing else. Check the question, I added my code

http://stackoverflow.com/comment/86022428
type: Comment
score: 0
has text: No your answer worked fine Jay, the reason for Liky's answer being accept was it ran in AWS Lambda whereas yours would not. I appreciate your help but this was ultimately going to be a Lambda function.
type: AnswerComment
comment on: http://stackoverflow.com/a/49193476

http://stackoverflow.com/q/49197269
accepted answer: http://stackoverflow.com/a/51332805
tagged with: django
has answer: http://stackoverflow.com/a/51332805
type: AnsweredQuestion
has body: I'm currently rendering my Django form in the following way: &lt;form action="/student/" method="post"&gt; {% csrf_token %} {% bootstrap_form form %} &lt;input type="submit" value="Launch" class="btn btn-primary"/&gt; &lt;/form&gt; I have multiple fields of different types, with different things applied to each field, such as validators and help-text. I have two fields that I would like to add bootstrap spans to. One money field which I'd like to prepend a pound symbol to, and one percentage field which I'd like to append a percentage symbol to, I know that this is possible to do using bootstrap as follows: This input field. &lt;div class="input-group"&gt; &lt;span class="input-group-addon"&gt;$&lt;/span&gt; &lt;input type="text" class="form-control" placeholder="Price"/&gt; &lt;/div&gt; But to do this in my django template would require me to break up the form into specific fields and create field specific html. Such as the solution to This question proposes. What I'm looking for is a way to specify either in the model, or the modelform, an attribute or class which will only apply to a specific field, but will render it as above without breaking up the form. Thank you. Info: Bootstrap-4 Django-2.0.2 Python-3.6.1
has title: Django Bootstrap input-group-addon on Model Form without separating fields
score: 1
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: css
favorite count: 0
linked to: http://stackoverflow.com/q/22729217
type: Question
tagged with: twitter-bootstrap-4
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49225506
downvote count: 0
answers question: http://stackoverflow.com/q/49225435
has comment: http://stackoverflow.com/comment/85454869
type: Answer
has comment: http://stackoverflow.com/comment/85454852
score: 2
accepted answer of: http://stackoverflow.com/q/49225435
upvote count: 2
has body: Setup np.random.seed(0) df = pd.DataFrame(np.random.normal(0, 1.5, (100, 1)), columns=['data']) Use the scipy.stats.normaltest function: from scipy.stats import normaltest k2, p = normaltest(df.data) p 0.796799418250495 The function tests the null hypothesis that the data comes from a normal distribution. Higher the value of p, higher is the probability that the data is from a normal distribution. Apply a threshold (usually 0.05) above which the null hypothesis cannot be rejected.
type: AcceptedAnswer

http://stackoverflow.com/comment/85492586
type: Comment
has text: @Jean-FrançoisFabre is right, the data is a nested list (a chopped-up single list).
type: AnswerComment
comment on: http://stackoverflow.com/a/49243954
score: 0

http://stackoverflow.com/q/49242180
tagged with: keras
has body: I have the task of character recognition. There is a certain data set. When I submit an input symbol not from this dataset (or a group of characters from the dataset in one image), then the neural network selects the most similar symbol. The network should say that she does not know such a symbol in this case. May be there is any architecture for this task? I'm writing in Python 3 using Keras (Tensorlow as backend). My architecture: Layer (type) Output Shape Param # ================================================================= conv2d_1 (Conv2D) (None, 29, 29, 75) 1275 _________________________________________________________________ max_pooling2d_1 (MaxPooling2 (None, 14, 14, 75) 0 _________________________________________________________________ dropout_1 (Dropout) (None, 14, 14, 75) 0 _________________________________________________________________ conv2d_2 (Conv2D) (None, 11, 11, 100) 120100 _________________________________________________________________ max_pooling2d_2 (MaxPooling2 (None, 5, 5, 100) 0 _________________________________________________________________ dropout_2 (Dropout) (None, 5, 5, 100) 0 _________________________________________________________________ conv2d_3 (Conv2D) (None, 2, 2, 125) 200125 _________________________________________________________________ max_pooling2d_3 (MaxPooling2 (None, 1, 1, 125) 0 _________________________________________________________________ dropout_3 (Dropout) (None, 1, 1, 125) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 125) 0 _________________________________________________________________ dense_1 (Dense) (None, 500) 63000 _________________________________________________________________ dropout_4 (Dropout) (None, 500) 0 _________________________________________________________________ dense_2 (Dense) (None, 69) 34569
tagged with: ocr
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85488935
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85489097
downvote count: 0
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/85488738
tagged with: python
has title: How to teach a convolutional neural network to say "no" to unknown images?
has comment: http://stackoverflow.com/comment/85488829
score: 2
has answer: http://stackoverflow.com/a/56183532
tagged with: image-recognition
answer count: 1

http://stackoverflow.com/comment/85548516
has text: Add the 1 column later. No need to build a list with repeated items. Doing it "in one go" is inefficient.
score: 0
comment on: http://stackoverflow.com/a/49272441
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85315919
score: 1
type: Comment
has text: in one you select `info` and in the other you use `id`. Maybe there is a problem with curly brace escaping?
type: QuestionComment
comment on: http://stackoverflow.com/q/49155485

http://stackoverflow.com/a/49220828
has comment: http://stackoverflow.com/comment/85445384
has comment: http://stackoverflow.com/comment/85445461
downvote count: 0
answers question: http://stackoverflow.com/q/49220735
type: Answer
has comment: http://stackoverflow.com/comment/85452509
has comment: http://stackoverflow.com/comment/85448375
has comment: http://stackoverflow.com/comment/85445327
upvote count: 2
type: AcceptedAnswer
has body: You overcomplicated things a bit. All you need to do is get the next element and yield that twice. You do need to treat the input as an iterator, not as a sequence. Only sequences like lists have a length and can be indexed, all an iterator can do is give you the next value until it is exhausted. For a class-based iterator, that means you need to store the element to be repeated so that every other call to next() can produce that stored value, while the other calls get the next element from the input iterator: class DoubleIterator: _sentinel = object() def __init__(self, iterator): self._data = iter(iterator) self._repeat = self._sentinel def next(self): # __next__ for Python 3 if self._repeat is self._sentinel: # get next element to yield, can raise StopIteration self._repeat = next(self._data) return self._repeat # repeat last element element = self._repeat self._repeat = self._sentinel return element def __iter__(self): return self I used a unique sentinel to make sure that None values in the input iterator are supported, and I called iter() on the input iterable to make sure we can always call next() on that object. However, it is much easier to just write a generator function here, and yield each element twice: def double_iterator(iterator): for elem in iterator: yield elem yield elem You can generalise that further with a loop, but if you only ever need to double the elements, I'd just stick to the simpler double yield.
accepted answer of: http://stackoverflow.com/q/49220735
score: 2
has comment: http://stackoverflow.com/comment/85450524

http://stackoverflow.com/a/49188772
type: Answer
accepted answer of: http://stackoverflow.com/q/49183577
answers question: http://stackoverflow.com/q/49183577
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has body: Long story short, you have text data in some row in the picture column of the users table. This is possible because unlike many other SQL implementations, SQLite has dynamic typing, compared to static. The type you give to a column defines its affinity, or in other words the recommended type for data stored in that column, but it is a recommendation, not a requirement. In the end you can have text data in an INTEGER column, or such as in your case, data using the TEXT storage class in a BLOB column. An example: In [2]: class User(Base): ...: __tablename__ = 'user' ...: id = Column(Integer, primary_key=True) ...: picture = Column(LargeBinary) ...: In [3]: metadata.create_all() ... 2018-03-09 09:33:37,785 INFO sqlalchemy.engine.base.Engine CREATE TABLE user ( id INTEGER NOT NULL, picture BLOB, PRIMARY KEY (id) ) ... In [4]: engine.execute("insert into user (picture) values ('BANG!')") Out[4]: &lt;sqlalchemy.engine.result.ResultProxy at 0x7f7ad8bcc278&gt; Trying to fetch users does not end well: In [5]: session.query(User).all() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-5-f1275abaf1fd&gt; in &lt;module&gt;() ----&gt; 1 session.query(User).all() ... ~/Work/SO/lib/python3.6/site-packages/sqlalchemy/sql/sqltypes.py in process(value) 900 def process(value): 901 if value is not None: --&gt; 902 value = bytes(value) 903 return value 904 return process TypeError: string argument without an encoding You'll have to go through your user data and fix manually. Using the typeof() function you can find the offending rows: In [9]: session.query(User.id).\ ...: filter(func.typeof(User.picture) == 'text').\ ...: all() Out[9]: [(1)]
has comment: http://stackoverflow.com/comment/85394403

http://stackoverflow.com/comment/85292785
type: AnswerComment
score: 2
has text: Ah, yes. On rechecking, even instances of old-style classes claim to be instances of `object`, despite inheriting from `object` being the way you make a class new-style. Somehow, `isinstance(Foo(), object)` is true, even as `issubclass(Foo, object)` is false, because `instance` itself is a subclass of `object`. The hackery in the Py2 type system is faintly magical at times. :-)
comment on: http://stackoverflow.com/a/49143578
type: Comment

http://stackoverflow.com/comment/85424793
comment on: http://stackoverflow.com/q/49210113
has text: Can you show sample data? Thanks
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49203337
answers question: http://stackoverflow.com/q/49202578
has body: Your clean method looks ok. You can't assume that values are set in the clean method, so your checks are necessary. If a field has blank=False, then there will be an error raised in the clean_fields method. However the validation doesn't stop at that point. The full_clean method will call the clean() method first, so it's up to you to add checks before you do if self.fieldA &gt; self.fieldB: (which will raise a TypeError for None in Python 3).
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/49202578
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49279387
has comment: http://stackoverflow.com/comment/85562254
has title: Looping through a pandas Dataframe to get values from another Dataframe
score: 1
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49280070
possible better answer: http://stackoverflow.com/a/49280070
has comment: http://stackoverflow.com/comment/85562797
answer count: 2
tagged with: for-loop
downvote count: 0
upvote count: 1
has body: I have two pandas dataframes. The first dataframe contains the location of different circles over time. Example: df1 = x y time circle 1.0 235 133 1.0 2.0 236 133 1.0 3.0 245 425 1.0 4.0 215 325 2.0 5.0 287 203 4.0 6.0 394 394 5.0 The second dataframe is organised exactly like the first, but contains the locations of squares at different times. Example: df2 = x y time square 1.0 243 233 1.0 1.0 293 436 2.0 2.0 189 230 3.0 2.0 189 233 4.0 3.0 176 203 4.0 3.0 374 394 5.0 I would like to figure out how to loop through the dataframe df1 to access all the present squares in df2 at each time point, to find out which is closest. Example output: x y time closest_sq sq_x sq_y circle 1.0 235 133 1.0 1.0 243 233 2.0 236 133 1.0 1.0 243 233 3.0 245 425 1.0 1.0 243 233 4.0 215 325 2.0 1.0 243 233 5.0 287 203 4.0 2.0 189 233 6.0 394 394 5.0 3.0 374 394 I'm guessing I have to use either iterrows() or itertuples() in a for loop to get at this but I'm not sure, and scipy cdist to get the distance.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49302004
accepted answer: http://stackoverflow.com/a/49302004
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/49213524
tags question: http://stackoverflow.com/q/49226200
tags question: http://stackoverflow.com/q/49142688
tags question: http://stackoverflow.com/q/49210018
tags question: http://stackoverflow.com/q/49242094
tags question: http://stackoverflow.com/q/49213298
tags question: http://stackoverflow.com/q/49132100
tags question: http://stackoverflow.com/q/49181152
tags question: http://stackoverflow.com/q/49147403
tags question: http://stackoverflow.com/q/49218914
tags question: http://stackoverflow.com/q/49252997
tags question: http://stackoverflow.com/q/49141603
tags question: http://stackoverflow.com/q/49231909
tags question: http://stackoverflow.com/q/49203300
tags question: http://stackoverflow.com/q/49150902
tag name: json
tags question: http://stackoverflow.com/q/49188829
tags question: http://stackoverflow.com/q/49179347
tags question: http://stackoverflow.com/q/49200074
tags question: http://stackoverflow.com/q/49274137
tags question: http://stackoverflow.com/q/49183289
tags question: http://stackoverflow.com/q/49211097
tags question: http://stackoverflow.com/q/49219822
tags question: http://stackoverflow.com/q/49204735
tags question: http://stackoverflow.com/q/49249675
tags question: http://stackoverflow.com/q/49166307
tags question: http://stackoverflow.com/q/49155334
tags question: http://stackoverflow.com/q/49139188
tags question: http://stackoverflow.com/q/49213314
tags question: http://stackoverflow.com/q/49153020
tags question: http://stackoverflow.com/q/49161620
tags question: http://stackoverflow.com/q/49177723
tags question: http://stackoverflow.com/q/49211791
tags question: http://stackoverflow.com/q/49241798
tags question: http://stackoverflow.com/q/49214741
tags question: http://stackoverflow.com/q/49185974
tags question: http://stackoverflow.com/q/49155808
tags question: http://stackoverflow.com/q/49155485
tags question: http://stackoverflow.com/q/49153585
tags question: http://stackoverflow.com/q/49179656
tags question: http://stackoverflow.com/q/49169585
tags question: http://stackoverflow.com/q/49223071
tags question: http://stackoverflow.com/q/49186510
tags question: http://stackoverflow.com/q/49200983
tags question: http://stackoverflow.com/q/49158184
tags question: http://stackoverflow.com/q/49188488
tags question: http://stackoverflow.com/q/49162910
tags question: http://stackoverflow.com/q/49161614
tags question: http://stackoverflow.com/q/49233156
tags question: http://stackoverflow.com/q/49135157
tags question: http://stackoverflow.com/q/49220405
tags question: http://stackoverflow.com/q/49127155
tags question: http://stackoverflow.com/q/49151426
type: Tag
tags question: http://stackoverflow.com/q/49161691
tags question: http://stackoverflow.com/q/49228460
tags question: http://stackoverflow.com/q/49140416
tags question: http://stackoverflow.com/q/49200536
tags question: http://stackoverflow.com/q/49173204
tags question: http://stackoverflow.com/q/49209226
tags question: http://stackoverflow.com/q/49218324
tags question: http://stackoverflow.com/q/49256431
tags question: http://stackoverflow.com/q/49222380
tags question: http://stackoverflow.com/q/49135021
tags question: http://stackoverflow.com/q/49133320
tags question: http://stackoverflow.com/q/49196110
tags question: http://stackoverflow.com/q/49244391
tags question: http://stackoverflow.com/q/49187943
tags question: http://stackoverflow.com/q/49207308
tags question: http://stackoverflow.com/q/49198415
tags question: http://stackoverflow.com/q/49168349
tags question: http://stackoverflow.com/q/49232484
tags question: http://stackoverflow.com/q/49183806
tags question: http://stackoverflow.com/q/49156465
tags question: http://stackoverflow.com/q/49121985
tags question: http://stackoverflow.com/q/49266786
tags question: http://stackoverflow.com/q/49148668
tags question: http://stackoverflow.com/q/49191798
tags question: http://stackoverflow.com/q/49141730

http://stackoverflow.com/a/49242051
type: Answer
has body: In short what you are asking for is impossible. The string like &lt;dict object at 0x0000000000511948&gt; actually tell you the address of the object in the memory. but python is very very high level programming language, so you cannot access the memory (RAM) directly, even if you have the exact address (like in C), all the more you cannot modify the address. But if you want to use something like this you can simply create a new variable referencing your object instead of the string. your_dict = {'a':5} new_dict = your_dict new_dict['a'] = 17 print(your_dict['a']) $17
answers question: http://stackoverflow.com/q/49241160
score: 0

http://stackoverflow.com/comment/85450030
has text: @Franz I also just realized that your second, random example suffers from under-determination (14+1 coefficients, but only 10 observations). I added a bit.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49222585

http://stackoverflow.com/q/49230178
possible better answer: http://stackoverflow.com/a/49230655
has answer: http://stackoverflow.com/a/49230664
has body: I want to display the users that have used a value. import pandas as pd user = ['alice', 'bob', 'tim', 'alice'] val = [['a','b','c'],['a'],['c','d'],['a','d']] df = pd.DataFrame({'user': user, 'val': val}) user val 'alice' [a, b, c] 'bob' [a] 'tim' [c, d] 'alice' [a, d] Desired output: val users a [alice,bob] b [alice] c [alice,tim] d [alice,tim] Any ideas?
linked to: http://stackoverflow.com/q/24644656
downvote count: 0
tagged with: pandas
has title: pandas - groupby column with multiple values
has answer: http://stackoverflow.com/a/49230655
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/49230236
accepted answer: http://stackoverflow.com/a/49230236
tagged with: python
has answer: http://stackoverflow.com/a/49230243
answer count: 4

http://stackoverflow.com/q/49132301
has title: Summing up the total based on the random number of inputs of a column
has comment: http://stackoverflow.com/comment/85269359
favorite count: 0
tagged with: calculated-columns
has comment: http://stackoverflow.com/comment/85291994
has comment: http://stackoverflow.com/comment/85933103
has answer: http://stackoverflow.com/a/49132398
tagged with: python
has comment: http://stackoverflow.com/comment/85933530
type: Question
upvote count: 0
answer count: 2
type: UnansweredQuestion
score: -2
has answer: http://stackoverflow.com/a/49132376
downvote count: 2
has body: I need to sum up the "value" column amount for each value of col1 of the File1 and export it to an output file. I'm new in python and need to do it for thousands of records. File1 col1 col2 value 559 1 91987224 2400000000 559 0 91987224 100000000 558 0 91987224 100000000 557 2 87978332 500000000 557 1 59966218 2400000000 557 0 64064811 100000000 Desired Output: col1 Sum 559 2500000000 558 1000000000 557 3000000000 Thanks in advance. P.S : I can't use the pandas library due to permission issues.I tried the following code. Sharing it with trace backs: import csv fin = open("File1.txt","r") list_txid = {} num_tx = {} amount_tx = {} for line in fin: line = line.rstrip() f = line.split("\t") txid = f[0] amount = int(f[3]) fin.close() for txid in list_txid: num_tx[txid] += 1 amount_tx[txid] += amount print("{0}\t{1:d}\t{2:d}".format(txid, amount_tx[txid])) Traceback : Traceback (most recent call last): File "C:\Users....\sum.py", line 14, in amount = int(f[3]) IndexError: list index out of range
tagged with: data-processing

http://stackoverflow.com/a/49276102
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49275945
has comment: http://stackoverflow.com/comment/85555070
type: Answer
has comment: http://stackoverflow.com/comment/85556391
has comment: http://stackoverflow.com/comment/85554948
downvote count: 0
has body: How can I get all the to-do's whose dead line is greater that current date and time I guess you are using lte instead of gt (greater than)? get only todos whose deadline is later than now to_do_list = user.todo_set.all().filter(dead_line__gt=datetime.now(pytz.timezone('Asia/Kolkata'))) Unless you stored everything with timezone Koalkata, this can be an empty queryset. you should always use UTC. Notice that you are looking up the ToDos of certain user. Make sure the user has data. the second approach you use seems wrong. you're comparing the day, which is a number in the range 1-30, aprox https://docs.python.org/2/library/datetime.html: date.day Between 1 and the number of days in the given month of the given year

http://stackoverflow.com/comment/85394434
score: 0
type: Comment
type: AnswerComment
has text: yes , it was working by adding //doc_a = doc_a.decode('utf-8')
comment on: http://stackoverflow.com/a/49194177

http://stackoverflow.com/comment/85568871
type: Comment
comment on: http://stackoverflow.com/q/49149932
type: QuestionComment
score: 0
has text: you're most welcome. --- instead of adding it to the question, I think you should post it as an answer (with some explanations) and accept it, if it answers your original question. it is perfectly OK to post and accept your own answer.

http://stackoverflow.com/a/49158393
upvote count: 3
downvote count: 0
has body: Solution found! remove scipy (entire folder), in my computer where in C:\Users(your name)\AppData\Roaming\Python\Python36\site-packages\scipy* download scipy from https://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy re-install by pip install scipy-1.0.0-cp36-cp36m-win_amd64.whl (my os is windows-64bit) That's it!
answers question: http://stackoverflow.com/q/49155540
score: 3
type: Answer

http://stackoverflow.com/q/49228532
score: -1
favorite count: 0
tagged with: numpy
has answer: http://stackoverflow.com/a/49228967
has comment: http://stackoverflow.com/comment/85463275
upvote count: 0
tagged with: python
type: UnansweredQuestion
answer count: 1
has body: I'm trying to use numpy to curve fit (polyfit) a data set I have - it's multiple y vals for discrete x vals, i.e.: data = [[2, 3], [3, 4], [5, 4]] where the index is x, and the arrays are the y vals. I tried the average/median of each array, but I get the feeling that's ignoring a lot of useful data. TLDR: Need to fit a curve to this scatter plot:
has title: How to curve fit multiple y vals for single x value?
has comment: http://stackoverflow.com/comment/85460593
has comment: http://stackoverflow.com/comment/85460950
type: Question
has comment: http://stackoverflow.com/comment/85460711
has comment: http://stackoverflow.com/comment/85463595
tagged with: matplotlib
linked to: http://stackoverflow.com/q/6148207
downvote count: 1

http://stackoverflow.com/q/49276598
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/49277233
tagged with: python
has comment: http://stackoverflow.com/comment/85555736
tagged with: pandas
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85557084
possible better answer: http://stackoverflow.com/a/49277107
has answer: http://stackoverflow.com/a/49277233
has answer: http://stackoverflow.com/a/49277107
has title: get count of all positive values from a the last 150 rows at each row - pandas
has comment: http://stackoverflow.com/comment/85556108
has body: I have the following dataset where I have the column Date and Values for each row. It has both +ve and -ve values. I have to get a count of all positive values for the last 150 rows. IN each row. SO the 1st 150 rows will have null values. Then, the following rows will have have the count of last 150 +ve rows and similarly the -ve column will be filled with the count of negative values until that row. I tried using : def get_count_of_all_150_positive_rows_before_this_row(row): df1 = row.tail(2) df1 = df1.to_frame() print(df1.tail()) # if df1['positive_values'] &gt; 0: return (df1['positive_values'].count()) df.apply(get_count_of_all_150_positive_rows_before_this_row, axis=1) Dataset: Date values positive_values negative_values 01/01/08 0.12344 02/01/08 -0.12344 03/01/08 -0.1234433 04/01/08 -0.12344 05/01/08 -0.1234433 06/01/08 -0.12344 07/01/08 -0.1234433 08/01/08 -0.12344 09/01/08 -0.1234433 10/01/08 0.12344 11/01/08 -0.12344 12/01/08 -0.1234433 13/01/08 -0.12344 14/01/08 -0.1234433 15/01/08 -0.12344 16/01/08 -0.1234433 17/01/08 -0.12344 18/01/08 -0.1234433 19/01/08 0.12344

http://stackoverflow.com/comment/85547914
score: 0
comment on: http://stackoverflow.com/a/49272441
type: AnswerComment
type: Comment
has text: I want two columns.pos column contains some data another column contains value '1'.How to do this in one go

http://stackoverflow.com/a/49231316
type: AcceptedAnswer
downvote count: 0
upvote count: 3
score: 3
has body: The reason for this error is that you have defined the return type of udf as float while the udf is actually returning numpy.float64. pyspark treats float and numpy.float64 as different types. convert the return type to float like this. findmax = F.udf(lambda x: float(max(x)),DoubleType())
type: Answer
answers question: http://stackoverflow.com/q/49230602
accepted answer of: http://stackoverflow.com/q/49230602

http://stackoverflow.com/a/49267109
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49266877
has comment: http://stackoverflow.com/comment/85537717
has comment: http://stackoverflow.com/comment/85537971
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49266877
has body: You haven't told mod_wsgi where your project code is. Try changing to: WSGIDaemonProcess dashboard python-path=/srv/http/dashboard BTW, do not use: DocumentRoot /srv/http/dashboard If you removed the WSGIScriptAlias people could download your code. Never setup DocumentRoot such that the directory for it is where your application code exists. Leave it unset so picks up Apache default, or create an empty directory and set DocumentRoot to point at it. You also don't appear to be using a Python virtual environment. Ensure you read: http://modwsgi.readthedocs.io/en/develop/user-guides/virtual-environments.html

http://stackoverflow.com/q/49236655
tagged with: python-3.x
has answer: http://stackoverflow.com/a/78222635
has comment: http://stackoverflow.com/comment/85476825
has comment: http://stackoverflow.com/comment/85477228
has comment: http://stackoverflow.com/comment/85476738
has comment: http://stackoverflow.com/comment/85477015
type: Question
has comment: http://stackoverflow.com/comment/85476940
has comment: http://stackoverflow.com/comment/85477488
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/85477354
has title: bytes doesn't have __bytes__ method
tagged with: python
has comment: http://stackoverflow.com/comment/85477039
has comment: http://stackoverflow.com/comment/85476998
possible better answer: http://stackoverflow.com/a/78222635
has comment: http://stackoverflow.com/comment/85476721
has comment: http://stackoverflow.com/comment/85476553
has comment: http://stackoverflow.com/comment/85476713
has body: So... I have code more or less along these lines: class Foo(bytes): def __bytes__(self): return b'prefix' + super().__bytes__() But unique taste for consistency of Python core developers gets in my way, and this attempt fails miserably. Looking at methods defined on bytes class, I see no way to reproduce its default printing behavior in subclasses. Or maybe there is a way?
has comment: http://stackoverflow.com/comment/85476979
has comment: http://stackoverflow.com/comment/85477158
has comment: http://stackoverflow.com/comment/85476647
has comment: http://stackoverflow.com/comment/85480900
has comment: http://stackoverflow.com/comment/85476941
has comment: http://stackoverflow.com/comment/85477289
has comment: http://stackoverflow.com/comment/85476682
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85477054
has comment: http://stackoverflow.com/comment/85476594
answer count: 2
accepted answer: http://stackoverflow.com/a/49237034
has comment: http://stackoverflow.com/comment/85480685
downvote count: 0
has comment: http://stackoverflow.com/comment/85476846
has comment: http://stackoverflow.com/comment/85476877
has comment: http://stackoverflow.com/comment/85476680
has answer: http://stackoverflow.com/a/49237034
has comment: http://stackoverflow.com/comment/85476792
has comment: http://stackoverflow.com/comment/85477092
favorite count: 0
has comment: http://stackoverflow.com/comment/85476880
has comment: http://stackoverflow.com/comment/85477209

http://stackoverflow.com/q/49275254
tagged with: subprocess
has body: How can I run a subprocess with administrator privileges with a subprocess call? Example: subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe","Get-HotFix"]) I tried with runAS and user:Administrator and nothing.... I need this to execute the following command with cmd with administrator privileges with python. Does anyone have an idea how to do this? sc config vss start=auto I think subprocess.call((["runAS","user:Administrator","C\Windows\system32\cmd.exe","sc config vss start=auto"])) but this doesn't work.
has answer: http://stackoverflow.com/a/53168999
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
has title: Problems with subprocess call with Python
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85592036
tagged with: windows
has comment: http://stackoverflow.com/comment/85558777
has comment: http://stackoverflow.com/comment/85559582
tagged with: python
has comment: http://stackoverflow.com/comment/85559941

http://stackoverflow.com/comment/85583090
score: 0
type: AnswerComment
has text: Well, your edits tell me I have no idea what you're asking about. What do the modifications in your two examples have to do with each other?
type: Comment
comment on: http://stackoverflow.com/a/49271374

http://stackoverflow.com/q/49145992
has comment: http://stackoverflow.com/comment/85296773
score: 0
tagged with: python
has title: Python "If" statement will not return proper value when true
linked to: http://stackoverflow.com/q/20449427
type: Question
duplicate of: http://stackoverflow.com/q/20449427
answer count: 0
has body: I am sure this has been covered as I have found several similar topics but they are just not making sense to me. I have been working on this for nearly 3 hours with no progress. I am trying to ask for a user input, and then print their input just as a way for me to check my code, and then I want to check if 0 was entered. If 0 was entered, I want it to be invalid. If anything else, I want it to be valid. Heres my code #checking for variable to be a 0 def zero_chk(x): if x == 0: print ('Value cannot be 0') else: print ('valid input') prompt = 'What is your first number?\n' num1 = input(prompt) print(num1) #Input Check. Remove after debug zero_chk(num1) If I input a 0, it comes back as a valid input. I cannot understand why it will not return as invalid. Please help, my brain is just about fried on this one. I'm sure it's something very simple but for the life of me I just cant figure it out.
has comment: http://stackoverflow.com/comment/85296790
type: UnansweredQuestion

http://stackoverflow.com/comment/85516820
has text: @englealuze The FastFilter filter function I wrote can handle numbers with an arbitrary number of digits. The value of the sum really needs to be increased for it to be interesting though. There are only six numbers (5, 14, 23, 122, 1112, 11111) that satisfy the properties of the original question.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49245959

http://stackoverflow.com/q/49142748
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49155268
has answer: http://stackoverflow.com/a/49155268
tagged with: django
tagged with: python
has title: Pycharm autocomplete doesn't work in conda env
type: AnsweredQuestion
tagged with: anaconda
tagged with: pycharm
score: 1
downvote count: 0
answer count: 1
has body: I have python2/python3 env on my local machine. Python2 is installed in /usr/bin/python2.7, and python3 is installed with anaconda. I set up python3/Django2.0 project, set up isolated env for Django with anaconda. conda create --name newapp Activated new env. source activate newapp And installed dependencies with pip3 pip3 install -r requirements.txt Python, Django version: python --version: Python 3.6.4 :: Anaconda, Inc. django-admin.py version: 2.0.2 And, set python interpreter properly, as shown in the image. But, pycharm autocomplete is not working for me. Pycharm autocomplete doesn't work with pip installed packages in anaconda environment? Is this something you faced before?
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/85367804
type: QuestionComment
comment on: http://stackoverflow.com/q/49176813
has text: Yes, it works without labels both ways. But it only works with labels in the non-templated version.
type: Comment
score: 0

http://stackoverflow.com/comment/85615809
has text: OK, so in my 'connect' event at the server i am saving the request.namespace.socket.sessid into the mongoDB (my flask version is 0.10.1), then when user click button i use emit() and send to the 'room' argument the value that i pre-saved in DB? The sessid is a StringField right?
comment on: http://stackoverflow.com/a/49271227
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85430360
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49201725
has text: Well now I have the .exe file and when I run "import pytesseract", everything looks fine, I have no error message... But if I try the code, same error

http://stackoverflow.com/q/49269080
type: AnsweredQuestion
downvote count: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49275270
accepted answer: http://stackoverflow.com/a/49275270
has body: I'm using matplotlib to display a stock's price movements over time. I want to focus on the last 90 days and then predict the next 14 days. I have the last 90 days of data and my predictions, but I want to graph my predictions in a different color, so it's clear they're different. How would I do this? If I just add a second plot() call to my code, the predictions will start from the same point as my 90 days of data and be overlaid, which isn't what I want. Right now I'm doing this: df[-90:]["price"].plot() plt.show() Thanks!
tagged with: matplotlib
has title: Matplotlib: Plot Data and then Time Series Predictions
has answer: http://stackoverflow.com/a/49270188
favorite count: 0
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49270246
possible better answer: http://stackoverflow.com/a/49270188
tagged with: python
score: 2

http://stackoverflow.com/q/49143786
has title: How to use .loc to flag a new column with groupby pandas
has body: I have a df thats grouped by 'Key'. I want to flag any row within a group where the admit date matches another admit date. df = pd.DataFrame({'Key': ['10003', '10003', '10003', '10003', '10003','10003','10034', '10034'], 'Num1': [12,13,13,13,13,13,16,13], 'Num2': [121,122,122,124,125,126,127,128], 'admit': [20120506, 20120508, 20121010,20121010,20121010,20121110,20120516,20120520], 'discharge': [20120508, 20120508, 20121012,20121016,20121023,20121111,20120518,20120522]}) df['admit'] = pd.to_datetime(df['admit'], format='%Y%m%d') df['discharge'] = pd.to_datetime(df['discharge'], format='%Y%m%d') Initial df Key Num1 Num2 admit discharge 0 10003 12 121 2012-05-06 2012-05-08 1 10003 13 122 2012-05-08 2012-05-08 2 10003 13 122 2012-10-10 2012-10-12 3 10003 13 124 2012-10-10 2012-10-16 4 10003 13 125 2012-10-10 2012-10-23 5 10003 13 126 2012-11-10 2012-11-11 6 10034 16 127 2012-05-16 2012-05-18 7 10034 13 128 2012-05-20 2012-05-22 final df Key Num1 Num2 admit discharge flag 0 10003 12 121 2012-05-06 2012-05-08 0 1 10003 13 122 2012-05-08 2012-05-08 0 2 10003 13 122 2012-10-10 2012-10-12 1 3 10003 13 124 2012-10-10 2012-10-16 1 4 10003 13 125 2012-10-10 2012-10-23 1 5 10003 13 126 2012-11-10 2012-11-11 0 6 10034 16 127 2012-05-16 2012-05-18 0 7 10034 13 128 2012-05-20 2012-05-22 0 The df dimensions are 150 million by 400 so I was thinking using .loc rather than .apply might be better suited for this. But I'm open to advice. my code: df.loc[df.groupby('Key').duplicated(subset='admit'),'flag'] = 1 however, this is throwing an error that I should use apply. AttributeError: Cannot access callable attribute 'duplicated' of 'DataFrameGroupBy' objects, try using the 'apply' method
downvote count: 0
answer count: 1
score: 1
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49143814
tagged with: python
accepted answer: http://stackoverflow.com/a/49143814
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/comment/85349278
has text: I didn't mean already running spark jobs by previous submitted jobs. e.g. you may have submitted your job previously multiple times and kill them suddenly in the middle of their operations. By doing such an action the temp files of those jobs are remaining right now on your disk. On linux you can check this memory by "df -h" command and looking on tmpfs. if this is filled up then you can delete the containing folders and files in it. or restart the machine.
score: 0
comment on: http://stackoverflow.com/a/49170399
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49124570
type: AnsweredQuestion
score: 0
has title: Pandas 'key' error while creating charts through Dash
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has body: I am trying to create a scatter plot between two metrics after asking for the dimension level drill down. However, I am getting the the error: KeyError: u’brand’(one of the column names). I am new do Dash and cannot debug the error because there is nothing wrong with the column name. Following is the code: import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go import pandas as pd import sqlalchemy as sq import numpy as np from datetime import datetime engine_prd = sq.create_engine(“connection url”) df=pd.read_sql(“SELECT t1.date, t1.article_type as article_type, t1.product_gender as product_gender, t1.brand as brand, t1.master_category as master_category, t1.business_unit as business_unit, SUM(t1.revenue) as revenue, SUM(t1.sold_quantity) as units_sold, SUM(t1.total_discount) / NULLIF( SUM(t1.total_mrp),0) AS discount_perc, SUM(t1.approved_po_quantity) - SUM(t1.po_inwarded_quantity) AS pending_invard_quantity, SUM(t1.revenue) / NULLIF(SUM(t1.list_count), 0) AS rpi, SUM(t1.list_count), 100 *ratio_to_report(SUM(t1.list_count)) OVER (PARTITION BY t1.DATE) AS lc_share FROM fact_category_over_view_metrics t1 WHERE t1.DATE&gt; 20180101 and is_live_style=1 GROUP BY t1.DATE,t1.article_type,t1.product_gender,t1.brand,t1.master_category, t1.business_unit;”,engine_prd) df‘date_format’ = df‘date’.applymap(str).applymap(lambda s: “{}/{}/{}”.format(s[4:6],s[6:], s[0:4])) df‘year_month’=df‘date’.applymap(str).applymap(lambda s: “{}-{}”.format(s[0:4],s[4:6])) df[‘year_month’]=df[‘year_month’].astype(str) year_month=df[‘year_month’].unique() available_indicators = np.array([‘revenue’,‘units_sold’,‘discount_perc’,‘pending_invard_quantity’,‘rpi’,‘lc_share’]) dimension_level=np.array([‘brand’,‘product_gender’,‘article_type’,‘master_category’,‘business_unit’]) #available_indicators=list(df) app=dash.Dash() app.layout = html.Div([ html.Div([ html.Div([ dcc.Dropdown( id='dimension-level', options=[{'label': i, 'val…
tagged with: python
accepted answer: http://stackoverflow.com/a/49127317
has answer: http://stackoverflow.com/a/49127317
tagged with: plotly-dash

http://stackoverflow.com/a/49176884
has comment: http://stackoverflow.com/comment/85360918
accepted answer of: http://stackoverflow.com/q/49176643
has body: If you're not limited to regex or regex like, this is simple: has_zeros = [line for line in data['cc_flags'] if line[-1] == '0'] This list comprehension will extract out each element from data['cc_flags'] into a variable named line, and return a resulting list that is only comprised of the last character of line being a 0. (Obviously, if you need your if statement to be more specific, you can add whatever else you need into the filter condition.)
answers question: http://stackoverflow.com/q/49176643
has comment: http://stackoverflow.com/comment/85372163
has comment: http://stackoverflow.com/comment/85361561
type: Answer
has comment: http://stackoverflow.com/comment/85360881
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85459233
type: AnswerComment
score: 1
type: Comment
has text: You had the indentation wrong in the body of the function, probably from a simple pasting-into-SO problem. (And of course that problem only comes up when you're answering a question that's actually about indentation…)
comment on: http://stackoverflow.com/a/49227538

http://stackoverflow.com/comment/85543148
has text: When you say "replace the values", do you mean that you have to change them in the original dictionary (maybe because someone else has a reference to it), or just that you need to end up with a dictionary with the normalized values (and don't care whether it's the same one or a new one)?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49269874
type: QuestionComment

http://stackoverflow.com/comment/85402671
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49198786
has text: One could just wrap it into list before passing into list comprehension. In some cases explicit is better then implicit =)

http://stackoverflow.com/comment/85629459
score: 0
comment on: http://stackoverflow.com/a/49243924
type: Comment
type: AnswerComment
has text: Thanks :) Always glad to help.

http://stackoverflow.com/comment/85534624
comment on: http://stackoverflow.com/a/49262914
has text: Sorry about my poor English expression, but you had answered what I meant to ask, thank you very much
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85284317
type: AnswerComment
comment on: http://stackoverflow.com/a/49124400
has text: Oh, sorry, it should be `browser.execute_script('document.querySelector("div.k-overlay").style.display="none";')`
score: 0
type: Comment

http://stackoverflow.com/comment/85385771
comment on: http://stackoverflow.com/a/49170140
score: 0
has text: Probably you are right but that didn't worked out either, since its a zip file which essentially can have multiple Dependency within the folder, however pyspark extracts it in warehouse folder and load it for further processing. and as i said i'm executing the command ./spark-submit --py-files /home/varun/SparkPythonJob.zip /home/varun/main.py which is irrespective of the fact whether it has one file or multiple, i need all the dependencies from within the zipped file
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49160820
tagged with: python
type: Question
tagged with: python-3.x
score: 2
upvote count: 2
has body: Since Arabic starts at the right side, there will be bugs if I do the following: cnt = {} cnt["پ"] = 5 # right start char cnt["t"] = 4 # left start char import operator sorted(cnt, key=operator.itemgetter(1), reverse=True) Is there any way I could solve this problem?
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49160931
has answer: http://stackoverflow.com/a/49160931
favorite count: 0
type: AnsweredQuestion
has title: How to sort a counter with Arabic in Python
has comment: http://stackoverflow.com/comment/85327429

http://stackoverflow.com/comment/85465641
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49230527
type: Comment
has text: Yes, you are right! I had left a string in that needed to be removed. it works now! omg, I thought I would never get it to work. Thank you so much!

http://stackoverflow.com/a/49190645
has comment: http://stackoverflow.com/comment/104049605
has comment: http://stackoverflow.com/comment/120054307
upvote count: 11
has comment: http://stackoverflow.com/comment/104049900
has comment: http://stackoverflow.com/comment/115566438
has comment: http://stackoverflow.com/comment/88586299
has body: Change serializers.py as below class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) class Meta: model = User fields = ('username', 'email', 'password', 'firstname', 'last name') def create(self, validated_data): user = super().create(validated_data) user.set_password(validated_data['password']) user.save() return user def update(self, instance, validated_data): user = super().update(instance, validated_data) try: user.set_password(validated_data['password']) user.save() except KeyError: pass return user
has comment: http://stackoverflow.com/comment/119529930
downvote count: 1
has comment: http://stackoverflow.com/comment/85386615
answers question: http://stackoverflow.com/q/49189484
score: 10
type: Answer
has comment: http://stackoverflow.com/comment/85387265

http://stackoverflow.com/q/49162578
tagged with: python
has title: 'generator' object does not support item assignment
has comment: http://stackoverflow.com/comment/85330972
tagged with: python-2.7
score: 0
answer count: 1
has body: def _ext_x_y(buff_1): min_x=1000.0 min_y=1000.0 max_x=0.0 max_y=0.0 #buff_1 is a mat file tot_no_hd_img=buff_1['boxes'][0].shape[0] #gives total no of lists within a list in buff_1 .mat file hds_info_arr2d=[(0.0 for col in range(4))for rows in range(tot_no_hd_img)] #initializing 2d array for cur_hand in range(tot_no_hd_img): for i in range(4): # i represents total no of elements i a list try: idx_val_x=buff_1['boxes'][0][cur_hand][0][0][i][0][0] # last index[0] represents x coordinate float value if(idx_val_x&lt;min_x): min_x=idx_val_x hds_info_arr2d[cur_hand][0]=min_x elif(idx_val_x&gt;max_x): hds_info_arr2d[cur_hand][1]=max_x idx_val_y=buff_1['boxes'][0][cur_hand][0][0][i][0][1] #last index[1] represents y coordinate float value if(idx_val_y&lt;min_y): hds_info_arr2d[cur_hand][2]=min_y elif(idx_val_y&gt;max_y): hds_info_arr2d[cur_hand][3]=max_y except Exception as e: print e return hds_info_arr2d #this should return a 2D list of x,y coordinates image_mat_file=sc.loadmat('/home/ishaan/Codes/Datasets/hand_dataset/test_dataset/test_data/annotations/VOC2007_2.mat') x_y=_ext_x_y(image_mat_file) #why is this generating error print x_y Problem: I am trying to get a 2d list with x,y coordinates but it keeps generating error: 'generator' object does not support item assignment 'generator' object does not support item assignment 'generator' object does not support item assignment 'generator' object does not support item assignment [&lt;generator object &lt;genexpr&gt; at 0x7f2c5a5df140&gt;]
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85331056
has answer: http://stackoverflow.com/a/49162735
type: UnansweredQuestion

http://stackoverflow.com/q/49199002
type: Question
tagged with: dask
has answer: http://stackoverflow.com/a/49199361
type: UnansweredQuestion
tagged with: python
tagged with: logarithm
has body: If apply funtion to calculate logaritm at single column of large dataset using Dask, How can I do that? df_train.apply(lambda x: np.log1p(x), axis=1 , meta={'column_name':'float32'}).compute() The dataset is very large (125 Millions of rows), How can I do that?
downvote count: 0
has comment: http://stackoverflow.com/comment/85403076
answer count: 1
has title: How to apply funtion to single Column of large dataset using Dask?
score: 8
upvote count: 8
favorite count: 0

http://stackoverflow.com/q/49229610
has answer: http://stackoverflow.com/a/49229702
has answer: http://stackoverflow.com/a/76888952
tagged with: rounding
upvote count: 20
tagged with: arrays
tagged with: python
has answer: http://stackoverflow.com/a/49229831
possible better answer: http://stackoverflow.com/a/49229831
score: 19
accepted answer: http://stackoverflow.com/a/49229702
type: AnsweredQuestion
answer count: 3
downvote count: 1
has title: Difference between numpy.round and numpy.around
favorite count: 0
has body: So, I was searching for ways to round off all the numbers in a numpy array. I found 2 similar functions, numpy.round and numpy.around. Both take seemingly same arguments for a beginner like me. So what is the difference between these two in terms of: General difference Speed Accuracy Being used in practice
type: Question
tagged with: numpy

http://stackoverflow.com/q/49238332
tagged with: numpy
has answer: http://stackoverflow.com/a/71203085
downvote count: 0
has answer: http://stackoverflow.com/a/49238483
has comment: http://stackoverflow.com/comment/85480382
type: UnansweredQuestion
tagged with: arrays
favorite count: 0
has comment: http://stackoverflow.com/comment/85480516
type: Question
has answer: http://stackoverflow.com/a/49239032
has title: Numpy array: group by one column, sum another
has answer: http://stackoverflow.com/a/49239253
has answer: http://stackoverflow.com/a/49239335
answer count: 7
tagged with: python
has answer: http://stackoverflow.com/a/49238821
has body: I have an array that looks like this: array([[ 0, 1, 2], [ 1, 1, 6], [ 2, 2, 10], [ 3, 2, 14]]) I want to sum the values of the third column that have the same value in the second column, so the result is something is: array([[ 0, 1, 8], [ 1, 2, 24]]) I started coding this but I'm stuck with this sum: import numpy as np import sys inFile = sys.argv[1] with open(inFile, 'r') as t: f = np.genfromtxt(t, delimiter=None, names =["1","2","3"]) f.sort(order=["1","2"]) if value == previous.value: sum(f["3"])
has answer: http://stackoverflow.com/a/49238616
has comment: http://stackoverflow.com/comment/85860841
has comment: http://stackoverflow.com/comment/85480148
score: 8
has comment: http://stackoverflow.com/comment/85480562
upvote count: 8

http://stackoverflow.com/comment/85353795
has text: For example AEDAUD 12-01-2018 0.3448 is lower than 0.3470
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49173597
type: QuestionComment

http://stackoverflow.com/q/49246800
upvote count: 0
has title: 504 in a request to Typeform API using request library
answer count: 1
tagged with: timeout
has comment: http://stackoverflow.com/comment/85497726
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: request
score: -1
has comment: http://stackoverflow.com/comment/85497715
has answer: http://stackoverflow.com/a/49247836
has body: I am integrating the answers given by some users to a typeform poll. I am using the request library and 50% of the times I get the response and 50% of the times i get a 504 code. Does anyone have an advice/link on how to solve this?

http://stackoverflow.com/a/49141768
has body: Since the axes change their size due to the fixed aspect of the image, they are repositioned such that they are in the center of the figure, even if the subplot parameters specify a larger space. Shrink the available space You may draw the figure such the position of the axes is fixed, obtain the actual width of the axes, and set the right subplot parameter as the sum of the left and the width. import numpy as np import matplotlib.pyplot as plt for width in [7, 10, 13]: data = np.random.rand(10 * width).reshape(10, width) fig, ax = plt.subplots(figsize=(6, 4)) fig.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9) ax.imshow(data) ax.set_title(u'10 × {}'.format(width)) fig.canvas.draw() pos=ax.get_position() fig.subplots_adjust(right=0.1+pos.width) fig.savefig('10_rows_x_{}_columns.png'.format(width), facecolor='0.7', edgecolor='none') plt.show() Iteratively change position A hack would be to iteratively set the axes left position to 0.1 draw the figure, let the axes rescale itself, then again set the axes position etc. such that evenually it will end up at the x=0.1 position. import numpy as np import matplotlib.pyplot as plt for width in [7, 10, 13]: data = np.random.rand(10 * width).reshape(10, width) fig, ax = plt.subplots(figsize=(6, 4)) fig.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9) ax.imshow(data) ax.set_title(u'10 × {}'.format(width)) fig.canvas.draw() while ax.get_position().x0 &gt; 0.1: pos=ax.get_position() pos.x0=0.1 ax.set_position(pos) fig.canvas.draw() fig.savefig('10_rows_x_{}_columns.png'.format(width), facecolor='0.7', edgecolor='none') plt.show() Note that this redraws the figure ~ 50 times or so. So depending on the accuracy needed, one may opt for a slightly larger condition, like while ax.get_position().x0 &gt; 0.105: or so. Both methods result in the following pictures.
accepted answer of: http://stackoverflow.com/q/49141479
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85305140
has comment: http://stackoverflow.com/comment/85289079
type: Answer
answers question: http://stackoverflow.com/q/49141479

http://stackoverflow.com/comment/85340673
comment on: http://stackoverflow.com/a/49148433
type: AnswerComment
score: 0
has text: I agree with your personal note, indeed I need to tweak my batch generator because I'm implementing a triplet loss function where I want to compare different examples and similar examples.
type: Comment

http://stackoverflow.com/comment/85345753
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49170271
type: QuestionComment
has text: maybe this can help? https://stackoverflow.com/questions/34507744/how-to-install-beautifulsoup-into-python3-when-default-dir-is-python2-7 check pip freeze if it's really installed.

http://stackoverflow.com/comment/85414907
comment on: http://stackoverflow.com/q/49204684
type: Comment
type: QuestionComment
has text: Also, the `replace` method seems to be only incrementing `1` in the given `color` in `bag`.
score: 0

http://stackoverflow.com/q/49147128
type: Question
tagged with: nltk
score: 6
tagged with: dataframe
tagged with: python
has body: I have a DataFrame df like this: Pattern String 101 hi, how are you? 104 what are you doing? 108 Python is good to learn. I want to create ngrams for String Column. I've create unigram using split() and stack() new= df.String.str.split(expand=True).stack() However, I want to create ngrams (bi, tri, quad etc)
accepted answer: http://stackoverflow.com/a/49147340
has comment: http://stackoverflow.com/comment/85298892
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85299042
has answer: http://stackoverflow.com/a/49147340
answer count: 2
tagged with: pandas
has title: Generate N-Grams from strings with pandas
possible better answer: http://stackoverflow.com/a/49149097
upvote count: 7
downvote count: 1
has answer: http://stackoverflow.com/a/49149097
favorite count: 0

http://stackoverflow.com/q/49276214
has title: How to make separate lists out of multiple dataframe columns?
score: 2
type: AnsweredQuestion
answer count: 3
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49276576
accepted answer: http://stackoverflow.com/a/49276576
tagged with: loops
favorite count: 0
has answer: http://stackoverflow.com/a/49276735
type: Question
upvote count: 2
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49276446
has answer: http://stackoverflow.com/a/49276446
tagged with: dataframe
tagged with: python
has body: Yep, much discussed and similar questions down voted multiple times.. I still can't figure this one out.. Say I have a dataframe like this: df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) I want to end up with four separate list (a, b, c and d) with the data from each column. Logically (to me anyway) I would do: list_of_lst = df.values.T.astype(str).tolist() for column in df.columns: i = 0 while i &lt; len(df.columns) - 1: column = list_of_lst[1] i = i + 1 But assigning variable names in a loop is not doable/recommended... Any suggestions how I can get what I need?

http://stackoverflow.com/a/49193778
score: 0
has comment: http://stackoverflow.com/comment/85392321
has comment: http://stackoverflow.com/comment/85392596
has body: I think the error is this line net = tflearn.input_data(shape=[None, len(self.train_x[0])]) The second shape parameter should be 568 but is 1180. Perhaps you meant to write: net = tflearn.input_data(shape=[None, len(self.train_x[1])]) Otherwise, if your model allows, you could hard-code the length as net = tflearn.input_data(shape=[None, 568)
answers question: http://stackoverflow.com/q/49193435
type: Answer

http://stackoverflow.com/q/49264796
has title: Beautiful Soup Youtube subscribers
has body: I'm using Python with Requests and Beautiful Soup to try to return the number of subscribers for certain Youtube channels using the below code: import requests from bs4 import BeautifulSoup request = requests.get("https://www.youtube.com/channel/UCFIjVWFZ__KhtTXHDJ7vgng") content = request.content soup = BeautifulSoup(content, "html.parser") element = soup.find("yt-formatted-string", {"id": "subscriber-count", "class": "style-scope ytd-c4-tabbed-header-renderer"}) print(element) I know everything is installed correctly as it is working with scraping information from different sites but when I run this it just says "None". Any help would be much appreciated.
favorite count: 0
tagged with: beautifulsoup
score: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85533091
tagged with: web-scraping
tagged with: python
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/49264869
type: Question

http://stackoverflow.com/q/49180523
tagged with: python
has title: Find range between floats in python
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49180569
score: 0
possible better answer: http://stackoverflow.com/a/49180569
has comment: http://stackoverflow.com/comment/85367199
has comment: http://stackoverflow.com/comment/85367019
has comment: http://stackoverflow.com/comment/85366994
has answer: http://stackoverflow.com/a/49180556
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85366637
tagged with: floating-point
has answer: http://stackoverflow.com/a/49183469
favorite count: 0
has comment: http://stackoverflow.com/comment/85366851
type: Question
has comment: http://stackoverflow.com/comment/85366979
linked to: http://stackoverflow.com/q/7267226
has comment: http://stackoverflow.com/comment/85367040
accepted answer: http://stackoverflow.com/a/49180556
has body: I am trying to find if a number falls in a range, and one or both of the numbers of the range can be floats. I.E. if x in range(0.5, 3.5): pass I understand range only accepts integers So, how do I find a range between one or both floats in python. I searched around and found frange() and numpy.linspace(). Yet the former it seems is for incrementing with a float and linspace just creates a list of numbers between a range equally. All of the solutions either want floor division by 10 or have to do with incrementing. I looked here range() for floats already and not my question. Thanks.
has answer: http://stackoverflow.com/a/49180582
tagged with: range

http://stackoverflow.com/comment/85320052
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49156983
has text: Can you be any more specific about what API this is and what exactly you are trying to do?
score: 0

http://stackoverflow.com/comment/85451727
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49223770
has text: Answer: I needed to add the "x_compat=True" keyword to my calls to the pandas plotting method. I think this addresses the incompatibility issue.

http://stackoverflow.com/a/49216101
answers question: http://stackoverflow.com/q/49216088
type: Answer
has comment: http://stackoverflow.com/comment/85436244
has body: Python uses a stable sort so for ties, items will show up in the same order they occurred. You can sort on multiple keys, but that will reverse the sort for both: my_list = sorted(mylist, key=itemgetter(1, 0), reverse=True) or sort twice since you only want one of the sorts reversed: my_list = sorted(sorted(my_list, key=itemgetter(0)), key=itemgetter(1), reverse=True)
score: 0
accepted answer of: http://stackoverflow.com/q/49216088
type: AcceptedAnswer
upvote count: 1
downvote count: 1

http://stackoverflow.com/q/49201194
upvote count: 7
has comment: http://stackoverflow.com/comment/85407731
downvote count: 1
linked to: http://stackoverflow.com/q/28681782
favorite count: 0
type: Question
has body: I have a (very simplified) segment of code here for an open source project I'm working on for plotting ATE results from STDF data... def plot_everything_from_one_test(test_data, data, num_of_sites, test_tuple): plt.figure() # Title for everything plt.suptitle("Test Information Goes Here") # Find the limits low_lim = get_plot_min(data, test_tuple, num_of_sites) hi_lim = get_plot_max(data, test_tuple, num_of_sites) ###### table = function_that_returns_a_dataframe() plt.subplot(121) # HOW WOULD I ACTUALLY PUT A DATAFRAME HERE ###### # Plots the trendline plt.subplot(222) plot_full_test_trend(test_data, low_lim, hi_lim) plt.title("Trendline") # Plots the histogram plt.subplot(224) plot_full_test_hist(test_data, low_lim, hi_lim) plt.title("Histogram") plt.show() Basically, all I really want to do is in subplot section (121) to render simply a table containing the contents of an array or dataframe or whatever. This dataframe happens to be 10 columns wide and indefinitely long (in the order of magnitude of ~10s, but can be trimmed if needed). I've looked around and I know matplotlib has table(), but from what I can see it creates a new figure (unwanted) and it also tries to force a graph to render on top of it, even though I really don't want to have that render because it really would be useless. I saw this could be sort-of circumvented, but I don't know how I would manage it while preserving my subplots. Perhaps I just don't understand how matplotlib works with them. Another problem is that when I can sort-of get tables to render, they are absurdly SLOW, reaching upwards of a minute to render a 10x30-something dataframe. Also, the text renders absurdly too small and doesn't scale. Sorry if this all sounds like a cluster of problems, but I really don't know how I would deal with what should be a simple render of a table. I may just convert to a string if I really need and render it as text. Thanks in advance!
type: UnansweredQuestion
tagged with: subplot
score: 6
duplicate of: http://stackoverflow.com/q/28681782
has answer: http://stackoverflow.com/a/49201574
tagged with: dataframe
tagged with: python
has title: Python: matplotlib/pandas - Plotting a dataframe as a table in a subplot
tagged with: pandas
duplicate of: http://stackoverflow.com/q/32137396
tagged with: matplotlib
answer count: 1

keras
tags question: http://stackoverflow.com/q/49211957
tags question: http://stackoverflow.com/q/49206650
tags question: http://stackoverflow.com/q/49216299
tags question: http://stackoverflow.com/q/49124814
tags question: http://stackoverflow.com/q/49207338
tags question: http://stackoverflow.com/q/49259361
tags question: http://stackoverflow.com/q/49195189
tags question: http://stackoverflow.com/q/49275835
tags question: http://stackoverflow.com/q/49122806
tags question: http://stackoverflow.com/q/49275570
tags question: http://stackoverflow.com/q/49239478
tags question: http://stackoverflow.com/q/49231119
tags question: http://stackoverflow.com/q/49275827
tags question: http://stackoverflow.com/q/49130108
tags question: http://stackoverflow.com/q/49152221
tags question: http://stackoverflow.com/q/49192968
tags question: http://stackoverflow.com/q/49213553
tags question: http://stackoverflow.com/q/49163097
tags question: http://stackoverflow.com/q/49232895
tags question: http://stackoverflow.com/q/49204156
tags question: http://stackoverflow.com/q/49196586
tags question: http://stackoverflow.com/q/49183229
tags question: http://stackoverflow.com/q/49193589
tags question: http://stackoverflow.com/q/49135929
tags question: http://stackoverflow.com/q/49202007
tags question: http://stackoverflow.com/q/49161174
tags question: http://stackoverflow.com/q/49236382
tags question: http://stackoverflow.com/q/49162202
tags question: http://stackoverflow.com/q/49255141
tags question: http://stackoverflow.com/q/49263269
tags question: http://stackoverflow.com/q/49132151
tags question: http://stackoverflow.com/q/49225211
tags question: http://stackoverflow.com/q/49176929
tags question: http://stackoverflow.com/q/49196858
tags question: http://stackoverflow.com/q/49213607
tags question: http://stackoverflow.com/q/49216803
tags question: http://stackoverflow.com/q/49200461
tags question: http://stackoverflow.com/q/49226440
tags question: http://stackoverflow.com/q/49229234
tags question: http://stackoverflow.com/q/49239961
tags question: http://stackoverflow.com/q/49244969
tags question: http://stackoverflow.com/q/49169638
tags question: http://stackoverflow.com/q/49226447
tags question: http://stackoverflow.com/q/49129858
tags question: http://stackoverflow.com/q/49254249
tags question: http://stackoverflow.com/q/49219474
tags question: http://stackoverflow.com/q/49262623
tags question: http://stackoverflow.com/q/49263487
tags question: http://stackoverflow.com/q/49255545
tags question: http://stackoverflow.com/q/49152291
tags question: http://stackoverflow.com/q/49161208
tags question: http://stackoverflow.com/q/49225346
tags question: http://stackoverflow.com/q/49125026
tags question: http://stackoverflow.com/q/49200423
tags question: http://stackoverflow.com/q/49146529
tags question: http://stackoverflow.com/q/49239916
tags question: http://stackoverflow.com/q/49175961
tags question: http://stackoverflow.com/q/49146065
tags question: http://stackoverflow.com/q/49166240
tags question: http://stackoverflow.com/q/49245331
tags question: http://stackoverflow.com/q/49201067
tags question: http://stackoverflow.com/q/49263271
tags question: http://stackoverflow.com/q/49197916
tags question: http://stackoverflow.com/q/49202952
tags question: http://stackoverflow.com/q/49126007
tags question: http://stackoverflow.com/q/49211609
tag name: keras
tags question: http://stackoverflow.com/q/49227015
tags question: http://stackoverflow.com/q/49147811
tags question: http://stackoverflow.com/q/49254581
tags question: http://stackoverflow.com/q/49258492
tags question: http://stackoverflow.com/q/49260919
tags question: http://stackoverflow.com/q/49189496
tags question: http://stackoverflow.com/q/49142256
tags question: http://stackoverflow.com/q/49271691
tags question: http://stackoverflow.com/q/49237117
tags question: http://stackoverflow.com/q/49155113
tags question: http://stackoverflow.com/q/49159923
tags question: http://stackoverflow.com/q/49151607
tags question: http://stackoverflow.com/q/49192051

http://stackoverflow.com/comment/85519717
comment on: http://stackoverflow.com/q/49258328
type: Comment
score: 2
type: QuestionComment
has text: Not related to your question, but please don't prefix all those variables with `_`.

http://stackoverflow.com/q/49122407
has comment: http://stackoverflow.com/comment/85251418
has body: Since python does slice-by-copy, slicing strings can be very costly. I have a recursive algorithm that is operating on strings. Specifically, if a function is passed a string a, the function calls itself on a[1:] of the passed string. The hangup is that the strings are so long, the slice-by-copy mechanism is becoming a very costly way to remove the first character. Is there a way to get around this, or do I need to rewrite the algorithm entirely?
has comment: http://stackoverflow.com/comment/85250883
has comment: http://stackoverflow.com/comment/85251408
accepted answer: http://stackoverflow.com/a/49122567
has comment: http://stackoverflow.com/comment/85251103
has comment: http://stackoverflow.com/comment/85251304
answer count: 1
has comment: http://stackoverflow.com/comment/85251069
has comment: http://stackoverflow.com/comment/85250943
tagged with: string
has comment: http://stackoverflow.com/comment/85250614
has comment: http://stackoverflow.com/comment/85250360
type: AnsweredQuestion
upvote count: 3
has comment: http://stackoverflow.com/comment/85250411
score: 3
has comment: http://stackoverflow.com/comment/85250419
has comment: http://stackoverflow.com/comment/85251263
downvote count: 0
has comment: http://stackoverflow.com/comment/85250878
has comment: http://stackoverflow.com/comment/85250541
has title: Efficiently slicing a string in Python3
has answer: http://stackoverflow.com/a/49122567
linked to: http://stackoverflow.com/q/35180377
has comment: http://stackoverflow.com/comment/85252367
tagged with: python
has comment: http://stackoverflow.com/comment/85250905
has comment: http://stackoverflow.com/comment/85251144
tagged with: slice
linked to: http://stackoverflow.com/q/5722006
favorite count: 0
has comment: http://stackoverflow.com/comment/85250399
type: Question
has comment: http://stackoverflow.com/comment/85251003
has comment: http://stackoverflow.com/comment/85250706

http://stackoverflow.com/comment/85353869
comment on: http://stackoverflow.com/q/49174427
has text: Can you show what you have done so far? Then the hints can be much more specific.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49205065
type: Answer
answers question: http://stackoverflow.com/q/49204518
type: AcceptedAnswer
has body: The find() method returns the tag which is the first match. Iterating over the contents of a tag, will give you all the tags one by one. So, to get the &lt;td&gt; tags in the table, you should first find the table and store it in a variable. And then iterate over all the td tags using find_all('td'). table = soup.find("div", {"class": "sec-fundamentals"}) for row in table.find_all('td'): print(row.text.strip()) Partial Output: 32.27 34.80 $122.24B $3.41 14.14% 15.88% If you want only the first value, you can use this: table = soup.find("div", {"class": "sec-fundamentals"}) value = table.find('td').text.strip() print(value) # 32.27
score: 0
accepted answer of: http://stackoverflow.com/q/49204518

http://stackoverflow.com/q/49156297
accepted answer: http://stackoverflow.com/a/49156596
tagged with: python
tagged with: windows-task-scheduler
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85317348
score: 0
has comment: http://stackoverflow.com/comment/85317686
has answer: http://stackoverflow.com/a/49156596
tagged with: amazon-ec2
answer count: 1
type: Question
has title: Is it Possible to use schtasks on Python Code?
has body: I have set up a windows server on AWS and have set it up to run python. I'm trying to get this to run on a regular basis but I'm not sure is schtasks will work to run the python code. Could you give some advice around this please. Also, the reason I didn't set this up on a native python friendly OS is because I was having some issues installing the libraries I needed. Any help or advice is hugely appreciated.

http://stackoverflow.com/a/49131131
has body: Update list after each iteration make infinite loop list=[0] for x in list: list.append(x+1) print (x)
has comment: http://stackoverflow.com/comment/85271000
answers question: http://stackoverflow.com/q/49131012
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85266826
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85291781
comment on: http://stackoverflow.com/q/49136816
type: QuestionComment
has text: How i can close all window. I thought this is the way to close all window.
type: Comment
score: 0

http://stackoverflow.com/comment/85357468
has text: The OP **needs** to use Python. I quote : `Using python is not optional sadly.`.
comment on: http://stackoverflow.com/a/49176138
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49204401
tagged with: python
has title: Printing values for a determined number of times
has answer: http://stackoverflow.com/a/49204420
score: 0
has body: I have a table containing: table = [[2, 1],[5, 2],[6, 4],[4, 5],[1, 3],[3, 6]] and what I'm trying to do is to print the elements in the table for a set number of times, provided by the user. For example, userinput = 1 then it should just print one element from the table, left to right which is just: [2,1] the same goes for user input such as: userinput = 4 it should print: [2, 1],[5, 2],[6, 4],[4, 5] Here's what I attempted: table = [[2, 1],[5, 2],[6, 4],[4, 5],[1, 3],[3, 6]] n = len(arr) user = int(input("Enter how many times to print: ")) for i in range(n): for j in range(user): print(table[j]) but the code i wrote is printing out too many duplicate values. For example, if userinput = 1 the output i get is [2,1] [2,1] [2,1] [2,1] . . which is wrong.
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85414151
has answer: http://stackoverflow.com/a/49204422
type: UnansweredQuestion

http://stackoverflow.com/comment/85315378
type: Comment
has text: ...you know what...`curve_fit` actually passes the array, so you're absolutely right...Moreover, your code works absolutely fine here! ...putting the unknown parameters `1`, except the threshold, which I set to `1e-3`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49151557

http://stackoverflow.com/a/49216856
answers question: http://stackoverflow.com/q/49216681
has comment: http://stackoverflow.com/comment/85438522
has comment: http://stackoverflow.com/comment/85437771
has comment: http://stackoverflow.com/comment/85437855
has body: The fact that Spark creates a folder instead of a file is the expected behavior. The reason being that Spark is a distributed system, hence data is processed in partitions and each worker node will write out its data to a part file. So what you are seeing is the way it should work. It works the same way with mapreduce.
has comment: http://stackoverflow.com/comment/85437842
has comment: http://stackoverflow.com/comment/85437754
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85437827
type: Answer
has comment: http://stackoverflow.com/comment/85437843
downvote count: 0
has comment: http://stackoverflow.com/comment/85437746

string
tags question: http://stackoverflow.com/q/49219454
tags question: http://stackoverflow.com/q/49279432
tags question: http://stackoverflow.com/q/49158802
tags question: http://stackoverflow.com/q/49164667
type: Tag
tags question: http://stackoverflow.com/q/49162302
tags question: http://stackoverflow.com/q/49239875
tags question: http://stackoverflow.com/q/49186419
tags question: http://stackoverflow.com/q/49146039
tags question: http://stackoverflow.com/q/49122407
tags question: http://stackoverflow.com/q/49233874
tags question: http://stackoverflow.com/q/49248488
tags question: http://stackoverflow.com/q/49250269
tags question: http://stackoverflow.com/q/49219690
tags question: http://stackoverflow.com/q/49211981
tags question: http://stackoverflow.com/q/49156434
tags question: http://stackoverflow.com/q/49163709
tags question: http://stackoverflow.com/q/49271613
tags question: http://stackoverflow.com/q/49196910
tags question: http://stackoverflow.com/q/49122265
tags question: http://stackoverflow.com/q/49244267
tags question: http://stackoverflow.com/q/49272147
tags question: http://stackoverflow.com/q/49196429
tags question: http://stackoverflow.com/q/49165548
tags question: http://stackoverflow.com/q/49189529
tags question: http://stackoverflow.com/q/49268210
tags question: http://stackoverflow.com/q/49255775
tags question: http://stackoverflow.com/q/49269684
tags question: http://stackoverflow.com/q/49174427
tags question: http://stackoverflow.com/q/49248658
tags question: http://stackoverflow.com/q/49181480
tags question: http://stackoverflow.com/q/49216206
tags question: http://stackoverflow.com/q/49218782
tags question: http://stackoverflow.com/q/49156160
tags question: http://stackoverflow.com/q/49236731
tags question: http://stackoverflow.com/q/49183423
tags question: http://stackoverflow.com/q/49260004
tags question: http://stackoverflow.com/q/49252543
tags question: http://stackoverflow.com/q/49137639
tags question: http://stackoverflow.com/q/49168941
tags question: http://stackoverflow.com/q/49267837
tags question: http://stackoverflow.com/q/49141352
tags question: http://stackoverflow.com/q/49151010
tags question: http://stackoverflow.com/q/49256063
tags question: http://stackoverflow.com/q/49259125
tags question: http://stackoverflow.com/q/49214609
tags question: http://stackoverflow.com/q/49276977
tags question: http://stackoverflow.com/q/49164066
tags question: http://stackoverflow.com/q/49127844
tags question: http://stackoverflow.com/q/49122658
tags question: http://stackoverflow.com/q/49198261
tags question: http://stackoverflow.com/q/49172072
tags question: http://stackoverflow.com/q/49272973
tags question: http://stackoverflow.com/q/49230262
tags question: http://stackoverflow.com/q/49215738
tags question: http://stackoverflow.com/q/49192351
tags question: http://stackoverflow.com/q/49135146
tag name: string
tags question: http://stackoverflow.com/q/49211458
tags question: http://stackoverflow.com/q/49219328
tags question: http://stackoverflow.com/q/49188432
tags question: http://stackoverflow.com/q/49176643
tags question: http://stackoverflow.com/q/49271187
tags question: http://stackoverflow.com/q/49197678
tags question: http://stackoverflow.com/q/49129065
tags question: http://stackoverflow.com/q/49192542
tags question: http://stackoverflow.com/q/49265699
tags question: http://stackoverflow.com/q/49261010
tags question: http://stackoverflow.com/q/49222772
tags question: http://stackoverflow.com/q/49140120
tags question: http://stackoverflow.com/q/49131026

http://stackoverflow.com/q/49241035
has answer: http://stackoverflow.com/a/49241378
has answer: http://stackoverflow.com/a/49241117
has body: I'm trying to print a list with {} curly braces. For example: the_list = [1, 2, 3] and I want to print the list as {1, 2, 3} How can I do that? Thanks!
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49241281
tagged with: python
has answer: http://stackoverflow.com/a/49241183
linked to: http://stackoverflow.com/q/22864221
has comment: http://stackoverflow.com/comment/85485789
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85485872
has answer: http://stackoverflow.com/a/49241113
has answer: http://stackoverflow.com/a/49242599
has answer: http://stackoverflow.com/a/49241104
upvote count: 2
score: 0
type: UnansweredQuestion
downvote count: 2
answer count: 7
has title: How to print list with " { list } " brackets

http://stackoverflow.com/comment/85357583
comment on: http://stackoverflow.com/a/49174728
score: 0
type: AnswerComment
type: Comment
has text: It gives `TypeError: unorderable types: int() < str()` if any of the value in the row is 0.

http://stackoverflow.com/comment/85391303
comment on: http://stackoverflow.com/a/49192610
has text: You can split the string based on "," and can then type cast it to float.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85579930
type: Comment
has text: I just added the Python source code to the question above.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49284728

http://stackoverflow.com/q/49259361
has body: I am using VGG16 with keras for transfer learning (I have 7 classes in my new model) and as such I want to use the build-in decode_predictions method to output the predictions of my model. However, using the following code: preds = model.predict(img) decode_predictions(preds, top=3)[0] I receive the following error message: ValueError: decode_predictions expects a batch of predictions (i.e. a 2D array of shape (samples, 1000)). Found array with shape: (1, 7) Now I wonder why it expects 1000 when I only have 7 classes in my retrained model. A similar question I found here on stackoverflow (Keras: ValueError: decode_predictions expects a batch of predictions ) suggests to include 'inlcude_top=True' upon model definition to solve this problem: model = VGG16(weights='imagenet', include_top=True) I have tried this, however it is still not working - giving me the same error as before. Any hint or suggestion on how to solve this issue is highly appreciated.
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/60865373
answer count: 2
tagged with: conv-neural-network
has title: ValueError: `decode_predictions` expects a batch of predictions (i.e. a 2D array of shape (samples, 1000)). Found array with shape: (1, 7)
has answer: http://stackoverflow.com/a/60865373
downvote count: 0
tagged with: keras
favorite count: 0
type: Question
tagged with: pre-trained-model
upvote count: 5
score: 5
accepted answer: http://stackoverflow.com/a/49259606
tagged with: machine-learning
linked to: http://stackoverflow.com/q/41910617
tagged with: python
has answer: http://stackoverflow.com/a/49259606

http://stackoverflow.com/comment/85316537
has text: i tried your answer but i got this error : **builtins.TypeError: '>' not supported between instances of 'student' and 'int'**
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49155823

http://stackoverflow.com/comment/85345950
comment on: http://stackoverflow.com/q/49170390
has text: I'm guessing you do `print(df.sort_values())`. Hint: What does `df.sort_values()` return? Why does it return something?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49169357
downvote count: 0
has comment: http://stackoverflow.com/comment/85344757
has comment: http://stackoverflow.com/comment/85344495
answer count: 1
tagged with: cmd
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85345219
has answer: http://stackoverflow.com/a/49170208
tagged with: console-application
tagged with: python
tagged with: inno-setup
has body: I'm using Inno Setup to make installer for my Django webapp created using PyInstaller. Since my application needs a command (command-line console application) to run a server, I wrote a batch script to accomplish that. My problem is I don't want to show console window to end user, I want to make it hidden. Inno Setup .iss file: [Run] Filename: "{app}\cookie_dot.bat"; Description: "Start server"; \ Flags: nowait postinstall runhidden skipifsilent But it still shows a console window. For more details, my batch file: set PATH=%PATH%;C:\cookie_dot\wkhtmltopdf.exe START "" "http://localhost:88/" START "" "C:\cookie_dot\cookie_dot.exe" runserver localhost:88
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49170208
tagged with: batch-file
has comment: http://stackoverflow.com/comment/85345122
has title: Inno Setup runhidden flag is not working for console application executed from batch file

http://stackoverflow.com/comment/122190032
type: Comment
type: AnswerComment
has text: Sorry I am not familiar with Avro. You could post this as a new question and I am sure it'll get some better attention that way!
comment on: http://stackoverflow.com/a/49163584
score: 0

http://stackoverflow.com/q/49178121
has comment: http://stackoverflow.com/comment/85361858
has title: list all directories created in os.makedirs()
type: Question
downvote count: 0
upvote count: 1
linked to: http://stackoverflow.com/q/973473
has comment: http://stackoverflow.com/comment/85363580
answer count: 1
tagged with: python
favorite count: 0
has body: os.makedirs(path) creates recursively all non existing directories Is there a way to print all the newly created directories. Say if: path = '/tmp/path/to/desired/directory/a/b/c' and /tmp/path/to/desired/directory already exists then it should return: /tmp/path/to/desired/directory/a /tmp/path/to/desired/directory/a/b /tmp/path/to/desired/directory/a/b/c Input is /tmp/path/to/desired/directory/a/b/c so I am not sure till what level directories are existing, so I cannot use walk. Here in this example /tmp/path/to/desired/ may be already existing or not. I am not looking for os.walk or list subdirectories. I am looking for only new directories created intermediately while os.makedirs(). The input path is NOT a static one. It can be varied so I cannot go and check list of sub directories in it or the timestamp. I need to traverse entire filesystem then
has comment: http://stackoverflow.com/comment/85363403
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85361702
score: 1
has answer: http://stackoverflow.com/a/49182230
accepted answer: http://stackoverflow.com/a/49182230

http://stackoverflow.com/q/49213607
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/37596333
upvote count: 2
type: UnansweredQuestion
has body: I came across this answer, which explains how one can load a (multidimensional) numpy array as a constant into GPU memory and slice from it (each slice being a potential batch for training) with TensorFlow. I was wondering whether it was possible to do the same with Keras (with TensorFlow backend) and, if yes, how. I may have overlooked it, but I have not seen something like it in the documentation.
tagged with: python
has title: Load multidimensional (numpy) array into GPU memory and slice from it - with Keras?
score: 2
answer count: 0
tagged with: gpu
downvote count: 0
tagged with: memory

http://stackoverflow.com/comment/85404393
type: Comment
has text: @DChy No worries.
type: AnswerComment
comment on: http://stackoverflow.com/a/49199452
score: 0

http://stackoverflow.com/comment/85373183
type: AnswerComment
has text: jezrael there's no need to: `df.reset_index(inplace=True, drop=True)` will reindex the df, with integers. (Mind you it will invalidate any existing variables storing indices).
comment on: http://stackoverflow.com/a/49148056
type: Comment
score: 0

http://stackoverflow.com/comment/85430061
has text: I would like to keep it abstract, so it is applicable for more projects and for other people.
score: 0
comment on: http://stackoverflow.com/q/49212385
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49247650
upvote count: 4
has body: You can use: first, last = full_name.split(" ", 1)
answers question: http://stackoverflow.com/q/49247636
downvote count: 0
type: Answer
score: 4

http://stackoverflow.com/q/49123617
has answer: http://stackoverflow.com/a/49124511
has body: from nltk.stem import PorterStemmer english_stemmer = PorterStemmer() class StemmedTfidfVectorizer(TfidfVectorizer): def build_analyzer(self): analyzer = super(TfidfVectorizer, self).build_analyzer() return lambda doc: english_stemmer.stemWords(analyzer(doc)) I am new to python and I am having a problem when building my code. When I run the above code an error gets as given below: return lambda doc: english_stemmer.stemWords(analyzer(doc)) AttributeError: 'PorterStemmer' object has no attribute 'stemWords'
tagged with: python
type: Question
type: UnansweredQuestion
score: 0
answer count: 1
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85253957
has title: 'PorterStemmer' object has no attribute 'stemWords'

http://stackoverflow.com/comment/85363073
type: QuestionComment
score: 2
has text: Do you get some kind of prize for shoving the entire function into 2 lines? Otherwise, it would simplify your debugging tremendously to put one step per line, and check the result. Open your file. (Debug if needed) Read the lines. (Debug if needed) Check if the word is in the lines. (Debug if needed) If not, open the file. (Debug if needed) Write to it. (Debug if needed)
comment on: http://stackoverflow.com/q/49178434
type: Comment

http://stackoverflow.com/a/49263048
type: Answer
has comment: http://stackoverflow.com/comment/85737275
answers question: http://stackoverflow.com/q/49259055
has comment: http://stackoverflow.com/comment/85592765
type: AcceptedAnswer
has body: The error - Unsupported deadline - you're seeing is because add_timeout takes a datetime.timedelta object, whereas, you're giving it a datetime.time object. Since, you want to run the callback at a specific time, you can calculate the timedelta upto that time. import datetime # see the current time now = datetime.datetime.now() # create a datetime object for your desired time starting_time = datetime.datetime(year=2018, month=3, day=13, hour=14, minute=30) # subtract `now` from `starting_time` # to calculate timedelta td = starting_time - now main_loop.add_timeout(td, periodicCallback) If the year or month or day are same as the now time, you can also do: starting_time = datetime.datetime(year=now.year, month=now.month, day=now.day, hour=14, minute=30)
accepted answer of: http://stackoverflow.com/q/49259055
score: 0

http://stackoverflow.com/a/49181696
type: Answer
has body: Pandas DataFrame.replace() accepts regex expressions, so you can remove the characters with: df = df.replace(r"\s*\.*", "", regex = True)
accepted answer of: http://stackoverflow.com/q/49180379
answers question: http://stackoverflow.com/q/49180379
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/85257418
has text: `\xa0` is just a byte, not Unicode. ASCII encoded text is part of Unicode too.
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49126355

http://stackoverflow.com/a/49273743
score: 2
has body: You can work around it using Func() expressions. from django.db.models import Func, F class NotEqual(Func): arg_joiner = '&lt;&gt;' arity = 2 function = '' things = Thing.objects.annotate(diff=NotEqual(F('n1'), F('n2'))).order_by('diff')
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49273339
type: Answer

http://stackoverflow.com/comment/85288812
type: QuestionComment
has text: 1. chmod a+x geckodriver 2. Are you sure your firefox is 64bit?
comment on: http://stackoverflow.com/q/49141621
score: 1
type: Comment

http://stackoverflow.com/a/49289524
has comment: http://stackoverflow.com/comment/85584269
has body: Based on http://lcio.desy.de/v01-07/src/python/lcio_swig.i, it looks like they use tuples rather than arrays to represent the 3 element vectors. You should be able to do something like 'particle.setMomentum((1.0, 2.0, 3.0))' and have it work. Likewise, getMomentum would return a 3 element tuple.
has comment: http://stackoverflow.com/comment/85584283
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/49270010
upvote count: 1

http://stackoverflow.com/q/49143556
has answer: http://stackoverflow.com/a/50204764
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85292456
has comment: http://stackoverflow.com/comment/85292485
type: Question
score: 0
tagged with: bots
has body: I'm new to the discord API and I'm having trouble figuring out why my commands are not recognized. I've read through the documentation, but I'm not exactly sure where to look. Any help would be appreciated. Don't mind the hard-coded lists. I plan on changing that in the future. For now I just want to make sure that it works. import discord from discord.ext.commands import Bot from discord.ext import commands import asyncio Client = discord.Client() client = commands.Bot(command_prefix = "!") @client.event async def on_ready(): print("Bot online!") @client.command(pass_context=True) async def add_roles(member, *roles): if message.content.startswith("!role"): role_list = ["CS101", "CS492", "CS360", "CS213", "CS228", "CS401", "CS440", "CS450", "CS480", "CS410", "CS420", "CS430", "CS108", "CS111", "CS226", "CS312", "CS405", "CS413", "CS435", "CS499", "CS250", "CS475", "CS445"] entered_role = message.content[6:].upper() role = discord.utils.get(message.server.roles, name=entered_role) if role is None or role.name not in role_list: # If the role wasn't found by discord.utils.get() or is a role that we don't want to add: await client.send_message(message.channel, "Role doesn't exist.") return elif role in message.author.roles: # If they already have the role await client.send_message(message.channel, "You already have this role.") else: try: await client.add_roles(message.author, role) await client.send_message(message.channel, "Successfully added role {0}".format(role.name)) except discord.Forbidden: await client.send_message(message.channel, "I don't have perms to add roles.") @client.command(pass_context=True) async def remove_roles(member, *roles): if message.content.startswith("!unassign"): role_list = ["CS101", "CS492", "CS360", "CS213", "CS228", "CS401", "CS440", "CS450", "CS480", "CS410", "CS420", "CS430", "CS108", "CS111", "CS226", "CS312", "CS405", "CS413", "CS435", "CS499", "CS250", "CS475", "CS445"] roles_cleared = True for r in role_list: # Check every role ro…
has title: Discord bot not recognizing commands
tagged with: python
tagged with: discord

http://stackoverflow.com/q/49224066
has body: I encounter a question on the interview and it was challenging. The topic was based in Decision analysis. The question is that Let's assume we have a tuple; (15, 8, 8, 3) And we want to create all sums of all combinations one by one without repeating and summing same numbers such as this output; [(23, 8, 3), (18, 8, 8), (15, 11, 8)] Another example; (6, 5, 3, 8) And output is: [(11, 3, 8), (9, 5, 8), (14, 5, 3), (6, 8, 8), (6, 13, 3), (6, 5, 11)] Note: Order is flexible. I just really wonder the answer so if anyone is interested in this coding challenge, would help me to improve my mind structure.
tagged with: combinations
tagged with: tuples
accepted answer: http://stackoverflow.com/a/49224305
type: Question
has title: How can I create all sums of combinations from a tuple? (interview)
has answer: http://stackoverflow.com/a/49361555
has answer: http://stackoverflow.com/a/49224305
possible better answer: http://stackoverflow.com/a/49224374
downvote count: 3
has comment: http://stackoverflow.com/comment/85452044
has comment: http://stackoverflow.com/comment/85452274
tagged with: python
has comment: http://stackoverflow.com/comment/85452072
has answer: http://stackoverflow.com/a/49224374
has comment: http://stackoverflow.com/comment/85451910
has comment: http://stackoverflow.com/comment/85452278
type: AnsweredQuestion
upvote count: 3
score: 0
has comment: http://stackoverflow.com/comment/85452000
answer count: 3
favorite count: 0

http://stackoverflow.com/a/49289114
answers question: http://stackoverflow.com/q/49267730
has body: INIT_OP should contains the global variable initialization op. By default it contains an op that when run, runs these two: variables.global_variables_initializer() resources.initialize_resources(resources.shared_resources()) LOCAL_INIT_OP should contains the local variable initialization op. By default it contains an op that when run, runs these three: variables.local_variables_initializer() lookup_ops.tables_initializer() resources.initialize_resources(resources.local_resources())
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49267730
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49132419
has body: I am trying to run a python script that executes few API calls and Kafka logic but getting following error: dyld: Library not loaded: @executable_path/../.Python Tried brew update &amp;&amp; brew upgrade and also with both Python2 and Python3 but still getting same error. What could be the cause and how to fix it?
has comment: http://stackoverflow.com/comment/85271160
answer count: 2
possible better answer: http://stackoverflow.com/a/56154913
tagged with: installation
has answer: http://stackoverflow.com/a/56154913
downvote count: 0
accepted answer: http://stackoverflow.com/a/50207048
has answer: http://stackoverflow.com/a/50207048
favorite count: 0
type: Question
score: 5
has title: Python on MacOS "dyld: Library not loaded" - error
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/87350752
tagged with: macos
tagged with: shared-libraries
type: AnsweredQuestion

http://stackoverflow.com/q/49204655
has comment: http://stackoverflow.com/comment/85414706
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: qtabbar
tagged with: qtabwidget
tagged with: pyqt
has comment: http://stackoverflow.com/comment/85414650
has title: PyQt5 can't create Tabbars or Tabs
has comment: http://stackoverflow.com/comment/85414684
accepted answer: http://stackoverflow.com/a/49204748
answer count: 1
has body: I have been struggling to learn PyQt5 (and object oriented programming). In my current script I need to create a tabbed interface but can't seem to manage it. I suspect the problem is related to OOP (I am a novice). "self" seems to be the problem, and I kind of know what that means but not enough to be able to fix it. Below is my latest attempt. It seems like I am using the "wrong self", from elsewhere in the script. I want very much to understand object oriented programming - thanks in advance to anyone kind enough to help! Some of the code/errors are: code: tabbar = QTabBar() tab1 = QTabWidget() tabbar.addTab(tab1, 'tab1') error: TypeError: arguments did not match any overloaded call: addTab(self, str): argument 1 has unexpected type 'QTabWidget' addTab(self, QIcon, str): argument 1 has unexpected type 'QTabWidget' And here's the code: class App(QMainWindow): def launch(self, filepath): subprocess.run(filepath) def newLauncher(self, matrix): pass # cut for brevity def __init__(self): super(App, self).__init__() tabbar = QTabBar() tab1 = QTabWidget() index = tabbar.addTab(tab1, 'tab1') self.initUI() def initUI(self): self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_())
tagged with: pyqt5
has answer: http://stackoverflow.com/a/49204748
type: Question
has comment: http://stackoverflow.com/comment/85414717
has comment: http://stackoverflow.com/comment/85414740

http://stackoverflow.com/q/49209226
accepted answer: http://stackoverflow.com/a/49211603
upvote count: 2
has answer: http://stackoverflow.com/a/49211603
has body: I defined a class A and I am using objects of A inside other classes, containers and nested types. Example a = A() b = [a,3,'hello' c = {'hey': b, 'huy': 3} d = [a,b,c] I am interested in the json representation of d, so of course I have to specify how to behave when encountering an instance of A. For an object of class 'A' I want to get this (note that I am skipping att2, this shows that I don't what to use something like a.__dict__): { class_name = 'A', att1 = '&lt;value of att1&gt;', att3 = '&lt;value of att3&gt;' } att1 can be anything: an A instance, a default type, etc. I would like to be able to call json.dumps(d) and having the desired output, so what I trying to do is to tell the class A what to output when asked by the json serializer. I looked around and I have only found complex solutions in which a lambda or a class is passed to json.dumps() and I can't figure out why not just overriding a method called by the json serialiser, like when overriding __str__() or __repr__(). Maybe this is not possible? In such a case what could be a simple solution in my case? Note that in my real problem I have not only the class A but various custom classes nested together, so overriding the default serialiser would be the natural and easier solution. One of my attempts I am trying to follow the suggestion of line 160 of encoder.py So subclassed A from json.JSONEncoder and I declared the method def default(self,obj): return 'valid custom json representation of A' but this is not working and the exception of line 179 of the above link is raised. What is wrong with my code?
answer count: 1
downvote count: 0
tagged with: jsonserializer
favorite count: 0
type: Question
has title: Support default serialisation for a custom class in a nested type
tagged with: http://stackoverflow.com/tag/json
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/49135653
tagged with: gradient-descent
tagged with: python
has comment: http://stackoverflow.com/comment/85276426
has comment: http://stackoverflow.com/comment/85313196
type: Question
has comment: http://stackoverflow.com/comment/85340860
answer count: 0
has comment: http://stackoverflow.com/comment/85276756
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47178371
has comment: http://stackoverflow.com/comment/85277343
has body: I have the following question. I wanted to test the tf.gradients function so I develop a network with just one neuron with softmax with W = tf.Variable(tf.zeros([10, 784]), dtype=tf.float32) b = tf.Variable(tf.zeros([10,1]), dtype=tf.float32) y_ = tf.nn.softmax(tf.matmul(W,X_)+b) cost = - tf.reduce_mean(Y * tf.log(y_)+(1-Y) * tf.log(1-y_)) grad_W, grad_b = tf.gradients(xs=[W, b], ys=cost) and then I update the weights with new_W = W.assign(W - learning_rate_ * (grad_W)) new_b = b.assign(b - learning_rate_ * (grad_b)) now I wanted to compare it with the standard optimizer optimizer = tf.train.GradientDescentOptimizer(learning_rate_).minimize(cost) the funny thing is that the cost function (the same in the two cases) comes out almost the same, but not quite. I was wondering why. Are rounding errors? Or is tf.train.GradientDescentOptimizer doing something slightly different? To give you an idea here are pairs of values (with gradients and with optimizer) 0.993107 - 0.993085 0.953979 - 0.953984 Anyone can explain it? EDIT: interesting enough at the beginning (epoch = 0) the two values are the same. It seems like an error that adds to the cost function each epoch... Thanks, Umberto
has title: gradients evaluation against classical optimizer
tagged with: tensorflow
score: 0

http://stackoverflow.com/comment/85498168
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49247245
has text: Please include the actual errors in your question.
score: 0

http://stackoverflow.com/a/49275546
type: Answer
score: 0
has body: The best working solution this far seems to be normalization with median value and using .astype(np.float32) as pyAudio output is float32: samplerate, data = wavfile.read(location) input = data.T[0] # first track of audio fftData = np.fft.rfft(input[sample:], length) fftData = np.divide(fftData, np.median(fftData)) output = np.fft.irfft(fftData).astype(dtype=np.float32) If anyone has better solutions I'd like to hear. I tried with mean normalization but it still resulted in clipping audio, normalization with np.max made the whole audio too low. This normalization problem with FFT is always giving me trouble and haven't found any 100% working solutions here in SO.
answers question: http://stackoverflow.com/q/49256507

http://stackoverflow.com/a/49142588
score: 0
answers question: http://stackoverflow.com/q/49142525
type: Answer
has body: if the tr attribute in the document you are scraping is in every 3'd line then you can use this option: rows = soup.findAll('tr')[2::3]

http://stackoverflow.com/a/49184355
score: 0
has body: Not a complete answer, but perhaps a start for someone who can take it further. If you use a custom Scatter like: class MyScatter(Scatter): def on_pos(self, *args): parent = self.parent gparent = parent.parent if gparent is None: return ggparent = gparent.parent if ggparent is None: return num_children = len(ggparent.children) ggparent.remove_widget(gparent) ggparent.add_widget(gparent, num_children) Extremely ugly, and has a side effect that I don't understand (tabs appear on the right). But the MyScatter object stays behind the tabs.
has comment: http://stackoverflow.com/comment/85449398
answers question: http://stackoverflow.com/q/49178348
type: Answer

http://stackoverflow.com/q/49144470
type: Question
answer count: 2
tagged with: discord.py
has body: So here's the bit I wrote to unassign roles. If I have multiple roles assigned it will remove the first one of them it finds, but then it breaks out of the loop somehow. I'm not sure why it isn't removing all of them. Any ideas? role_list is just a list of strings. if message.content.startswith("!unassign"): roles_cleared = True for r in role_list: # Check every role role = discord.utils.get(message.server.roles, name=r) if role in message.author.roles: # If they have the role, get rid of it try: await client.remove_roles(message.author, role) except discord.Forbidden: await client.send_message(message.author, "I don't have perms to remove roles.") roles_cleared = False break if roles_cleared: await client.send_message(message.author, "Roles successfully cleared.")
possible better answer: http://stackoverflow.com/a/49144882
score: -2
upvote count: 1
tagged with: python
has title: discord bot removing one role but not the rest
has answer: http://stackoverflow.com/a/49144882
accepted answer: http://stackoverflow.com/a/49151166
has answer: http://stackoverflow.com/a/49151166
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85294768
has comment: http://stackoverflow.com/comment/85294573
tagged with: bots
has comment: http://stackoverflow.com/comment/85294513
downvote count: 3
tagged with: discord
has comment: http://stackoverflow.com/comment/85294537
favorite count: 0
has comment: http://stackoverflow.com/comment/85294592

http://stackoverflow.com/q/49184422
type: AnsweredQuestion
has title: Tkinter not showing DB number in Label
tagged with: python
accepted answer: http://stackoverflow.com/a/49184469
answer count: 1
tagged with: label
has answer: http://stackoverflow.com/a/49184469
type: Question
score: 0
has body: I need to fetch one number from a column cursor.execute('''SELECT vacas FROM animales''') cantidad1 = cursor.fetchone() Then I need this number to be shown in a Tkinter Label: cantidad = Label (ventana, textvariable=cantidad1).grid(row=1, column=3) And I have a refresh button in order to update the data. ref = Button (ventana, text="Refresh", command=update ) The problem is that the Label is always blank, even when I press button and call Update(): Here is the complete code: cantidad1 = 0 ventana = Tk() cursor = db.cursor() def update(): cursor.execute('''SELECT vacas FROM animales''') cantidad1 = cursor.fetchone() print (cantidad1[0]) #The number shown in command is right, but blank in tkinter. ref = Button (ventana, text="Refresh", command=update ) ref.grid(row=3, column=2) cantidad = Label (ventana, textvariable=cantidad1).grid(row=1, column=3) ventana.mainloop() https://i.sstatic.net/Aft0y.jpg "Screenshot tkinter blank"
tagged with: tkinter

http://stackoverflow.com/q/49244690
has answer: http://stackoverflow.com/a/49244860
has comment: http://stackoverflow.com/comment/85493509
has title: How to get this pseudocode to double a number in a while loop?
score: -4
answer count: 1
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85493469
has comment: http://stackoverflow.com/comment/85493441
has body: pseudocode numtodouble=int result=int print("") print("Enter a number you would like to double and press Enter.") input (numtodouble) &lt;class 'int'&gt;2 '2' while numtodouble&gt;0: result=numtodouble*2 print("2 X", numtodouble, "=", result) print("") print("Enter a number you would like to double and press Enter.") input(numtodouble) break print("OK, you entered a value &lt;=0, ending execution.") Does anyone know where I went wrong with my code? I've been struggling with this for hours.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85493435
has comment: http://stackoverflow.com/comment/85493454
downvote count: 5
tagged with: python

http://stackoverflow.com/a/49180235
has body: IIUC You can using pivot_table with reset_index df.pivot_table(columns='Time_measures', values='Time_in_sec',index=['Date','Project','Processes'],fill_value='').reset_index() Out[98]: Time_measures Date Project Processes \ 0 1/23/2017 ICC Acct Transfer.dc 1 1/23/2017 ICC eBanking Logon.no 2 1/24/2017 PCB Transaction .com 3 7/6/2017 FE eBanking .aspx 4 9/2/2017 PCB eBanking Frontpage.fi Time_measures Average Response Time Call per hour Number of calls 0 28 1 0 2 0 3 157 4 227
answers question: http://stackoverflow.com/q/49180178
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85366641
has comment: http://stackoverflow.com/comment/85366220
accepted answer of: http://stackoverflow.com/q/49180178
score: 1
type: Answer

http://stackoverflow.com/a/49139545
has comment: http://stackoverflow.com/comment/85284871
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85284908
has comment: http://stackoverflow.com/comment/85284827
type: Answer
accepted answer of: http://stackoverflow.com/q/49139232
score: 2
upvote count: 2
downvote count: 0
has body: In iptables rules, you have reject rules befor accept rules for your script. They are never used because they are checked in the same order iptables list them. So kernel finds matching reject rule first. You have to move reject rules to the end of table, or move yours to the top (insert them using iptables -I instead of appending by iptables -A). Or remove reject rules, and set default policy for input chain to reject or drop). Also please keep in mind, that there are always some rules (at least default policies) for all tables on kernel level. So by disabling some system deamon, you not necessarily make your host wide open to all connections. Always refer to iptables --list if unsure. Oh, and there is this older solution for accepting/rejecting TCP connections based on content of files /etc/hosts.allow and /etc/hosts.deny. Please check if connections to 443 are allowed in one and not denied in the other.
answers question: http://stackoverflow.com/q/49139232

http://stackoverflow.com/comment/85381439
type: Comment
comment on: http://stackoverflow.com/q/49181097
type: QuestionComment
has text: Note that `ctypes.POINTER(ctypes.c_char_p)` is a **double** pointer (equivalent of `char **`). Is that what you're after?
score: 0

http://stackoverflow.com/q/49205782
tagged with: chrome-web-driver
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/54459701
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49205867
answer count: 3
score: 7
downvote count: 0
tagged with: selenium
has title: selenium.common.exceptions.WebDriverException: Message: chrome not reachable error while using find_element_by_id Selenium with ChromeDriver
upvote count: 7
favorite count: 0
accepted answer: http://stackoverflow.com/a/49207166
type: Question
has answer: http://stackoverflow.com/a/49207166
has answer: http://stackoverflow.com/a/73378755
has body: Here is the html code: &lt; input class="form-control input-lg input auto-complete" id="ymMsgInput" type="text" placeholder="Type your message ..." autocomplete="off" &gt; Code: i = s.find_element_by_id("ymMsgInput"); Python - Selenium Chrome webdriver error: Traceback (most recent call last): File "&lt;pyshell#19&gt;", line 1, in &lt;module&gt; i = s.find_element_by_id("ymMsgInput"); File "C:\Users\vishn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 351, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "C:\Users\vishn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 955, in find_element 'value': value})['value'] File "C:\Users\vishn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute self.error_handler.check_response(response) File "C:\Users\vishn\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: chrome not reachable (Session info: chrome=65.0.3325.146) (Driver info: chromedriver=2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91),platform=Windows NT 10.0.16299 x86_64)
tagged with: python
possible better answer: http://stackoverflow.com/a/49205867

http://stackoverflow.com/comment/85251616
type: QuestionComment
score: 0
has text: Got it, Kyle. But in pycharm, I can not run it with clicking start button. It says no module named xlwt.T-T
comment on: http://stackoverflow.com/q/49122916
type: Comment

http://stackoverflow.com/comment/85521457
type: Comment
score: 1
type: QuestionComment
has text: https://stackoverflow.com/help/mcve
comment on: http://stackoverflow.com/q/49259073

http://stackoverflow.com/a/49555604
type: Answer
has body: For your 1st doubt: Why is N a generator? The list function is being applied to the map(int, input().split()) statement and indeed that is a list being returned, however, the outermost pair of parentheses and for _ in range(K) means that a generator object is being returned to N and not the list. If you want to see the contents of N while debugging, change the outermost parentheses to square brackets [ and ] and add a print(N) statement after that as such: # Debug &amp; view contents of N like this: N = [ list(map(int, input().split()))[1:] for _ in range(K) ] print(N) For your 2nd doubt: How does the value of the variable results come about? Just so everyone who's reading this answer is clear, in the below example, I'll let: N = [[1, 2], [3, 4], [5, 6]] product(*N) will return an iterator for a list of tuples containing the cartesian product of each of the sublists of N, e.g. product(*N) returns the tuples (1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), ..., (2, 4, 6). You can verify this by doing print([x for x in product(*N)]) or if you iterate through N in a for loop and print out each value as such: N = [[1, 2], [3, 4], [5, 6]] # You can verify the contents of a generator like this: print([item for item in product(*N)]) # Or like this: for item in product(*N): print(item) Breaking down results = map(lambda x: sum(i**2 for i in x)%M, product(*N)): In (i**2 for i in x), x refers to one of the tuples, e.g. (1, 3, 5) in product(*N), and returns a generator that contains the values (1, 9, 25). So it's basically squaring every integer in the tuple (1, 3, 5) and returning a tuple of their squares. sum(i**2 for i in x) sums every integer in the tuple x to give you 1 + 9 + 25 = 35. After that, the resultant sum, 35, is applied to the modulus operation % M. Finally, results would contain the generator with all of the resultant modulus sums for every tuple. Similarly, you can verify the content of results by doing print([x for x in results]) or if you iterate results in a for…
score: 0
answers question: http://stackoverflow.com/q/49122033

http://stackoverflow.com/q/49197330
answer count: 1
tagged with: acrcloud
type: Question
tagged with: raspberry-pi
type: UnansweredQuestion
tagged with: python
has title: ImportError Running Test.py
score: 0
has body: I recently downloaded ACRCloud and began trying to use it to recognize music on the Raspberry Pi. So, the first thing I did was run the setup.py script with the following command: sudo python setup.py install Everything runs fine and all the necessary files are created. Next thing I did was enter my API information into the test.py file. It currently looks like this with the information entered: #!/usr/bin/env python #-*- coding:utf-8 -*- ''' &gt;&gt;&gt; python test.py test.mp3 ''' import os, sys from acrcloud.recognizer import ACRCloudRecognizer from acrcloud.recognizer import ACRCloudRecognizeType if __name__ == '__main__': config = { 'host':'--------------', 'access_key':'--------------', 'access_secret':'--------------', 'recognize_type': ACRCloudRecognizeType.ACR_OPT_REC_AUDIO, # you can replace it with [ACR_OPT_REC_AUDIO,ACR_OPT_REC_HUMMING,ACR_OPT_REC_BOTH], The SDK decide which type fingerprint to create accordings to "recognize_type". 'debug':False, 'timeout':10 # seconds } '''This module can recognize ACRCloud by most of audio/video file. Audio: mp3, wav, m4a, flac, aac, amr, ape, ogg ... Video: mp4, mkv, wmv, flv, ts, avi ...''' re = ACRCloudRecognizer(config) #recognize by file path, and skip 0 seconds from from the beginning of sys.argv[1]. print re.recognize_by_file(sys.argv[1], 0, 10) buf = open(sys.argv[1], 'rb').read() #recognize by file_audio_buffer that read from file path, and skip 0 seconds from from the beginning of sys.argv[1]. print re.recognize_by_filebuffer(buf, 0, 10 Nothing other than the host, access key, or access secret have been touched, and I removed them here. Next, I try running the following command: sudo python test.py test.mp3 This should return the song, as my directory contains both files. ls -la returns the following: drwxrwxrwx 6 pi pi 4096 Mar 9 15:26 . drwxr-xr-x 3 pi pi 4096 Feb 15 08:36 .. drwxrwxrwx 2 pi pi 4096 Mar 9 01:08 acrcloud drwxr-xr-x 4 root root 4096 Mar 9 00:46 build drwxr-xr-x 2 root root 4096 Mar 9 00:46 d…
has answer: http://stackoverflow.com/a/49216081

http://stackoverflow.com/comment/126658712
score: 0
type: Comment
type: AnswerComment
has text: Sorry, I didn't see this comment until recently :( It's possible that the site listing the available packages gets out-of-sync. It may not update on packages-removed, only on packages added. By the time you're reading this, there have been a few iterations on updated python3 by a better maintainer, so I hope everything is fine now.
comment on: http://stackoverflow.com/a/54259475

http://stackoverflow.com/comment/85458053
type: QuestionComment
comment on: http://stackoverflow.com/q/49222748
score: 0
type: Comment
has text: No, it doesn't look like it has any way to add icons or images. This can be done using `PySide`

http://stackoverflow.com/comment/85539084
type: AnswerComment
comment on: http://stackoverflow.com/a/49249129
score: 0
type: Comment
has text: @orbeckst thank you. I am now a bit confused. Can you please add an answer how to find the moment of inertia and principal axes and eigenvalues? Please note in the issue that we need to use `np.matmul` or `np.dot` and not the `*` operator in issue [#18](https://github.com/MDAnalysis/MDAnalysisTutorial/issues/18).

http://stackoverflow.com/comment/85377119
score: 1
has text: Also FYI `if blah: return True else: return False` is equivalent to simply `return blah`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49185754

http://stackoverflow.com/comment/85443334
type: Comment
type: QuestionComment
score: 0
has text: Can you please clarify what kind of tables? A SQL database table? A python table coming from a module (e.g. pandas)? A self written table class?
comment on: http://stackoverflow.com/q/49219630

http://stackoverflow.com/q/49237041
type: Question
answer count: 1
has title: How to get access to SQLAlchemy automap?
has answer: http://stackoverflow.com/a/49250626
accepted answer: http://stackoverflow.com/a/49250626
type: AnsweredQuestion
score: 0
tagged with: python
tagged with: sqlalchemy
has body: I am using SQLAlchemy automap. When I described structure Declarative I have got backref property: The above configuration establishes a collection of Address objects on User called User.addresses. But now with automap my code is like next: engine = create_engine('sqlite:///sql_test.db', echo=True) Session = sessionmaker(bind=engine) sess = Session() Base = automap_base() Base.prepare(engine, reflect=True) User = Base.classes.Users addresses = Base.classes.addresses answer = sess.query(User).filter(User.id==1).first() print('type:', type(answer)) # will print: class User But how I can get access to addresses here? I tried: answer.addresses and so one, but it is not working. Users: CREATE TABLE "Users"( "id" Integer PRIMARY KEY, "name" Text, CONSTRAINT "unique_id" UNIQUE ( "id" ) ) Addresses: CREATE TABLE "addresses"( "id" Integer PRIMARY KEY, "email" Text, "user_id" Integer, CONSTRAINT "lnk_Users_addresses" FOREIGN KEY ( "user_id" ) REFERENCES "Users"( "id" ), CONSTRAINT "unique_id" UNIQUE ( "id" ) )

http://stackoverflow.com/a/49196132
type: Answer
has comment: http://stackoverflow.com/comment/85397944
score: 0
answers question: http://stackoverflow.com/q/49195912
has comment: http://stackoverflow.com/comment/85397375
has comment: http://stackoverflow.com/comment/85397700
has body: Open your csv file to read. Read line by line, append user to final_list if his ID is not already found in there. If it is found, check the year of your current_data, with your final_list data. If the current data has a more recent entry, just change the date of your user in final_list, along with the color associated with it. Only then, when your final_list is done, will you write a new csv file. If you want this task to be faster, you want to... Optimize your loops. Use standard python functions and/or libraries coded in C. If this is still not optimized enough... learn C. Reading a csv file in C, parsing it with a separator, and iterating through an array is not hard, even in C.

http://stackoverflow.com/a/49300458
upvote count: 3
has body: I encountered this problem a few month ago. The m2m relationships are not updated inside the model save method, even if super() is called before using those relationships. The only workaround I've found is to write a separate function that deals with m2m relationships, and call it from the save method of the form: def save(self, *args, **kwargs): instance = super().save(*args, **kwargs) instance.update_m2m() return instance In your case, this function is the nearly the same as your model save method: def update_m2m(self): if self.Servers != self._old_Servers: self.Status = 'C' self._old_Servers = self.Servers self.save()
answers question: http://stackoverflow.com/q/49254839
downvote count: 0
type: Answer
score: 3

http://stackoverflow.com/comment/85424726
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49210018
has text: your json is valid. You have to just print in a diff way. try the following: >>> import json >>> json.dumps(result)
type: Comment

http://stackoverflow.com/a/49164978
upvote count: 1
has body: You should be able to use the groupby and nunique() functions to obtain a distinct count of patients that had each diagnosis. This should give you the result you need: df'pid', 'code'.groupby(['code']).nunique()
score: 1
answers question: http://stackoverflow.com/q/49164819
type: Answer
downvote count: 0

http://stackoverflow.com/a/49282424
answers question: http://stackoverflow.com/q/49266771
has body: Adjusted code and seems to work now. Correct code is below for anyone who needs. import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd import dash_table_experiments as dt # Load in data set sheet_to_df_map = pd.ExcelFile('output.xlsx') dropdown_options = pd.read_excel('output.xlsx', sheet_name=None) # Create the dash app app = dash.Dash() # Define the layout for the drop down menu app.layout = html.Div([ html.H2("Select Sheet Number"), html.Div([dcc.Dropdown(id="field_dropdown", options=[{ 'label': i, 'value': i } for i in dropdown_options], value='Sheet3')], style={'width': '25%', 'display': 'inline-block'}), dt.DataTable(rows=[{}], row_selectable=True, filterable=True, sortable=True, selected_row_indices=[], id='datatable') ]) @app.callback( dash.dependencies.Output('datatable', 'rows'), [dash.dependencies.Input('field_dropdown', 'value')]) def update_datatable(user_selection): if user_selection == 'Sheet1': return sheet_to_df_map.parse(0).to_dict('records') elif user_selection == 'Sheet2': return sheet_to_df_map.parse(1).to_dict('records') else: return sheet_to_df_map.parse(2).to_dict('records') if __name__ == '__main__': app.run_server()code here
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/94538933
score: 2
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49266771
upvote count: 2

http://stackoverflow.com/comment/85395602
type: Comment
has text: You can iterate over tables in the document. See this thread for code examples: https://github.com/python-openxml/python-docx/issues/13#issuecomment-35335835
type: QuestionComment
comment on: http://stackoverflow.com/q/49178914
score: 0

http://stackoverflow.com/q/49240364
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/85484392
tagged with: django-views
answer count: 0
score: 1
downvote count: 0
upvote count: 1
has title: About pythonType
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85486877
has body: I want ask you about Type of value in Django 2.0.2, I have code in file with name (models.py) class AutherDetalis(models.Model): author = models.ForeignKey(Author,on_delete=models.PROTECT) post = models.ForeignKey(Post,on_delete=models.PROTECT) def __str__(self): return "{} - {}".format(self.author,self.post) in file with name (views.py) class AuthorView(DetailView): model = AutherDetalis template_name = "AuthorView.html" context_object_name = "authorview" slug_field = "author" in file with name (urls.py) path('AuthorView/&lt;slug&gt;/',AuthorView.as_view(),name="AuthorView"), And in file (Authorview.html) {% extends 'base.html' %} {% block content %} &lt;div align="center"&gt; {{ authorview.author.name }} &lt;/div&gt; {% endblock %} the ValueError comes and he says : invalid literal for int() with base 10: '&lt;name_of_author&gt;' I want ask about the value of &lt;name_of_author&gt; What is? and how I can solve the problem?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85486460
has comment: http://stackoverflow.com/comment/85485783
tagged with: django

http://stackoverflow.com/comment/85493199
has text: I checked it against the old run and it is correct ヽ(´▽`)/
comment on: http://stackoverflow.com/a/49243745
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85300287
type: AnswerComment
has text: no, it still throws the same error . i don't know where i going wrong .
comment on: http://stackoverflow.com/a/49146756
type: Comment
score: 0

http://stackoverflow.com/a/49159476
has comment: http://stackoverflow.com/comment/85348735
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/85348705
has body: You can define custom field, use to_representation method to customize output format: class EndPointField(serializers.PrimaryKeyRelatedField): def to_representation(self, value): serializer = EndPointSerializer(value) return serializer.data def get_queryset(self): return models.EndPoint.objects.all() And use it in DownloadSerializer for endpoint field: class DownloadSerializer(serializers.ModelSerializer): endpoint = EndPointField() class Meta: model = Download fields = ('id', 'endpoint') UPD Based on Kilian Perdomo Curbelo feedback EndPointField's to_representation value should be replaced with endpoint instance: def to_representation(self, value): endpoint = EndPoint.objects.get(pk=value.pk) serializer = EndPointSerializer(endpoint) return serializer.data
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85349887
upvote count: 5
answers question: http://stackoverflow.com/q/49159247
has comment: http://stackoverflow.com/comment/85348580
type: Answer
has comment: http://stackoverflow.com/comment/85349365
accepted answer of: http://stackoverflow.com/q/49159247

http://stackoverflow.com/comment/85453506
score: 0
comment on: http://stackoverflow.com/q/49224925
type: Comment
type: QuestionComment
has text: If you're worried about typos so much, make it a habit to use python3.6's typing checks inside an IDE.

http://stackoverflow.com/comment/85588116
type: Comment
score: 0
type: AnswerComment
has text: when used the step mentioned= local('fab -f fabfile.py function_name:\'{}\''.format(json.dumps(dictionary))), then it is not able to find the mentioned function and throws error saying use available functions.
comment on: http://stackoverflow.com/a/49218938

http://stackoverflow.com/comment/85415477
has text: https://docs.python.org/3/library/functions.html#enumerate
type: Comment
comment on: http://stackoverflow.com/q/49205092
score: 2
type: QuestionComment

http://stackoverflow.com/comment/85282320
score: 0
has text: @Genetical - you said a binary file. If its .bin, put that in the question. How are we supposed to know?
type: Comment
comment on: http://stackoverflow.com/q/49138450
type: QuestionComment

http://stackoverflow.com/comment/85420487
score: 0
type: Comment
has text: @DustinMichels - Can you add timings to question?
type: AnswerComment
comment on: http://stackoverflow.com/a/49207772

http://stackoverflow.com/comment/85556060
has text: using for loop may not be a good choice as it was mentioned that data is huge.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49276840

http://stackoverflow.com/comment/85433320
type: AnswerComment
comment on: http://stackoverflow.com/a/49214402
score: 0
type: Comment
has text: @seam Thank you so much! I wish I could up vote this twice!

http://stackoverflow.com/a/49184744
has comment: http://stackoverflow.com/comment/85375366
has body: I am not sure if I solved the issue (because I do not get the same accuracy as mentioned in the README section) but here's what I did: added if p.grad is not None: here: def clip_gradient(model, clip): """Computes a gradient clipping coefficient based on gradient norm.""" totalnorm = 0 for p in model.parameters(): if p.grad is not None: modulenorm = p.grad.data.norm() totalnorm += modulenorm ** 2 totalnorm = math.sqrt(totalnorm) return min(1, clip / (totalnorm + 1e-6)) and added if p.grad is not None: in: def train_batch(self, i): ''' Trains a regular RNN model ''' sentence, targets, actual_batch = self.make_batch(self.train_set, i) if(sentence is None): return None hidden = self.mdl.init_hidden(actual_batch) hidden = repackage_hidden(hidden) self.mdl.zero_grad() output, hidden = self.mdl(sentence, hidden) loss = self.criterion(output, targets) loss.backward() if(self.args.clip_norm&gt;0): coeff = clip_gradient(self.mdl, self.args.clip_norm) for p in self.mdl.parameters(): if p.grad is not None: p.grad.mul_(coeff) self.optimizer.step() return loss.data[0] The accuracies I get are as follows: for RNN model: python train.py --batch-size 20 --rnn_type GRU --cuda --gpu 1 --lr 0.0001 --mdl RNN --clip_norm 1 --opt Adam [Epoch 50] Train Loss=0.953654762131 T=0.51s Test loss=0.90144520998 Output Distribution={2: 1120} Accuracy=0.65 for TD-RNN model: python train.py --batch-size 20 --rnn_type GRU --cuda --gpu 1 --lr 0.0001 --mdl TD-RNN --clip_norm 1 --opt Adam [Epoch 50] Train Loss=0.64427837713 T=0.99s Test loss=0.828059911728 Output Distribution={0: 165, 1: 138, 2: 817} Accuracy=0.719642857143 However the accuracy mentioned in github readme for RNN is: [Epoch 50] Train Loss=0.680990989366 Test loss=0.810974478722 Output Distribution={0: 158, 1: 158, 2: 804} Accuracy=0.733035714286 What is the possible cause for such difference is accuracy? How would you fix the issue with no drop in accuracy? Not sure if my fix is causing the drop in accuracy. I used the fix from this link…
has comment: http://stackoverflow.com/comment/85375334
score: 0
has comment: http://stackoverflow.com/comment/85375411
answers question: http://stackoverflow.com/q/49184241
has comment: http://stackoverflow.com/comment/85375378
type: Answer

http://stackoverflow.com/comment/85365637
comment on: http://stackoverflow.com/q/49180006
score: 0
has text: Why is this tagged both python-3.x and python-2.7? Do you need code that runs in both?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85483442
type: Comment
has text: `Cython.Inline`?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49239036

http://stackoverflow.com/a/49125858
answers question: http://stackoverflow.com/q/49121841
type: Answer
score: 0
has body: You could try specifying redirect url in your settings.py file. Just include LOGIN_REDIRECT_URL = /mainapp/accounts/profile/ in that file and it should work. LOGOUT_REDIRECT_URL is also something you can list in your settings file to specify where to redirect after user logout.

http://stackoverflow.com/q/49138431
has comment: http://stackoverflow.com/comment/85282176
has comment: http://stackoverflow.com/comment/85283826
has comment: http://stackoverflow.com/comment/85282674
type: Question
has comment: http://stackoverflow.com/comment/85282784
has title: Receiving an Error Message in this "Guess the Word" Game?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85282050
has comment: http://stackoverflow.com/comment/85282141
score: 0
answer count: 0
has body: I am creating a "guess the word" game in python for my intro to programming class. The word is shown with dashes (-) in place of the vowels. The user is supposed to guess the word based off of a provided hint (the words/hints go together as parallel tuples). The user gets 5 guesses and if the word is guessed correctly, a certain amount of points are awarded. The user can then either choose to keep playing &amp; accumulate points, or quit. The code was working until I added the coding to ask the user if he/she would like to keep playing. What is it that I need to fix in order for it to work? #Clear Screen print("\n"*50) import random #Variables keep_playing = "y" round_score = 0 overall_score = 0 new_words = "" vowels = "AaEeIiOoUuYy" #Parallel tuples while keep_playing.lower() == "y": guesswords = ("Japan","France","Mexico","Italy","Australia") guesshints = ("Sushi comes from here","Croissants come from here","Tacos come from here","Pizza comes from here","Vegemite comes from here") #Random index = random.randrange(len(guesswords)) guesses = 5 #Replacing vowels for letter in guesswords[index]: if letter not in vowels: new_words += letter else: new_words += "-" #Output print(new_words.center(80, " ")) print("Hint:",guesshints[index]) while guesses &gt; 0: input_string = "\nGuess the word! You have " + str(guesses) + " guesses remaining: " user_guess = input(input_string) if user_guess.upper() == guesswords[index].upper(): print("YOU WIN") round_score = (guesses * 2) overall_score += round_score print("Your score for this round is ",round_score) break guesses -= 1 print("Your overall score is ",overall_score) keep_playing = input("Would you like to keep playing? (y/n)") print("GAME OVER")
has comment: http://stackoverflow.com/comment/85282960

http://stackoverflow.com/comment/85251436
comment on: http://stackoverflow.com/q/49122806
type: QuestionComment
score: 0
has text: Thanks for the suggestion. I do like to learn that after online course is finished. It's just I do also want to know more about how people learn things that are obscure e.g. Keras, since I would assume there are still more questions coming like this during career.
type: Comment

http://stackoverflow.com/comment/85416043
has text: Give a [**Minimal, Complete, Verifiable** Example](https://stackoverflow.com/help/how-to-ask) in your question.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49205354
type: QuestionComment

http://stackoverflow.com/comment/85433361
comment on: http://stackoverflow.com/q/49214455
score: 0
type: Comment
type: QuestionComment
has text: You need to send the result of the function to `stdout` if you want to see the result. So what @ColinRicardo

http://stackoverflow.com/a/49255395
answers question: http://stackoverflow.com/q/49226493
score: 0
accepted answer of: http://stackoverflow.com/q/49226493
type: AcceptedAnswer
has body: The easiest way to use OpenCL on EC2 is by using the Deep Learning Base Image, which comes with all necessary drivers and is already configured to work with P2 and P3 instance types. The image can be found at https://aws.amazon.com/marketplace/pp/B077GCH38C.
has comment: http://stackoverflow.com/comment/85525507
type: Answer

http://stackoverflow.com/a/49240693
has comment: http://stackoverflow.com/comment/85599999
has comment: http://stackoverflow.com/comment/85485650
has comment: http://stackoverflow.com/comment/85485918
accepted answer of: http://stackoverflow.com/q/49239943
downvote count: 0
has body: I believe it's the conversion to dtype('&lt;Unn') that might be giving you trouble. Check out the size of the array on a relative basis, using just the first few documents plus an NaN: &gt;&gt;&gt; df['cleaned'].values array(['acquaint hous receiv follow letter clerk crown', 'ask secretari state war whether issu statement', 'i beg present petit sign upward motor car driv', 'i desir ask secretari state war second lieuten', 'ask secretari state war whether would introduc', nan], dtype=object) &gt;&gt;&gt; df['cleaned'].values.astype('U').nbytes 1104 &gt;&gt;&gt; df['cleaned'].values.nbytes 48 It seems like it would make sense to drop the NaN values first (df.dropna(inplace=True)). Then, it should be pretty efficient to call v.fit_transform(df['cleaned'].tolist()).
has comment: http://stackoverflow.com/comment/85485895
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85486095
score: 1
has comment: http://stackoverflow.com/comment/85528980
type: Answer
answers question: http://stackoverflow.com/q/49239943

plotly
tags question: http://stackoverflow.com/q/49268918
tag name: plotly
type: Tag
tags question: http://stackoverflow.com/q/49162339
tags question: http://stackoverflow.com/q/49151474
tags question: http://stackoverflow.com/q/49180494
tags question: http://stackoverflow.com/q/49152131

http://stackoverflow.com/q/49171414
downvote count: 0
tagged with: javascript
tagged with: python
has answer: http://stackoverflow.com/a/49174263
has comment: http://stackoverflow.com/comment/85347959
possible better answer: http://stackoverflow.com/a/49174263
tagged with: ajax
has answer: http://stackoverflow.com/a/49174223
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49171658
score: 2
answer count: 3
has title: Scrapy tbody tag return an empty answer but has text inside
tagged with: http://stackoverflow.com/tag/html
tagged with: scrapy
favorite count: 0
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49171658
has body: I try to scrap and crawl a website. The data is in the tbody tag (event names). When I check the google console, the tbody tag has text data, but when I try to scrap it it returns an empty answer (also tested in scrapy shell). I checked for an AJAX method, because it can bug the script, but it seems does not have it. Do you have any idea why the answer is empty whereas the tbody tag has text inside source code ? Here is my code nom_robot = 'ListeCAP' domaine = ['www.justrunlah.com'] base_url = [ "https://www.justrunlah.com/running-events-calendar-malaysia", "https://www.justrunlah.com/running-events-calendar-australia", ] class ListeCourse_level1(scrapy.Spider): name = nom_robot allowed_domains = domaine start_urls = base_url def parse(self, response): selector = Selector(response) for unElement in response.xpath('//*[@id="td-outer-wrap"]/div[3]/div/div/div[1]/div/div[2]/div[3]/table/tbody/tr'): loader = ItemLoader(JustrunlahItem(), selector=unElement) loader.add_xpath('eve_nom_evenement', './/td[2]/div/div[1]/div/a/text()') # define processors loader.default_input_processor = MapCompose(string) loader.default_output_processor = Join() yield loader.load_item() yield loader.load_item() if response.xpath('//a[@class="smallpagination"]'): next_page = response.meta.get('page_number', 1) + 1 next_page_url = '{}?page={}'.format(base_url, next_page) yield scrapy.Request(next_page_url, callback=self.parse, meta={'page_number': next_page}) The terminal window ['https://www.justrunlah.com/running-events-calendar-malaysia/', 'https://www.justrunlah.com/running-events-calendar-australia/'] ----------------------------- 2018-03-08 12:34:56 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: justrunlah) 2018-03-08 12:34:56 [scrapy.utils.log] INFO: Overridden settings: {'BOT_NAME': 'justrunlah', 'NEWSPIDER_MODULE': 'justrunlah.spiders', 'ROBOTSTXT_OBEY': True, 'SPIDER_MODULES': ['justrunlah.spiders']} 2018-03-08 12:34:56 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.exten…

http://stackoverflow.com/q/49143433
tagged with: reverse
has comment: http://stackoverflow.com/comment/85292340
tagged with: python
has title: Pointer addresses of Python Lists and Matrix when reversing
has answer: http://stackoverflow.com/a/49143680
type: Question
tagged with: list
upvote count: 1
tagged with: matrix
type: UnansweredQuestion
score: 1
answer count: 1
downvote count: 0
tagged with: pointers
favorite count: 0
has body: I am trying to understand how Python matrices are implemented as compared to Java/C style 2D arrays. Specifically the problem I am facing is this: Given a matrix (list of lists), I am asked to reverse the individual lists in the matrix in-place. I came up with the following code: CODE 1 ------ def flip(matrix): for list in matrix: list=list[::-1] matrix=[[1,0,0],[0,0,1]] flip(matrix) print(matrix) # Outputs "[[1,0,0],[0,0,1]]" i.e. does not reverse If I modify the code a bit, CODE 2 ------ def flip(matrix): for list in matrix: list.reverse() matrix=[[1,0,0],[0,0,1]] flip(matrix) print(matrix) # Outputs "[[0,0,1],[1,0,0]]" i.e. works correctly this time I know that list.reverse() does in-place operation and list[::-1] creates a shallow copy. However in CODE 1, I am assigning the address of the shallow copy to the same variable (list) only. So the variable matrix should effectively get changed. Because the variable matrix[i] is the variable list. So if list gets modified, so should matrix. To illustrate my previous point, the following code is provided: CODE 3 ------ def test(matrix): for i, list in enumerate(matrix): print(matrix[i] is list) matrix=[[1,0,0],[0,0,1]] test(matrix) # Outputs "True True" If matrix[i] is list, then changing list means changing matrix[i] and changing matrix[i] means changing matrix. If I modify CODE 1 so that instead of list being assigned the address of the newly created reversed list, matrix[i] be assigned that address, then surprisingly it works! CODE 4 ------ def flip(matrix): for i, list in enumerate(matrix): # Instead of list=list[::-1] matrix[i]=list[::-1] matrix=[[1,0,0],[0,0,1]] flip(matrix) print(matrix) # Correctly Outputs [[0,0,1], [1,0,0]] I would like an explanation why CODE 1 does not work and why CODE 4 works.

http://stackoverflow.com/comment/85287311
comment on: http://stackoverflow.com/a/49140705
has text: 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. There's no file included in your post -- just a link -- and you haven't included the problem code and output.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85365928
comment on: http://stackoverflow.com/a/49179369
type: Comment
type: AnswerComment
has text: I edited my code and added the `AsyncTask`, but unfortunately your solution didn't help.
score: 0

http://stackoverflow.com/comment/85479803
score: 4
type: QuestionComment
comment on: http://stackoverflow.com/q/49238241
has text: I don't mean to sound snarky, but: are you sure you're writing Python? Because if so you have syntax errors and/or indentation errors on every single one of your lines.
type: Comment

http://stackoverflow.com/q/49188966
has answer: http://stackoverflow.com/a/49192414
tagged with: python
tagged with: jupyter-notebook
tagged with: azure-sql-database
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49189272
score: 1
upvote count: 1
favorite count: 0
type: Question
has title: DB Driver for azure SQL Data ware house via python notebook in ML Studio
tagged with: sql-data-warehouse
has body: I am trying to access my data warehouse azure, fetch some data in mlstudio-attached-notebook in python. Simple connection says driver not found. [01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 13 for SQL Server' : file not found (0) (SQLDriverConnect). Now, I need to know, is it a firewall issue or the not right driver name issue. I have tried multiple driver name/string. No effect.
tagged with: ml-studio
type: UnansweredQuestion

http://stackoverflow.com/a/49181038
downvote count: 0
has comment: http://stackoverflow.com/comment/85367709
upvote count: 1
score: 1
accepted answer of: http://stackoverflow.com/q/49180872
answers question: http://stackoverflow.com/q/49180872
type: Answer
has body: It's your indentation that's off. On my engine, it runs perfectly with proper indentation, but throws an indentation error when running without the indentation. Remember, use two or four spaces, and indentation is very important in python syntax.
type: AcceptedAnswer

http://stackoverflow.com/a/49215797
has comment: http://stackoverflow.com/comment/85435764
downvote count: 0
has body: You can use itertools.groupby with functools.reduce: import itertools import functools list1=[0, 1, 1, 1, 0, 0, 0, 1] list2=['ATT', 'TTC', 'TCC', 'CCC', 'CCA', 'CAA', 'AAA', 'AAG'] d = [[a, [h for _, h in b]] for a, b in itertools.groupby(zip(list1, list2), key=lambda x:x[0])] final_results = [i for b in filter(None, [[functools.reduce(lambda x, y:x+y[-1], [d[i-1][-1][-1]]+d[i][-1])] if d[i][0] else d[i][-1][:-1] for i in range(len(d))]) for i in b] Output: ['ATTCCC', 'CCA', 'CAA', 'AAAG']
has comment: http://stackoverflow.com/comment/85435784
type: Answer
has comment: http://stackoverflow.com/comment/85435978
answers question: http://stackoverflow.com/q/49215738
upvote count: 2
score: 2

http://stackoverflow.com/a/49280276
score: 0
answers question: http://stackoverflow.com/q/49276429
has body: If the problem is that you cannot specify particular hour for an existing datetime object, you can construct a future datetime object explicitly using some attributes from now: from datetime import datetime now = datetime.now() then = datetime(year=now.year, month=now.month, day=now.day+1, hour=19)
type: Answer

http://stackoverflow.com/a/49269811
type: Answer
answers question: http://stackoverflow.com/q/49267271
score: 2
upvote count: 2
downvote count: 0
has body: In the logs you posted it says upstream: "http://unix:/home/django/gunicorn.socket:/" - that looks like your misconfigured your Nginx server and it can't connect to the Django app. Make sure that the Nginx are set up to connect to either the socket (unix:/...) or the http endpoint that your Django app is serving traffic on.

http://stackoverflow.com/q/49157672
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has body: I have the following code, I am trying to run XFoil (an airfoil analysis code, but that isn't important) from Python. import subprocess as sp ps = sp.Popen(r'C:\Users\me\XFoil\xfoil.exe',stdin=sp.PIPE,stderr=sp.PIPE,stdout=sp.PIPE) When I run, I get the following error: OSError: [WinError 6] The handle is invalid With the full list of errors as follows: File "~/XFoil_Own.py", line 12, in &lt;module&gt; ps = sp.Popen(r'C:\Users\,e\XFoil\xfoil.exe' ,stdin=sp.PIPE,stderr=sp.PIPE,stdout=sp.PIPE) File "~\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 210, in __init__ super(SubprocessPopen, self).__init__(*args, **kwargs) File "~\Anaconda3\lib\subprocess.py", line 596, in __init__ _cleanup() File "~\Anaconda3\lib\subprocess.py", line 205, in _cleanup res = inst._internal_poll(_deadstate=sys.maxsize) File "~\Anaconda3\lib\subprocess.py", line 1035, in _internal_poll if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: OSError: [WinError 6] The handle is invalid I am running Python 3.6 through Anaconda3 and Spyder, on a 64bit windows machine. XFoil is 32bit - I don't know if that is maybe causing the issue, or if it is something else. I haven't been able to find anyone else with the same issue of WinError 6 when running a program like this. Any help would be very much appreciated.
has comment: http://stackoverflow.com/comment/85330245
type: UnansweredQuestion
tagged with: windows
has comment: http://stackoverflow.com/comment/111331630
downvote count: 0
tagged with: python
has title: OSError: [WinError 6] The handle is invalid, running subprocess.Popen on Python 3.6
tagged with: anaconda
answer count: 0
linked to: http://stackoverflow.com/q/40108816
score: 1
tagged with: spyder

doctest
type: Tag
tags question: http://stackoverflow.com/q/49190236
tag name: doctest
tags question: http://stackoverflow.com/q/49271586
tags question: http://stackoverflow.com/q/49254777
tags question: http://stackoverflow.com/q/49265430

http://stackoverflow.com/q/49184578
duplicate of: http://stackoverflow.com/q/988228
has answer: http://stackoverflow.com/a/61358653
has comment: http://stackoverflow.com/comment/85374976
type: Question
type: AnsweredQuestion
tagged with: byte
has answer: http://stackoverflow.com/a/49184648
has answer: http://stackoverflow.com/a/49184674
linked to: http://stackoverflow.com/q/1832940
has comment: http://stackoverflow.com/comment/85375059
tagged with: python
upvote count: 103
tagged with: dictionary
score: 101
has comment: http://stackoverflow.com/comment/85375039
has title: How to convert bytes type to dictionary
answer count: 4
favorite count: 0
accepted answer: http://stackoverflow.com/a/49184648
has body: I have a bytes type object like this: b"{'one': 1, 'two': 2}" I need to get proper python dictionary from the above bytes type object using python code. string = b"{'one': 1, 'two': 2}" d = dict(toks.split(":") for toks in string.split(",") if toks) But I am getting the below error: ------> d = dict(toks.split(":") for toks in string.split(",") if toks) TypeError: 'bytes' object is not callable
linked to: http://stackoverflow.com/q/988228
possible better answer: http://stackoverflow.com/a/53406072
downvote count: 2
has comment: http://stackoverflow.com/comment/123738360
has answer: http://stackoverflow.com/a/53406072

http://stackoverflow.com/q/49192909
answer count: 3
tagged with: api
score: 1
accepted answer: http://stackoverflow.com/a/49193975
has answer: http://stackoverflow.com/a/50398906
has answer: http://stackoverflow.com/a/49193975
favorite count: 0
type: Question
downvote count: 0
possible better answer: http://stackoverflow.com/a/50398906
upvote count: 1
tagged with: python
tagged with: request
has body: I need to do a post request according to the scenario given below. I only have consumers_key and consumer_secret. I don't know from where to get all the other fields. and also do i need to send the Authorization request including keys in the header? A request token for the application must be obtained using the consumer key from the above response. Request POST /public/v1/oauth1/request_token Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2 Authorization: OAuth oauth_consumer_key="btgd2cg2bm3lbjqsfv150fj9q8", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1467792887", oauth_nonce="9fd50a6f-40e0-41be-8809-34aa832b688e", oauth_callback="oob", oauth_signature="hcE6Q3boTytkHmM72xegCP1Y3W4%3D" I am doing something like this import requests url="https://api.discovergy.com" request_token_url=url+'/public/oauth1/request_token' head={'Accept':'text/html, image/gif, image/jpeg, *;q=.2, '/';q=.2', 'Authorization':'OAuth'} data= dict(oauth_consumer_key=client_key, oauth_signature_method='HMAC-SHA1', oauth_timestamp='1467792887', oauth_nonce='9fd50a6f-40e0-41be-8809-34aa832b688e', oauth_callback='oob', oauth_signature='hcE6Q3boTytkHmM72xegCP1Y3W4%3D') r=request.post(url=request_token_url, data=data, headers=head) print(r.content) It gives 400 status..
has title: OAuth1 Authentication of Rest API
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/75047903
tagged with: rest

http://stackoverflow.com/a/49154221
accepted answer of: http://stackoverflow.com/q/49154153
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49154153
has body: I think need remove []: print(df2[df2['col2'].isin(coursesFilter)]) print(df2[df2['col2'].isin(pd.Series(coursesFilter))]) print(df2[df2['col2'].isin(pd.Series(coursesFilter).tolist())]) Input Series.isin parameters: values : set or list-like The sequence of values to test. Passing in a single string will raise a TypeError. Instead, turn a single string into a list of one element.
type: AcceptedAnswer
upvote count: 2
score: 2

pdfbox
tag name: pdfbox
tags question: http://stackoverflow.com/q/49272234
type: Tag
tags question: http://stackoverflow.com/q/49246504

http://stackoverflow.com/comment/85408623
has text: @Jan I tried doing that in MATLAB so the syntax might be a little different and it is highly inefficient atm: 'expr = '(?<=Time\s*:\s*(\d{2}:\d{2}:\d{2}\.\d{2},))(?<your_field>(.*))'; '
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49201556

http://stackoverflow.com/comment/85367174
comment on: http://stackoverflow.com/q/49180476
score: 0
type: Comment
type: QuestionComment
has text: Also this one: https://stackoverflow.com/questions/20201706/overflowerror-34-result-too-large/20201845

http://stackoverflow.com/q/49230302
type: Question
tagged with: numpy
tagged with: numpy-indexing
downvote count: 0
has comment: http://stackoverflow.com/comment/85464148
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85464860
has body: In Numpy, can we use a 2D array as index into a 1D array? What array array indexing rule applies to following code? # 1D array arr = np.arange(10) # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) # 2D index indx = np.array([[2, 4], [6, 8]]) # 2D index in 1D array arr[indx] # Output of above indexing is a 2D array! array([[2, 4],[6, 8]])
favorite count: 0
tagged with: python-3.x
upvote count: 3
score: 3
has answer: http://stackoverflow.com/a/49231252
has comment: http://stackoverflow.com/comment/85464360
tagged with: python
has title: Indexing a 1D Numpy array using 2D array
has comment: http://stackoverflow.com/comment/85464589
has comment: http://stackoverflow.com/comment/85464049

http://stackoverflow.com/q/49214782
has comment: http://stackoverflow.com/comment/85438517
has comment: http://stackoverflow.com/comment/85453308
type: Question
has body: My Cython library compiles fine but when I try to import it I get undefined symbol: PyPyExc_TypeError. I'm not sure where this is coming from. PyPyExc_TypeError does not appear anywhere in the Cython generated file. I installed Cython 0.27.3 in a virtualenv to make sure it was clean. Python 2.7.12 (default, Dec 4 2017, 14:50:18) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import hi Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: ./hi.so: undefined symbol: PyPyExc_TypeError &gt;&gt;&gt; Here's my contrived hi.pyx to demonstrate cpdef hi(): return 'hi' Compiled with cython hi.pyx gcc hi.c -I /usr/lib/python2.7/ -fPIC -shared -o hi.so -pthread -lpython2.7
type: UnansweredQuestion
tagged with: cpython
has comment: http://stackoverflow.com/comment/85440361
has title: Cython undefined symbol PyPyExc_TypeError when using cpython
tagged with: python
score: 0
answer count: 0
tagged with: cython

http://stackoverflow.com/comment/85274325
comment on: http://stackoverflow.com/q/49134554
type: Comment
type: QuestionComment
has text: What's the result of `where python` and `python --version` on the Windows command line?
score: 0

http://stackoverflow.com/q/49258407
has comment: http://stackoverflow.com/comment/85525893
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85520296
upvote count: 4
has comment: http://stackoverflow.com/comment/85523566
has answer: http://stackoverflow.com/a/70113502
type: Question
has comment: http://stackoverflow.com/comment/85525935
tagged with: http://stackoverflow.com/tag/csv
has title: How to split .csv into multiple .csv by columns using R?
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85523699
tagged with: http://stackoverflow.com/tag/r
has body: I have a huge .CSV file with more than 3000 columns and need to load these into the database and because the table limitation is 1024 columns I want to split these .CSV files into multiple files of 1024 or less columns. So far what I have tried with the help of previous questions regarding this topic - Python - import csv import file input import os source = 'H:\\Programs\\Exploratory Items\\Outdated\\2018\\csvs\\' for root, dirs, filenames in os.walk(source): for f in filenames: fullpath = os.path.join(source, f) output_specifications = ( (fullpath[:-4] + 'pt1.csv', slice(1000) (fullpath[:-4] + 'pt2.csv', slice(1000, 2000)), (fullpath[:-4] + 'pt3.csv', slice(2000, 3000)), (fullpath[:-4] + 'pt4.csv', slice(3000, 4000)), (fullpath[:-4] + 'pt5.csv', slice(4000, 5000)), ) output_row_writers = [ ( csv.writer(open(file_name, 'wb'), quoting=csv.QUOTE_MINIMAL).writerow, selector, ) for file_name, selector in output_specifications ] reader = csv.reader(fileinput.input()) for row in reader: for row_writer, selector in output_row_writers: row_writer(row[selector]) The issue with the above python code is it takes forever to split and write these files because it writes by row is my understanding. Not ideal for my case as I have more than 200 .CSV files with 1000+ rows in each. Trying now - -cut command (POSIX) but I use Windows so will try this on Ubuntu platform. Want to try this in R: I have a code that converts all my SPSS to .csv which works efficiently so I want to add more to this at this stage so it can split my file by column into multiple .csvs. setwd("H:\\Programs\\2018") getwd() list.files() files &lt;- list.files(path = '.', pattern = '.sav') library(foreign) for (f in files) { #iterate over them data &lt;- read.spss(f, to.data.frame = TRUE, use.value.labels = FALSE ) write.csv (data, paste0(strsplit(f, split = '.', fixed = T)[[1]][1], '.csv')) } Thank you References - Python code ref
linked to: http://stackoverflow.com/q/25904824
has comment: http://stackoverflow.com/comment/85520152
has comment: http://stackoverflow.com/comment/85525674
has comment: http://stackoverflow.com/comment/85520320
score: 3
answer count: 1
has comment: http://stackoverflow.com/comment/85520156
has comment: http://stackoverflow.com/comment/85526086
has comment: http://stackoverflow.com/comment/85525799

http://stackoverflow.com/q/49193134
downvote count: 0
answer count: 1
favorite count: 0
tagged with: optimization
type: Question
tagged with: static-methods
has body: Does it make sense to pass attributes of instance/class (self.something) to a static method of the same class? Example without static method: from intel import i5 from kingston import ddr3 from windows import Prompt class PC: def __init__(self, username, password, cpu, ram): self.username = username self.password = password self.cpu = cpu self.ram = ram def _log_in(self, login_prompt): login_prompt.enter(self.username, self.password) def start_up(self): # boot_up and do stuff... login_prompt = Prompt() self._log_in(login_prompt) # auto-run applications and do stuff... Example with static method: from intel import i5 from kingston import ddr3 from windows import Prompt class PC: def __init__(self, username, password, cpu, ram): self.username = username self.password = password self.cpu = cpu self.ram = ram @staticmethod def _log_in(login_prompt, username, password): login_prompt.enter(username, password) def start_up(self): # boot_up and do stuff... login_prompt = Prompt() self._log_in(login_prompt, self.username, self.password) # auto-run applications and do stuff... In both cases usage would be the same: my_computer = PC('user', 'password', i5, ddr3) my_computer.start_up()
score: 1
has title: Passing class/instance attributes to static methods in Python
tagged with: python
has comment: http://stackoverflow.com/comment/85391310
tagged with: class
has comment: http://stackoverflow.com/comment/85391773
has answer: http://stackoverflow.com/a/49193271
upvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/q/49185538
possible better answer: http://stackoverflow.com/a/68419849
has answer: http://stackoverflow.com/a/53385042
has answer: http://stackoverflow.com/a/65271092
has answer: http://stackoverflow.com/a/68419849
has answer: http://stackoverflow.com/a/68071996
score: 13
tagged with: python
tagged with: youtube
upvote count: 13
has answer: http://stackoverflow.com/a/52576269
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49241754
has body: Is there a way to add progress bar in pytube? I don't know how to use the following method: pytube.Stream().on_progress(chunk, file_handler, bytes_remaining) My code: from pytube import YouTube # from pytube import Stream from general import append_to_file def downloader(video_link, down_dir=None): try: tube = YouTube(video_link) title = tube.title print("Now downloading, " + str(title)) video = tube.streams.filter(progressive=True, file_extension='mp4').first() print('FileSize : ' + str(round(video.filesize/(1024*1024))) + 'MB') # print(tube.streams.filter(progressive=True, file_extension='mp4').first()) # Stream(video).on_progress() if down_dir is not None: video.download(down_dir) else: video.download() print("Download complete, " + str(title)) caption = tube.captions.get_by_language_code('en') if caption is not None: subtitle = caption.generate_srt_captions() open(title + '.srt', 'w').write(subtitle) except Exception as e: print("ErrorDownloadVideo | " + str(video_link)) append_to_file('debug', format(e)) # FILESIZE print(tube.streams.filter(progressive=True, file_extension='mp4').first().filesize/(1024*1024))
has answer: http://stackoverflow.com/a/49241754
downvote count: 0
has answer: http://stackoverflow.com/a/68234125
has answer: http://stackoverflow.com/a/62713949
has title: How to add progress bar?
favorite count: 0
type: Question
tagged with: pytube
answer count: 9
has answer: http://stackoverflow.com/a/71431660

http://stackoverflow.com/q/49122003
type: Question
linked to: http://stackoverflow.com/q/44724185
has body: I'm trying to click on this button: browser.find_element_by_id('btnSearch') But this button is blocking by this div tag: &lt;div id="actionSearch" class="row pull-right"&gt; How do I go around to click this button with id='btnSearch" while it's blocking by the actionSearch div? I tried the following: browser.find_element_by_id('btnSearch').click() browser.implicitly_wait(10) el = browser.find_element_by_xpath('//*[@id="btnSearch"]') ActionChains(browser).move_to_element_with_offset(el, 1827, 270) ActionChains(browser).click() ActionChains(browser).perform() element = browser.find_element_by_id('btnSearch') browser.execute_script("arguments[0].click();", element) wait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, //*[@id="btnSearch"]'))).click() none of these work. Can anyone help me with this? I've spent two days trying to click this button!! Please help!
linked to: http://stackoverflow.com/q/44912203
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has title: Element is not clickable (the button is blocking by other element)
tagged with: css
has comment: http://stackoverflow.com/comment/85262080
tagged with: selenium-chromedriver
score: 0
has comment: http://stackoverflow.com/comment/85264447
has answer: http://stackoverflow.com/a/49124400
has comment: http://stackoverflow.com/comment/85264837
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/85266497

http://stackoverflow.com/a/49235380
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49235268
type: Answer
has body: list1 = [['RESULT 1', 'X'], ['RESULT 2', 'Y'], ['RESULT 3', 'X', 'Y'], ['RESULT 4', 'Z', 'Y'], ['RESULT 5', 'Z'], ['RESULT 6', 'Z', 'X']] list2 = [['X', 12, 56, 2], ['Y', 100], ['Z', 22, 78, 00, 1, 5]] map2 = {item[0]: item[1:] for item in list2} for item in list1: for pos, sub_item in enumerate(item): item[pos] = map2.get(sub_item, sub_item)

append
tags question: http://stackoverflow.com/q/49133657
tags question: http://stackoverflow.com/q/49144964
tags question: http://stackoverflow.com/q/49210678
tag name: append
tags question: http://stackoverflow.com/q/49186968
tags question: http://stackoverflow.com/q/49139563
tags question: http://stackoverflow.com/q/49160881
tags question: http://stackoverflow.com/q/49143128
tags question: http://stackoverflow.com/q/49222915
tags question: http://stackoverflow.com/q/49263071
type: Tag
tags question: http://stackoverflow.com/q/49227249

http://stackoverflow.com/comment/85296200
type: AnswerComment
has text: no need to add `if i in l` because you are iterating over list meaning that should be in the list
comment on: http://stackoverflow.com/a/49145472
score: 0
type: Comment

http://stackoverflow.com/q/49258114
answer count: 1
type: Question
linked to: http://stackoverflow.com/q/10604409
has comment: http://stackoverflow.com/comment/85519500
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85519265
has body: s = input("enter something:") print(s) d = input("enter something else") print(d) so once I input a string.. the program does not proceed.. nor does it print the string. (i'm a noob at python rn) [I'm using sublimeText3 + Anaconda] Check the screenshot out, it'd be more helpful
has title: I'm not getting any output after taking user input using input() in python.
tagged with: python
has answer: http://stackoverflow.com/a/49258257
score: 0
has comment: http://stackoverflow.com/comment/85519360

http://stackoverflow.com/comment/85334423
score: 1
type: Comment
type: AnswerComment
has text: @style Sure, but as OP was making such basic mistake, I think he should learn something fundamental first, or he won't be able to complete what he want.
comment on: http://stackoverflow.com/a/49164372

http://stackoverflow.com/comment/85323148
score: 0
comment on: http://stackoverflow.com/q/49151474
has text: IIUC you could try to use [plotly.offline](https://plot.ly/python/getting-started/#initialization-for-offline-plotting)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85559306
score: 0
has text: "Not hearing the question, son"
comment on: http://stackoverflow.com/q/49278353
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/96385923
type: AnswerComment
comment on: http://stackoverflow.com/a/49137028
has text: I tried this method and it only "looks" like aligned when the number of levels is small and the size is not too big. If I enlarge the widget it appears to be off. PS I'm using PyQt5 in case that makes a difference.
score: 1
type: Comment

http://stackoverflow.com/q/49207763
answer count: 1
type: Question
has body: I'm working on two computers, both of them running Windows 10. I'm pretty sure I installed the same python environment for the two of them (python3 32bits, numpy, scipy and matplotlib through pip). They don't produce the same kind of matplotlib window (the toolbar is different, and the colormap does not seem to be the same). Here are two screenshots: Matplotlib result 1: Matplotlib result 2: I guess it's a backend issue, but I can't seem to remember installing an additional backend on one of those environments. Since the picture 2 looks "GTK" to me, I still tried to install pygtk on my 2nd computer, which required me to install pygobject, which yields this compilation error: fatal error C1083: Cannot open include file: 'cairo.h': No such file or directory How could I get these two matplotlib setups to look the same?
has title: Matplotlib look & feel
has answer: http://stackoverflow.com/a/49208164
tagged with: python
accepted answer: http://stackoverflow.com/a/49208164
type: AnsweredQuestion
score: 0
tagged with: matplotlib

http://stackoverflow.com/q/49181526
has answer: http://stackoverflow.com/a/49236443
type: Question
answer count: 2
tagged with: yum
has body: Any yum command I try to run, returns the following: There was a problem importing one of the Python modules required to run yum. The error leading to this problem was: cannot import name Errors Please install a package which provides this module, or verify that the module is installed correctly. It's possible that the above module doesn't match the current version of Python, which is: 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) [GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] If you cannot solve this problem yourself, please go to the yum faq at: http://yum.baseurl.org/wiki/Faq This is what I've done and what I know: OS is Red hat 4.4.7018 I believe Python was 2.6 and was updated to 2.7 some time ago (I suspect this might have broken yum) python -V returns 2.7.13 # ls -lrt /usr/bin/python* -rwxr-xr-x. 1 root root 4864 Aug 18 2016 /usr/bin/python2.6 lrwxrwxrwx. 1 root root 6 Mar 8 13:16 /usr/bin/python2 -&gt; python lrwxrwxrwx. 1 root root 24 Mar 8 13:32 /usr/bin/python -&gt; /usr/local/bin/python2.7 # ls /usr/bin/python* /usr/bin/python /usr/bin/python2 /usr/bin/python2.6 # ls /usr/local/bin/python* /usr/local/bin/python2.7 /usr/local/bin/python2.7-config I've tried running import yum on all phytons and only the 2.6 does not give me an error, so I tried changing the links back to 2.6 (Validated with python -V to check it goes back to version 2.6.6), and yum still returns the "cannot import name Errors" error. Also, the PATH variable: # echo $PATH /usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin:/usr/local/git/bin:/root/bin The python configured on /usr/bin/yum is #!/usr/bin/python2.6, I've tried changing it to /python, and even /phyton2 and I still get the error.
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4140219
has answer: http://stackoverflow.com/a/49208957
tagged with: rhel
score: 0
tagged with: python
tagged with: redhat
has title: Yum "cannot import name Errors" - Red Hat 4.4 with Python 2.6 / 2.7

http://stackoverflow.com/q/49184885
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/49184959
possible better answer: http://stackoverflow.com/a/49184959
has comment: http://stackoverflow.com/comment/85375571
has title: Nesting dictionaries in python with a csv and I need to decrement or increment a date
type: AnsweredQuestion
score: 0
answer count: 3
tagged with: loops
has body: I'm excited because I got pretty far with some hints from a friend. I'm trying to create a dictionary of dictionaries using a loop. The csv I'm working with has dates from 2008-2014 and I'm using the dates as a key. The csv looks like this: year,title_field,value 2014,Total Housing Units,49109 2014,Vacant Housing Units,2814 2014,Occupied Housing Units,46295 2013,Total Housing Units,47888 2013,Vacant Housing Units,4215 2013,Occupied Housing Units,43673 2012,Total Housing Units,45121 2012,Vacant Housing Units,3013 2012,Occupied Housing Units,42108 2011,Total Housing Units,44917 2011,Vacant Housing Units,4213 2011,Occupied Housing Units,40704 2010,Total Housing Units,44642 2010,Vacant Housing Units,3635 2010,Occupied Housing Units,41007 2009,Total Housing Units,39499 2009,Vacant Housing Units,3583 2009,Occupied Housing Units,35916 2008,Total Housing Units,41194 2008,Vacant Housing Units,4483 2008,Occupied Housing Units,36711 Here's my code: import csv denton_housing = {} filename = 'denton_housing.csv' key = 2014 with open(filename, 'r', encoding='utf8', newline='') as f: for row in csv.DictReader(f, delimiter=','): while key not in denton_housing: denton_housing[key] = {} denton_housing[key][row['title_field']] = int(row['value']) key-1 When I print that, I get: {2014: {'Total Housing Units': 49109}} Which is awesome! But I need this: {2014: {'Total Housing Units': 49109}, {'Vacant Housing Units': 2814}, \ {'Occupied Housing Units': 46295}} More importantly, I need it to loop back around and do the same for 2013, 2012, 2011, 2010, 2009, and 2008, but stop there.
has comment: http://stackoverflow.com/comment/85375513
has answer: http://stackoverflow.com/a/49184976
type: Question
has answer: http://stackoverflow.com/a/49184946
accepted answer: http://stackoverflow.com/a/49184946
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/49142329
answers question: http://stackoverflow.com/q/49142124
type: Answer
has body: You need to broadcast your input like so: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; &gt;&gt;&gt; a, b, c = 2, 3, 4 &gt;&gt;&gt; seq = np.arange(a*b*c).reshape(a, b, c) &gt;&gt;&gt; &gt;&gt;&gt; weight = np.linspace(0, 1, 3) &gt;&gt;&gt; result = seq[..., None, :, None] * weight + seq[:, None, ..., None] * weight[::-1] &gt;&gt;&gt; result.shape (2, 3, 3, 4, 3) &gt;&gt;&gt; result array([[[[[ 0., 0., 0.], [ 1., 1., 1.], [ 2., 2., 2.], [ 3., 3., 3.]], [[ 4., 2., 0.], [ 5., 3., 1.], [ 6., 4., 2.], [ 7., 5., 3.]], [[ 8., 4., 0.], [ 9., 5., 1.], [10., 6., 2.], [11., 7., 3.]]], ... [[[12., 16., 20.], [13., 17., 21.], [14., 18., 22.], [15., 19., 23.]], [[16., 18., 20.], [17., 19., 21.], [18., 20., 22.], [19., 21., 23.]], [[20., 20., 20.], [21., 21., 21.], [22., 22., 22.], [23., 23., 23.]]]]])
score: 0

http://stackoverflow.com/a/49214404
type: Answer
accepted answer of: http://stackoverflow.com/q/49206726
has body: I have the same problem. My application worked and now it doesn't. I tried a lot of things (with python3.5 and not 3.6, delete all .pyc, uninstall and install django-paypa, change port...) It doesn't seem to change any thing. I was giving up, but I recived all my signals in one time. It was a lot of time after. I tried immediately after and nothing, no signals. So, for me, the probleme is on paypal's server. They takes time. We have to wait. I hope my experience helps you :) Currently, it works normally for me (11 march 2018 11am). I hope it's the same for you :)
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85468517
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49206726

http://stackoverflow.com/q/49139674
tagged with: python
has title: Getting a function's module of original definition
type: AnsweredQuestion
tagged with: python-import
score: 5
downvote count: 0
has body: Given a class or function, is there a way to find the full path of the module where it is originally defined? (I.e. using def xxx or class xxx.) I'm aware that there is sys.modules[func.__module__]. However, if func is imported in a package's __init__.py, then sys.modules will simply redirect to that __init__.py, because the function has been brought into that namespace, as far as my understanding goes. A concrete example: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; import sys &gt;&gt;&gt; np.broadcast.__module__ 'numpy' &gt;&gt;&gt; sys.modules[np.broadcast.__module__] &lt;module 'numpy' from '/Users/brad/.../site-packages/numpy/__init__.py'&gt; Obviously, broadcast is not defined in __init__.py; it is just brought into the namespace with one of these from module import * statements. It would be nice to see where in the source np.broadcast is defined (regardless of the file extension, be it .c or .py). Is this possible?
answer count: 1
has answer: http://stackoverflow.com/a/49139885
accepted answer: http://stackoverflow.com/a/49139885
favorite count: 0
type: Question
upvote count: 5

http://stackoverflow.com/comment/104755663
comment on: http://stackoverflow.com/a/49133602
score: 0
type: Comment
has text: @MattG thanks for the correction, I edited the answer.
type: AnswerComment

http://stackoverflow.com/q/49136544
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49136674
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85291165
answer count: 2
has body: X = dataset.iloc[:, 2:-1].values df_X = pd.DataFrame(X) df_X.head() I am slicing my columns to the index specified in the array. Is there any way I can show the columns names after slicing rather than showing the index? I am new to pandas. img
downvote count: 0
possible better answer: http://stackoverflow.com/a/49136654
upvote count: 1
has title: Initialise a new dataframe from another dataframe sub-slice along with its column names
has answer: http://stackoverflow.com/a/49136654
favorite count: 0
type: Question
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/49136674

http://stackoverflow.com/q/49149312
has body: I run the following python code: import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() Then I run somewhere: pip install --user --upgrade numpy Hover over the pyplot figure, and python crashes immediatly (segmentation fault). Question: Any idea how I can change the python code so python won't crash when I do the numpy command? If you want the full story, I have written a distributed TensorFlow tester which installs tensorflow on multiple stations (which also causes numpy to be reinstalled). The tester also displays result graphs using matplotlib.
has comment: http://stackoverflow.com/comment/85307155
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/85307636
tagged with: python-2.7
score: 0
answer count: 0
has title: matplotlib + upgrade numpy causes python 2.7 to crash
tagged with: matplotlib
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85306711
type: UnansweredQuestion

http://stackoverflow.com/comment/85536329
type: QuestionComment
score: 0
has text: Also, can you share the code snippet around the point where this exception occurs?
comment on: http://stackoverflow.com/q/49265525
type: Comment

http://stackoverflow.com/q/49246790
has comment: http://stackoverflow.com/comment/85497371
tagged with: python
has comment: http://stackoverflow.com/comment/85497586
type: Question
tagged with: coding-style
tagged with: python-3.x
score: 0
answer count: 0
has body: I am trying to extract data out of a csv file and output the data to another csv file. relate task perform 0 avc asd 1 12 24 2 34 54 3 22 33 4 11 11 5 335 534 Time A B C D 0 0.334 0.334 0.334 0.334 1 0.543 0.543 0.543 0.543 2 0.752 0.752 0.752 0.752 3 0.961 0.961 0.961 0.961 4 1.17 1.17 1.17 1.17 5 1.379 1.379 1.379 1.379 I am writing a python script to read the above table. I want all the data from Time, A, B,C, and D onwards in a separate file. import csv import pandas as pd import os read_file = False with open ('xyz.csv', mode = 'r', encoding = 'utf-8') as f_read: reader = csv.reader(f_read) for row in reader: if 'Time' in row I am stuck here. I read all the data in 'reader'. All the rows should have been parsed inside 'reader'. Now, how can I extract the data from line with Time and onwards into a separate file? Is there a better method to achieve the above objective? Should I use pandas instead of regular python commands? I read many similar answers on stackoverflow but I am confused on how to finish this problem. Your help is appreciated. Best
type: UnansweredQuestion
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: pandas
has title: Extract data out of a csv file

http://stackoverflow.com/a/49234386
downvote count: 0
score: 6
has body: Just as the linked question Python Matplotlib/Basemap Color Cycling shows, you may set the axes' prop_cycle to include those colors you like. Here you can take the tab10 colors and add two more colors to the list of colors to be used in the prop_cycle. import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() colors = list(plt.cm.tab10(np.arange(10))) + ["crimson", "indigo"] ax.set_prop_cycle('color', colors) for i in range(12): ax.plot([0,1],[i,i]) plt.show() However, since in the case from the question, you anyway loop over the colors, there is actually no need for a cycler. The following produces the same result as above. import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() colors = list(plt.cm.tab10(np.arange(10))) + ["crimson", "indigo"] for i in range(12): ax.plot([0,1],[i,i], color=colors[i]) plt.show()
answers question: http://stackoverflow.com/q/49233855
type: Answer
accepted answer of: http://stackoverflow.com/q/49233855
upvote count: 6
type: AcceptedAnswer

http://stackoverflow.com/q/49160890
tagged with: python
tagged with: amazon-web-services
has body: So I can run my bot locally from my machine and it works great, but when I try to host it on an AWS I get the error: AttributeError: 'Message' object has no attribute 'server' Here's the line that's causing the problem. role = discord.utils.get(message.server.roles, name=entered_role)
score: 0
has comment: http://stackoverflow.com/comment/85331780
has comment: http://stackoverflow.com/comment/85327723
answer count: 1
tagged with: amazon-ec2
upvote count: 1
tagged with: discord
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/50476620
has comment: http://stackoverflow.com/comment/85331821
tagged with: discord.py
has title: Discord bot runs locally but not on EC2 server?
type: UnansweredQuestion

http://stackoverflow.com/comment/85376672
has text: I found that the oss service my company using provide the compressed picture with a specific postfix，by using it I solve this problem. :p But in technique method, I still can't find a clean resolve.
comment on: http://stackoverflow.com/q/49124864
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49224477
has answer: http://stackoverflow.com/a/49224491
accepted answer: http://stackoverflow.com/a/49224491
tagged with: python
upvote count: 4
type: AnsweredQuestion
tagged with: tkinter
downvote count: 0
has body: I have a Tkinter GUI I've been working on for some time that has a live-plotting feature currently built in matplotlib. However, I'm finding matplotlib to be too slow (it seems to build up a lag over time, as if filling up a buffer of frames of incoming data), so I'm thinking of switching my plotting to PyQtGraph. Can I put this into my Tkinter app?
answer count: 1
tagged with: pyqtgraph
score: 4
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85452518
has title: Embedding a PyQtGraph into a Tkinter GUI

http://stackoverflow.com/q/49261143
has comment: http://stackoverflow.com/comment/85526505
type: Question
has comment: http://stackoverflow.com/comment/85528025
has title: Kivy: Transfer information between screens
accepted answer: http://stackoverflow.com/a/49261937
tagged with: python
has body: I have a simple app where users have to type in username and password to access second screen. To do this I use sqlite. *Py class LoginPage(Screen): def findAccount(self): username = self.ids["login_in"].text password = self.ids["pass_in"].text c.execute('''SELECT * FROM customer WHERE name = ? AND password = ?; ''', (username, password)) records = c.fetchone() #returns (1, Bob, qwerty, bob@gmail.com, 071234556) return records def verify(self): try: records = LoginPage.findAccount(self) if self.ids["login_in"].text == records[1] and self.ids["pass_in"].text == records[2]: self.manager.current = "user" except TypeError: print("Something is not correct") class UserInfoPage(Screen): def show_info(self): pass class ScreenManagement(ScreenManager): pass kv_file = Builder.load_file("login.kv") class LoginApp(App): def build(self): return kv_file *Kv ScreenManager: LoginPage: UserInfoPage: &lt;LoginPage&gt;: orientation: "vertical" name: "login" BoxLayout: TextInput: id: login_in TextInput: id: pass_in password: True Button: text: "GO" on_release: root.findAccount() root.verify() &lt;UserInfoPage&gt;: name: "user" BoxLayout: Label: id: the_id text: 'id: ' Label: text: 'name: ' Label: text: 'email: ' Label: text: 'phone number: ' by using 'show_info()' method I want to display user's information on 'UserInfoPage' screen. To do this I need information from variable 'records' from 'findAccount' account method. I tried to do like this: def show_info(self): information = LoginPage.findAccount(self) user_id = information[0] self.ids["the_id"].text = self.ids["the_id"].text + str(user_id) but it throws an error because 'findAccount()' method is linked to first screen. How to save information I got on first screen and transfer it on to second screen? Thank you.
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85526885
has answer: http://stackoverflow.com/a/49261937
tagged with: sqlite
answer count: 1
tagged with: kivy

http://stackoverflow.com/comment/85374028
comment on: http://stackoverflow.com/q/49183514
type: Comment
type: QuestionComment
score: 0
has text: What input do you have, and what is your expected output, *exactly*?

http://stackoverflow.com/comment/91531654
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/50719412
has text: @Yograj It's working fine. But can you add few other lines of code that install Box2D too. CartPole is running fine on it but when I use CarRacing it throws error. I tried installing Box2D from various sources, but failed all the time.

http://stackoverflow.com/comment/85624185
type: Comment
has text: @kevmo314 please elaborate how that connects to problem.
type: QuestionComment
comment on: http://stackoverflow.com/q/49266939
score: 0

http://stackoverflow.com/a/49183888
type: Answer
has body: Pandas is a great python package which includes tons of useful statistical/datascience functions, such as correlation. import pandas as pd import numpy as np array1 = np.array([[1,1,0.1627], [1,2,0.2993], [1,3,0.1192], [1,4,0.201 ], [1,5,0.0678], [1,6,0.2354], [1,7,0.1921], [2,1,0.1627], [2,2,0.2993], [2,3,0.1192], [2,4,0.201 ], [2,5,0.0678], [2,6,0.2354], [2,7,0.1921], [3,1,0.1627], [3,2,0.2993], [3,3,0.1192], [3,4,0.201 ], [3,5,0.0678], [3,6,0.2354]]) df = pd.DataFrame(columns=["cat1", "cat2", "jaccard"], data=array1) df.corr() # correlation output cat1 cat2 jaccard cat1 1.00000 -0.101380 -0.008720 cat2 -0.10138 1.000000 -0.109329 jacard -0.00872 -0.109329 1.000000
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49179155
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49179155
downvote count: 0

http://stackoverflow.com/comment/85301362
type: QuestionComment
score: 0
has text: @COLDSPEED No, I want it pure :)
type: Comment
comment on: http://stackoverflow.com/q/49147911

http://stackoverflow.com/q/49192351
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85389581
has comment: http://stackoverflow.com/comment/85390336
tagged with: python
accepted answer: http://stackoverflow.com/a/49193038
tagged with: regex
has answer: http://stackoverflow.com/a/49193038
type: Question
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49192446
downvote count: 0
has answer: http://stackoverflow.com/a/49192446
upvote count: 1
score: 1
tagged with: string
has body: I would like to find a Regex to convert string like the following one: wienerstr256pta 18 graz austria8051 4 Into the following one: wienerstr 256 pta 18 graz austria 8051 4 So I just want to surround every number set between spaces. I know I can easily find the digits by: /[0-9]+/g But how can I replace this match with the same content plus extra whitespaces?
has title: ReGex for surrounding numbers with whitespaces
favorite count: 0
has comment: http://stackoverflow.com/comment/85389534

http://stackoverflow.com/comment/85454503
type: Comment
type: QuestionComment
has text: so you cannot use `extend` or `+=` just because?
comment on: http://stackoverflow.com/q/49225343
score: 1

http://stackoverflow.com/q/49275041
has comment: http://stackoverflow.com/comment/85552544
linked to: http://stackoverflow.com/q/48542737
linked to: http://stackoverflow.com/q/18823139
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85554959
downvote count: 0
has answer: http://stackoverflow.com/a/49278563
accepted answer: http://stackoverflow.com/a/49278563
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85552998
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/85554666
has comment: http://stackoverflow.com/comment/85554780
favorite count: 0
type: Question
has title: Python-Selenium "input type file" upload
has comment: http://stackoverflow.com/comment/85552888
has body: I'm trying to upload a file to a website using python and selenium. I tried following methods driver = webdriver.Firefox() driver.get("ip-address") method 1: test = driver.find_element_by_id("selectedFile") test.send_keys('/Users/knightfox/Desktop/file.txt') method 2: test = driver.find_element_by_xpath("//input[@type='file']") test.send_keys('/Users/knightfox/Desktop/file.txt') method 3: test = driver.find_element_by_css_selector('input[type="file"]') test.send_keys(r'/Users/knightfox/Desktop/file.txt') But I get following errors when execute. Traceback (most recent call last): File "/home/knightfox/Desktop/bell/sel.py", line 18, in &lt;module&gt; test.send_keys(r/Users/knightfox/Desktop/file.txt) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 479, in send_keys 'value': keys_to_typing(value)}) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 628, in _execute return self._parent.execute(command, params) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 312, in execute self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotInteractableException: Message: Element &lt;input id="selectedFile" name="file" type="file"&gt; is not reachable by keyboard I'm using Python 2.7. Following is the html page. Update: Following code by Ian solved the issue. field = driver.find_element_by_id("selectedFile") driver.execute_script("arguments[0].style.display = 'block';", field) field = driver.find_element_by_id("selectedFile") field.send_keys('/Users/knightfox/Desktop/file.txt')
tagged with: python

http://stackoverflow.com/comment/85578236
type: Comment
has text: You must use a subclass of the django File object, instead of a PIL Image. See this answer for how to save the Image to the correct type using an in-memory BytesIO. https://stackoverflow.com/a/39710093/1977847
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49227183

http://stackoverflow.com/q/49164443
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49164480
has comment: http://stackoverflow.com/comment/85334476
favorite count: 0
type: Question
has body: I am doing a problem, the input is strings: ["abc","bcd","acef","xyz","az","ba","a","z"] The code is listed below. def groupStrings(self, strings): groups = collections.defaultdict(list) for s in strings: tmp=[0]*len(s) for i in range(len(s)): tmp[i]=(ord(s[i])-ord(s[0]))%26 tmptuple=tuple(tmp) groups[tmptuple] += s, return groups.values() So in groups[tmptuple]+=s, if I remove the comma ',' I get [["a","b","c","b","c","d","x","y","z"],["a","c","e","f"],["a","z"],["a","z","b","a"]] instead of [["abc","bcd","xyz"],["acef"],["a","z"],["az","ba"]] The groups just does not add the whole string s, can anyone explain why does the comma make it different and why I could not do it without the comma?
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/2347265
has title: python: what does the comma do in += s,?
tagged with: python
score: 3
upvote count: 3

http://stackoverflow.com/comment/85294355
has text: But you have not made any changes to the original list.. you have gone to a lot of effort to create new lists..
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49144306
score: 0

http://stackoverflow.com/comment/85385051
type: QuestionComment
has text: It's IIS hosting and there should not be any problem for serving multiple web applications from same port. It should work (and it works well for ASP.NET applications). It's something that is wrong in my code / approach above where I need help.
comment on: http://stackoverflow.com/q/49189246
score: 0
type: Comment

http://stackoverflow.com/comment/85266298
type: Comment
has text: @user202729 Because this service will be hosted on servers , which will not be having third party applications
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49130730

http://stackoverflow.com/q/49232866
tagged with: python
has answer: http://stackoverflow.com/a/49235090
possible better answer: http://stackoverflow.com/a/49235090
tagged with: python-3.6
answer count: 4
score: 2
type: AnsweredQuestion
tagged with: tkinter
tagged with: widget
has comment: http://stackoverflow.com/comment/85471973
upvote count: 3
has comment: http://stackoverflow.com/comment/85470129
has comment: http://stackoverflow.com/comment/85471721
downvote count: 1
has answer: http://stackoverflow.com/a/68886192
has answer: http://stackoverflow.com/a/68115815
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49234187
accepted answer: http://stackoverflow.com/a/49234187
has body: I am attempting to make the following code work: It is meant to delete the last character of the text widget named _textBox (as a backspace on a keyboard would usually do)... def addChar(_textBox, char): global charCount if charCount &lt;= 15: if char == "backSpace": _textBox.delete(charCount, END) if charCount != 0: charCount = charCount - 1 else: _textBox.insert(END, char) charCount = charCount + 1 print(charCount) It seems the only problem is the '.delete()' part of the code... Does anybody know how i can use this properly to remove only the last character in the text widget? Thanks in advance :)
has title: How to delete last character in text widget tkinter
has comment: http://stackoverflow.com/comment/85469750

scikit-learn
tags question: http://stackoverflow.com/q/49149075
tags question: http://stackoverflow.com/q/49152607
tags question: http://stackoverflow.com/q/49250151
tags question: http://stackoverflow.com/q/49209949
tags question: http://stackoverflow.com/q/49161133
tags question: http://stackoverflow.com/q/49133188
tags question: http://stackoverflow.com/q/49208617
tag name: scikit-learn
tags question: http://stackoverflow.com/q/49130850
tags question: http://stackoverflow.com/q/49276118
tags question: http://stackoverflow.com/q/49200761
tags question: http://stackoverflow.com/q/49217342
tags question: http://stackoverflow.com/q/49255034
tags question: http://stackoverflow.com/q/49167224
tags question: http://stackoverflow.com/q/49260932
tags question: http://stackoverflow.com/q/49158589
tags question: http://stackoverflow.com/q/49181519
tags question: http://stackoverflow.com/q/49263518
tags question: http://stackoverflow.com/q/49247796
tags question: http://stackoverflow.com/q/49246856
tags question: http://stackoverflow.com/q/49266776
type: Tag
tags question: http://stackoverflow.com/q/49243018
tags question: http://stackoverflow.com/q/49134593
tags question: http://stackoverflow.com/q/49259396
tags question: http://stackoverflow.com/q/49189648
tags question: http://stackoverflow.com/q/49167070
tags question: http://stackoverflow.com/q/49210239
tags question: http://stackoverflow.com/q/49211981
tags question: http://stackoverflow.com/q/49196650
tags question: http://stackoverflow.com/q/49171094
tags question: http://stackoverflow.com/q/49193286
tags question: http://stackoverflow.com/q/49151325
tags question: http://stackoverflow.com/q/49158724
tags question: http://stackoverflow.com/q/49260862
tags question: http://stackoverflow.com/q/49234736
tags question: http://stackoverflow.com/q/49218954
tags question: http://stackoverflow.com/q/49179155
tags question: http://stackoverflow.com/q/49198633
tags question: http://stackoverflow.com/q/49143626
tags question: http://stackoverflow.com/q/49275570
tags question: http://stackoverflow.com/q/49276254
tags question: http://stackoverflow.com/q/49136142
tags question: http://stackoverflow.com/q/49240908
tags question: http://stackoverflow.com/q/49252156
tags question: http://stackoverflow.com/q/49192335
tags question: http://stackoverflow.com/q/49196102
tags question: http://stackoverflow.com/q/49270324
tags question: http://stackoverflow.com/q/49262900
tags question: http://stackoverflow.com/q/49250254
tags question: http://stackoverflow.com/q/49167472
tags question: http://stackoverflow.com/q/49188400
tags question: http://stackoverflow.com/q/49201932
tags question: http://stackoverflow.com/q/49160206
tags question: http://stackoverflow.com/q/49259305
tags question: http://stackoverflow.com/q/49232895
tags question: http://stackoverflow.com/q/49228191
tags question: http://stackoverflow.com/q/49144771
tags question: http://stackoverflow.com/q/49190887
tags question: http://stackoverflow.com/q/49164404
tags question: http://stackoverflow.com/q/49236166
tags question: http://stackoverflow.com/q/49157001
tags question: http://stackoverflow.com/q/49134338
tags question: http://stackoverflow.com/q/49131598
tags question: http://stackoverflow.com/q/49274766
tags question: http://stackoverflow.com/q/49226358
tags question: http://stackoverflow.com/q/49159130
tags question: http://stackoverflow.com/q/49138692
tags question: http://stackoverflow.com/q/49149278
tags question: http://stackoverflow.com/q/49131151
tags question: http://stackoverflow.com/q/49175619
tags question: http://stackoverflow.com/q/49153905
tags question: http://stackoverflow.com/q/49238160
tags question: http://stackoverflow.com/q/49189637
tags question: http://stackoverflow.com/q/49147774
tags question: http://stackoverflow.com/q/49214915
tags question: http://stackoverflow.com/q/49170296
tags question: http://stackoverflow.com/q/49207957
tags question: http://stackoverflow.com/q/49150565
tags question: http://stackoverflow.com/q/49131464

http://stackoverflow.com/comment/85371982
type: Comment
has text: The dll is written in assembler (NASM) which does not have signatures like C -- instead, parameters are passed in registers. I've included it above, but it doesn't reveal the problem.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49181097

http://stackoverflow.com/a/49195063
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49186748
type: Answer
has body: Just enumerate over the document pages (wand.image.Image.sequence) to get the page number &amp; resource. With the page resource copied to a new instance of Image, export blob directly, and don't worry about intermediate conversions. from urllib2 import urlopen from wand.image import Image from io import BytesIO import boto3 # .... url = 'https://s3.us-east-2.amazonaws.com/converted1jpgs/example.pdf' resource = urlopen(url) with Image(file=resource) as document: for page_number, page in enumerate(document.sequence): with Image(page) as img: bytes_io_file = BytesIO(img.make_blob('JPEG')) filename = 'output_{0}.jpg'.format(page_number) s3.upload_fileobj(bytes_io_file, bucket_name, filename)
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49186748
score: 3
downvote count: 0

http://stackoverflow.com/a/49122979
has comment: http://stackoverflow.com/comment/85251479
upvote count: 4
has body: Use a list comprehension as a fast alternative since you're forced to iterate: string = "{0} has size {1}, above the average of {2} type ({3})" df['sentence'] = [string.format(*r) for r in df.values.tolist()] df name size type av_size_type \ 0 John 23 Qapra' 22 1 Dan 21 nuk'neH 12 2 Monica 12 kahless 15 sentence 0 John has size 23, above the average of Qapra' ... 1 Dan has size 21, above the average of nuk'neH ... 2 Monica has size 12, above the average of kahle...
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49122917
accepted answer of: http://stackoverflow.com/q/49122917
type: Answer
score: 4

http://stackoverflow.com/q/49251077
tagged with: flask
tagged with: flask-sqlalchemy
has body: In order to ensure that passwords are always stored, hashed and salted in the database, I decided to use a descriptor which will automatically hash the password when one is provided, e.g user.password = "jinja125". Here is my code from random import SystemRandom from backports.pbkdf2 import pbkdf2_hmac, compare_digest # ...snip... @password.setter def password(self, value): # When a user is first created, give them a salt if self._salt is None: self._salt = bytes(SystemRandom().getrandbits(128)) self._password = self._hash_password(value) However when I try to run some tests, I get this error. File "C:\Users\User\flask-python\site-tracker\app\users\models.py", line 34, in password self._salt = bytes(random.SystemRandom().getrandbits(simple_bit_counts)) OverflowError: cannot fit 'int' into an index-sized integer How can I best fix this error?
type: AnsweredQuestion
answer count: 1
has title: OverflowError: cannot fit 'int' into an index-sized integer
favorite count: 0
type: Question
score: 5
accepted answer: http://stackoverflow.com/a/49251203
has answer: http://stackoverflow.com/a/49251203
upvote count: 5
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/85498541
type: AnswerComment
has text: +100 ! Thanks for the next level follow-through on this one. Never, ever, would have gotten to that myself. Kudos!
comment on: http://stackoverflow.com/a/49244214
score: 1
type: Comment

http://stackoverflow.com/comment/85540333
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49268410
has text: If I use numpy.dot() on two 3x3 matrix I will get a 3x3 resulting matrix, but I'm trying to get the dot product as a scalar value @smci.
score: 0

http://stackoverflow.com/comment/85530488
has text: This is, however, the reason that each method should *return* a value rather than printing a value itself. The caller can always decide whether to print the return value or not; the caller *cannot* "unprint" a value.
type: Comment
comment on: http://stackoverflow.com/a/49262616
score: 0
type: AnswerComment

http://stackoverflow.com/a/49122977
downvote count: 0
answers question: http://stackoverflow.com/q/49122917
has comment: http://stackoverflow.com/comment/85251425
upvote count: 8
score: 8
has body: Use a splat and unpack string = lambda x: "{} has size {}, above the average of {} type ({})".format(*x) df.assign(sentence=df.apply(string, 1)) name size type av_size_type sentence 0 John 23 Qapra' 22 John has size 23, above the average of Qapra' ... 1 Dan 21 nuk'neH 12 Dan has size 21, above the average of nuk'neH ... 2 Monica 12 kahless 15 Monica has size 12, above the average of kahle... If you want, you can use dictionary unpacking string = lambda x: "{name} has size {size}, above the average of {type} type ({av_size_type})".format(**x) df.assign(sentence=df.apply(string, 1)) name size type av_size_type sentence 0 John 23 Qapra' 22 John has size 23, above the average of Qapra' ... 1 Dan 21 nuk'neH 12 Dan has size 21, above the average of nuk'neH ... 2 Monica 12 kahless 15 Monica has size 12, above the average of kahle...
has comment: http://stackoverflow.com/comment/85251391
type: Answer

http://stackoverflow.com/comment/85626989
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49273871
has text: Thanks, I reviewed logic and added `def start_requests(self)` function, also revised `def parse(self, response)` function as advised. Now it works well. Your advice is greatly appreciated.

http://stackoverflow.com/comment/85592711
type: Comment
score: 0
has text: Thank you for detailed reply. I will try and get back to you.
type: AnswerComment
comment on: http://stackoverflow.com/a/49284451

http://stackoverflow.com/a/49189522
has body: Add the following to settings.py: AUTH_USER_MODEL = "users_management.UserManage" More generally, AUTH_USER_MODEL = 'YourAppName.YourClassName' YourAppName: This is the name of the app that will have the User Model YourClassName: This is the name of the class used inside the models.py file
has comment: http://stackoverflow.com/comment/107863183
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49189402
score: 331
has comment: http://stackoverflow.com/comment/121636406
accepted answer of: http://stackoverflow.com/q/49189402
type: Answer
has comment: http://stackoverflow.com/comment/107861607
has comment: http://stackoverflow.com/comment/104123253
upvote count: 331

http://stackoverflow.com/comment/85435362
type: QuestionComment
comment on: http://stackoverflow.com/q/49213440
has text: I posted on the [mailing list](https://mail.gnome.org/archives/python-hackers-list/2018-March/msg00001.html).
score: 0
type: Comment

http://stackoverflow.com/a/49299088
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49266584
answers question: http://stackoverflow.com/q/49266584
type: Answer
has body: In your app.yaml file, when running gunicorn, you have to indicate the name of the flask class of your web app. Here, under deployment, you can find some different options to deploy a Flask-SocketIO server. You should replace entrypoint: gunicorn -b :$PORT web_app:socketio for entrypoint: gunicorn -b :$PORT web_app:app

http://stackoverflow.com/q/49203019
type: Question
has comment: http://stackoverflow.com/comment/85414345
has body: I have a model which takes three variable-length inputs with the same label. Is there a way I could use pack_padded_sequence somehow? If so, how should I sort my sequences? For example, a = (([0,1,2], [3,4], [5,6,7,8]), 1) # training data is in length 3,2,4; label is 1 b = (([0,1], [2], [6,7,8,9,10]), 1) Both a and b will be fed into three separated LSTMs and the result will be merged to predict the target.
answer count: 2
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/99786108
has comment: http://stackoverflow.com/comment/100719477
tagged with: python
possible better answer: http://stackoverflow.com/a/55759380
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55759380
has title: How to use pack_padded_sequence with multiple variable-length input with the same label in pytorch
tagged with: pytorch
downvote count: 0
accepted answer: http://stackoverflow.com/a/49204483
has answer: http://stackoverflow.com/a/49204483
tagged with: torch
favorite count: 0

http://stackoverflow.com/comment/89159026
has text: Alright. I'm not sure what's wrong, or what is the "source ID" you mention, but you could try having the same capabilities on both sides, and expliciting the host address to listen at
type: Comment
comment on: http://stackoverflow.com/a/50741905
type: AnswerComment
score: 0

http://stackoverflow.com/a/49252743
answers question: http://stackoverflow.com/q/49252543
has comment: http://stackoverflow.com/comment/85509982
has body: writefile = open(str(SNumber)+'.txt','a') If the file does not exists, open(name,'r+') will fail. You can use open(name, 'w'), which creates the file if the file does not exist, but it will truncate the existing file. Alternatively, you can use open(name, 'a'); this will create the file if the file does not exist, but will not truncate the existing file. import sys import random def create(): SNumber=random.randint(199999,999999) try: writefile = open(str(SNumber)+'.txt','a') writefile.write(SNumber) writefile.close() except: print("Error occurred.") sys.exit(0) create()
has comment: http://stackoverflow.com/comment/85510550
type: Answer
has comment: http://stackoverflow.com/comment/85510431
has comment: http://stackoverflow.com/comment/85509836
has comment: http://stackoverflow.com/comment/85509937
score: 0

newrelic
tag name: newrelic
type: Tag
tags question: http://stackoverflow.com/q/49203954

dot-product
tags question: http://stackoverflow.com/q/49259197
tag name: dot-product
type: Tag

http://stackoverflow.com/a/49273087
type: Answer
answers question: http://stackoverflow.com/q/49205223
score: 0
has body: Asked my friend for help on this matter as he's a python dev! So he said anaconda latest on windows is unstable and recommended to use anaconda on Linux. So i tried in Fedora workstation and then i didn't face any problem.

http://stackoverflow.com/a/49190851
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49190523
type: Answer
answers question: http://stackoverflow.com/q/49190523
score: 0
has body: I don't know Zope, but it looks like you're in Unix, so if you installed Python through apt, dnf, etc...: The symbolic link to Python is usually installed in /usr/bin. If you search by "python" in that folder you should find all the python available for you. If you are looking for the headers in /usr/include you should have a folder for each version of Python installed. And you say: "I am not sure where to install Python 2.4.3 though". If you're installing Python from source it will be installed in your local folder: /usr/local/bin (for symbolic link) and /usr/local/include for headers. Also, make sure to enable symbolic links when compiling. If I'm not wrong in the ./configure step, you can use ./configure --enable-shared to make sure that when you compile the source code it will installs you a symbolic link for that version in you /usr/local/bin

amazon-web-services
tags question: http://stackoverflow.com/q/49268374
tags question: http://stackoverflow.com/q/49210649
tags question: http://stackoverflow.com/q/49133225
tags question: http://stackoverflow.com/q/49224945
tags question: http://stackoverflow.com/q/49177491
tags question: http://stackoverflow.com/q/49198057
tags question: http://stackoverflow.com/q/49163099
tags question: http://stackoverflow.com/q/49224322
tags question: http://stackoverflow.com/q/49123105
tags question: http://stackoverflow.com/q/49200010
tags question: http://stackoverflow.com/q/49257972
tags question: http://stackoverflow.com/q/49186748
tags question: http://stackoverflow.com/q/49171093
tags question: http://stackoverflow.com/q/49210622
tags question: http://stackoverflow.com/q/49219686
tags question: http://stackoverflow.com/q/49196837
tags question: http://stackoverflow.com/q/49144110
type: Tag
tags question: http://stackoverflow.com/q/49222171
tags question: http://stackoverflow.com/q/49151938
tags question: http://stackoverflow.com/q/49180038
tags question: http://stackoverflow.com/q/49148771
tags question: http://stackoverflow.com/q/49220475
tag name: amazon-web-services
tags question: http://stackoverflow.com/q/49176476
tags question: http://stackoverflow.com/q/49255529
tags question: http://stackoverflow.com/q/49160890
tags question: http://stackoverflow.com/q/49150673
tags question: http://stackoverflow.com/q/49260369

http://stackoverflow.com/q/49161895
accepted answer: http://stackoverflow.com/a/49161922
has body: Just quick info I'm a beginner in python and django. Here is an issue: I'm trying to create simple blog app with django, I've created all whats needed and I'm able to render one of my main pages however when I try to access posts page(to be able to view current posts) I receive the following error: Request Method: GET Request URL: http://localhost:8000/posts/ Django Version: 2.0.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'post' not found. 'post' is not a valid view function or pattern name. I'm not sure why I receive this error as I have posts view function written and accessible, here are my files: my_blog/urls.py """Defines URL patterns for my_blog.""" from django.conf.urls import url from . import views #needed app name app_name='my_blog' urlpatterns=[ #Homepage url(r'^$',views.home,name='home'), # Show all posts. url(r'^posts/$', views.posts, name='posts'), models.py from django.db import models # Create your models here. class BlogPost(models.Model): """Post that can be viewed""" title=models.CharField(max_length=200) text=models.TextField() date_added=models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" if len(self.text)<50: return self.text else: return self.text[:50] + "..." views.py from django.shortcuts import render from .models import BlogPost from django.http import HttpResponseRedirect # Create your views here. def home(request): """The home page for Learning Log""" return render(request,'my_blog/home.html') def posts (request): """Show all posts.""" posts=BlogPost.objects.order_by('date_added') context={'posts':posts} return render(request, 'my_blog/posts.html', context) HTML pages: home.html {%extends "my_blog/base.html"%} {%block content%} Welcome to my Blog {%endblock content%} base.html My Blog Home - Posts {%block content%}{%endblock content%} posts.html {%extends "my_blog/base.html"%} {%block content%} Posts {%for post in posts%} {{post}} {%empty%} No posts have been add…
possible better answer: http://stackoverflow.com/a/49162151
has title: NoReverseMatch at /posts/
has answer: http://stackoverflow.com/a/49161922
tagged with: django-templates
tagged with: django-views
has answer: http://stackoverflow.com/a/49162151
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: django
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: exception
tagged with: python

http://stackoverflow.com/comment/85531561
score: 0
type: Comment
type: QuestionComment
has text: @PangeranBottor I cannot seem to understand what are you doing with the code you just typed in. How does this help ?
comment on: http://stackoverflow.com/q/49263903

http://stackoverflow.com/comment/85381833
type: QuestionComment
comment on: http://stackoverflow.com/q/49188289
has text: [Please do not tag multiple languages in your question](https://meta.stackoverflow.com/questions/354931/when-is-it-appropriate-to-tag-multiple-languages-in-my-question/) unless your question is specifically about these languages. You may think it will lead to a faster answer, but the reality is that it is more likely to lead to a faster closure.
score: 0
type: Comment

http://stackoverflow.com/comment/85440241
type: QuestionComment
has text: Please don't post pictures of code or error messages, post the text here on SO instead.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49218044

http://stackoverflow.com/comment/85290651
type: Comment
type: QuestionComment
has text: `type` is the base metaclass in Python. (Every class is an object, and a class's class is its metaclass.) You shouldn't subclass `type` unless you are intentionally trying to create a metaclass.
score: 5
comment on: http://stackoverflow.com/q/49142505

http://stackoverflow.com/q/49178434
has comment: http://stackoverflow.com/comment/85363297
tagged with: python
has answer: http://stackoverflow.com/a/49197956
has comment: http://stackoverflow.com/comment/85363277
accepted answer: http://stackoverflow.com/a/49197956
type: AnsweredQuestion
score: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85362423
has comment: http://stackoverflow.com/comment/85363709
answer count: 1
has comment: http://stackoverflow.com/comment/85363515
has comment: http://stackoverflow.com/comment/85362475
has comment: http://stackoverflow.com/comment/85362294
has comment: http://stackoverflow.com/comment/85363073
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85365467
has body: I have a problem: a function must create a file and write into it a word when I left-click on the word and also this function must check if this word already exists in the file, but file not create and write Here's the code I have so far: def f_save_word_to_file(word): if word not in [ x.strip() for x in open(os.path.expanduser (save_word_to_file_fname)).readlines() ]: print(word, file = open(os.path.expanduser (save_word_to_file_fname), 'a')) variable: save_word_to_file_fname = '~/saved_words' os.path library connected import os, subprocess, sys Another function that that's invoked by a right mouse button click works without a problem (I've tried to swap these functions but it didn't solve my problem). I've tired changing the path, creating the file myself, changing the fileright with 777 but nothing worked. Maybe anyone here knows where the mistake is?
has title: Not create and write into file, Python-3

http://stackoverflow.com/a/49261879
type: Answer
accepted answer of: http://stackoverflow.com/q/49261490
answers question: http://stackoverflow.com/q/49261490
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has body: I think this does what you are looking for: import datetime def timerange(a): return str(datetime.datetime.strptime(a, '%H:%M:%S') - datetime.timedelta(minutes=10))[-8:] + '-' + a df['TIME_BIN'] = df['TIME_BIN'].apply(timerangeange)

http://stackoverflow.com/comment/85256015
has text: Thanks, I don't have syntax highlighting on my editor, so little things like this don't get noticed. But thanks for the help :)
type: Comment
comment on: http://stackoverflow.com/q/49125636
type: QuestionComment
score: 0

http://stackoverflow.com/a/71269514
answers question: http://stackoverflow.com/q/49203507
score: 0
type: Answer
has body: The performance is not optimal but this is what I ended up doing: xr_dataset = xr.merge([ xr_dataset.categorical_variable.groupby('grouping_variable').first(), xr_dataset.continuous_variable.groupby('grouping_variable').mean(), ... ])

sframe
tags question: http://stackoverflow.com/q/49189054
type: Tag
tag name: sframe

http://stackoverflow.com/comment/85346546
comment on: http://stackoverflow.com/a/49170268
has text: ValueError: Some of types cannot be determined by the first 100 rows, please try again with sampling after running data3= spark.createDataFrame(input_data,["label","features"])
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/124360604
comment on: http://stackoverflow.com/a/70330735
score: 0
has text: You're sorting the array up to N times, so your time complexity is O(n^2 * log n), a long way off the mark!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85591444
has text: [That](https://stackoverflow.com/revisions/49271832/4)'s an _entirely_ different issue than the initial question. You should ask separately if so, as opposed to editing the initial question. Rolled back.
type: QuestionComment
comment on: http://stackoverflow.com/q/49271832
type: Comment
score: 0

http://stackoverflow.com/q/49247739
has answer: http://stackoverflow.com/a/49247847
has body: So I tried playing around with multiple options to set values of multiple cells in Pandas using a list but not able to get the right results. Searched here and on Google with no luck. Here is my sample df df = pd.DataFrame({'PersonID':['AB-123', 'AB-123', 'AB-123', 'AB-123', 'AB-123'], 'Date':['2/1/2016', '2/2/2016', '2/3/2016', '2/4/2016', '2/5/2016']}) df['Score']='' I am triying to add value in middle of the 'Score' column and tried following ways; Option 1: Using set_value df = df.set_value([3:5],'Score',[3,4,5]) Doesn't work because of the slicing and the list of values. Option 2: df.loc[3:5,'Score']=[3,4,5] same problem as above Option 3: df[df.index[3:5]]['Score']=[3,4,5] None of the above methods works. Does anyone know anyway that this could work out?
tagged with: python
possible better answer: http://stackoverflow.com/a/49247911
type: AnsweredQuestion
score: 2
answer count: 2
has answer: http://stackoverflow.com/a/49247911
upvote count: 2
tagged with: pandas
has title: Pandas set value range of cell with list
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49247847

http://stackoverflow.com/q/49210436
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49211055
has body: The problem (Story): I write inside an entry widget, then I press a button and a new label appear in the window with the text that I have entered. Then I press a different button and the expecting result is that the generated label disappear but, I receive an error message. Why do I want to do this? I want to make an interface to make SQL queries, the process that I'm trying to implement is: The user enters a string in an entry widget. The user presses a "search" button to perform the query. The interface returns the results. (I have achieved this using LabelFrame and Frame widgets). The user presses a "clear" button and all the widgets generated disappear and the interface is ready for a new query. The label that doesn't hide(code): from tkinter import * root = Tk() pacienteLabel = Label(text="Paciente: ") pacienteLabel.grid() pacienteEntry = Entry() pacienteEntry.grid() profesionalLabel = Label(text="Profesional: ") profesionalLabel.grid() profesional = StringVar() # Here I capture the string that I want to show: profesionalEntry = Entry(textvariable=profesional) profesionalEntry.grid() def ver(): # This label is generated without problems: newLabel = Label(text="hola profesional: {}".format(profesional.get())) newLabel.grid() # When I was trying to figure out what was happening I added this: print(newLabel) # And the output is: # .!label4 # I have read through documentation why is this but I couldn't find why. buscarButton = Button(text="Buscar", command=ver) buscarButton.grid() def borrar(): # After that I saw the previous output from print was obvious why the # next line don't work: newLabel.grid_forget() borrarButton = Button(text="Borrar", command=borrar) borrarButton.grid() root.mainloop() The following picture shows the error and the GUI: In the end, what have I read here: Hide label when a button is clicked in Python In Tkinter is there any way to make a widget not visible? Finally if you are reading this question, thanks for your time!
has answer: http://stackoverflow.com/a/49211055
linked to: http://stackoverflow.com/q/27654494
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85431622
has comment: http://stackoverflow.com/comment/85426126
tagged with: user-interface
has title: How hide a label that was generated with a command button, using another button?
score: 1
favorite count: 0
type: Question
tagged with: python-3.x
linked to: http://stackoverflow.com/q/3819354
tagged with: tkinter
linked to: http://stackoverflow.com/q/6920302
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85468541
has text: Confirmed, it works, thank you very much! Sadly A() or B() remain unresolved references in my editor, but that is another question.
score: 0
comment on: http://stackoverflow.com/a/49173430
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85520695
type: QuestionComment
comment on: http://stackoverflow.com/q/49258228
score: 0
has text: Yes I print(sys.path) and I see the first item is my root `/Users/myname/project/core`.
type: Comment

http://stackoverflow.com/comment/85399244
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49197079
has text: `val = 1` is a local, rather than a class attribute - it also has the 'wrong' name. I think you mean `self._val = 1` and `return self._val`

http://stackoverflow.com/a/49173959
has body: I think you are trying to write this class: class Menu_choice(): def login(self): print("Login") def register(self): pring("Register") def __init__(self, choice): self.choice = choice if self.choice == "LOGIN": self.login() if self.choice == "REGISTER": self.register() But as others have pointed out, this class as such does not make any sense. I think you want something like this: class Menu_choice(): def __init__(self): pass def login(self): print("Login") def register(self): print("Register") def __call__(self, choice): self.choice = choice if self.choice == "LOGIN": self.login() if self.choice == "REGISTER": self.register() choice = input("Would you like to login or register?: ").upper() m = Menu_choice() m(choice) You can make an instatiate your class as m but also define a __call__() funtion which will be executed when you call the instance like m(choice)
has comment: http://stackoverflow.com/comment/85359002
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49173633
answers question: http://stackoverflow.com/q/49173633
type: AcceptedAnswer

http://stackoverflow.com/comment/85331327
type: Comment
has text: Hi @johnashu! I'm trying only to open the broser by running webdriver.Firefox(executable_path="/usr/local/bin/geckodriver"). I think that in order to open a website one has to run driver.get().. but, as written in the question above, I'm a newbie both in python and in using the selenium package..
comment on: http://stackoverflow.com/q/49141621
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85399572
has text: Show a [mcve] in both matlab and python if you need help
comment on: http://stackoverflow.com/q/49197287
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85504975
comment on: http://stackoverflow.com/q/49250200
has text: Could you please give a link to the examples?
score: 1
type: Comment
type: QuestionComment

tex
tags question: http://stackoverflow.com/q/49198719
tag name: tex
type: Tag

http://stackoverflow.com/q/49218366
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85441340
has comment: http://stackoverflow.com/comment/85440578
has comment: http://stackoverflow.com/comment/85441299
linked to: http://stackoverflow.com/q/45460145
type: UnansweredQuestion
tagged with: matplotlib
tagged with: django
tagged with: python
has title: Django - how to best integrate matplotlib
has comment: http://stackoverflow.com/comment/85441281
has comment: http://stackoverflow.com/comment/85441322
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85441260
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49218825
has comment: http://stackoverflow.com/comment/85464785
has body: I am trying to display a graph using matplotlib and django. I've read quite a lot of questions on stack but still don't understand what the best way is to use matplotlib in Django. SITUATION: I have a model that has a bunch of data in. In views.py I then have a simple form that captures some data and queries the model and returns a subset of the data. Here is the relevant views.py section: def getinput(request): if request.method == 'POST': form = get_data(request.POST) if form.is_valid(): down = form.cleaned_data['get_down'] ytg = form.cleaned_data['get_ytg'] yfog = form.cleaned_data['get_yfog'] map_data = next_play.objects.filter(last_dwn__exact=down, last_yfog__exact=yfog, last_ytg__exact=ytg) context = {'form': form, 'query_data': map_data} return render(request, 'play_outcomes/output.html', context) else: form = get_data() return render(request, 'play_outcomes/getinput.html', {'form': form}) When I got to play_outcomes/getinput and enter dwn ytg yfog the template then outputs a whole ton of data. It is this data I want to plot i.e., the data in map_data. QUESTION: How do I integrate matplotlib into this? Do I integrate the matplotlib code in views.py, should I set it up in a separate python module? Presumably I need to create a png file and then show that?

http://stackoverflow.com/comment/85551757
type: Comment
has text: @VPfB That's why it does not make sense ot import `A.py`. It just import `main` from a different module and calls it. If you want to use `main` there is no point in messing with `A.py`, go directly for the module that defines it.
type: AnswerComment
comment on: http://stackoverflow.com/a/49236224
score: 0

http://stackoverflow.com/a/49209424
type: Answer
has body: Spark will parallelize for you as long as you use a RDD or Spark data frame not data frame. will be single threaded. Just UDF operation to define your function.
score: 0
answers question: http://stackoverflow.com/q/49184050
has comment: http://stackoverflow.com/comment/85817420

http://stackoverflow.com/comment/85478095
type: AnswerComment
has text: @cdt This is why I made `list_generator` an iterator. You can read lines from the file and yield them one by one, using the fact that the file object you get from `open()` already is an iterator over the file's lines.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49208116

http://stackoverflow.com/comment/85520199
type: Comment
comment on: http://stackoverflow.com/a/49258468
type: AnswerComment
has text: `any([elem in s for elem in stop_list])` => `any(elem in s for elem in stop_list)` no need to create a list.
score: 0

http://stackoverflow.com/q/49223219
tagged with: numpy
accepted answer: http://stackoverflow.com/a/49246499
has answer: http://stackoverflow.com/a/49246499
has comment: http://stackoverflow.com/comment/85456904
tagged with: python
has comment: http://stackoverflow.com/comment/85456760
score: -1
has title: Efficient matrix update and matrix multiplication using Scipy sparse matrix
tagged with: sparse-matrix
has body: I have a large matrix (236680*236680), and my pc does not have sufficient memory to read in the complete matrix so that I am thinking the Scipy sparse matrix. My goal is to multiply a generated matrix (not sparse) by np.eye(the number of observation)-np.ones(the number of observation)/the number of observation with a sparse matrix. In Scipy, I use the following code, but the computation is still huge. My questions include: to generate the first matrix, is there any other way to speed the process? for the matrix multiplication, is there any way to reduce the memory usage, as the first matrix is not sparse? - from scipy.sparse import lil_matrix fline=5 nn=1/fline M=lil_matrix((fline,fline)) M.setdiag(values=1-nn,k=0) for i in range(fline)[1:]: M.setdiag(values=0-nn,k=i) M.setdiag(values=0-nn,k=-i) #the first matrix is: array([[ 0.8, -0.2, -0.2, -0.2, -0.2], [-0.2, 0.8, -0.2, -0.2, -0.2], [-0.2, -0.2, 0.8, -0.2, -0.2], [-0.2, -0.2, -0.2, 0.8, -0.2], [-0.2, -0.2, -0.2, -0.2, 0.8]]) #the second matrix is: array([[0., 0., 0., 1., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 0.], [1., 0., 1., 0., 0.]]) a2=M.dot(B) #the final expected results array([[-0.2, 0. , -0.2, 0.6, 0. ], [-0.2, 0. , -0.2, -0.4, 0. ], [-0.2, 0. , -0.2, 0.6, 0. ], [-0.2, 0. , -0.2, -0.4, 0. ], [ 0.8, 0. , 0.8, -0.4, 0. ]]) Updated: is there any way to improve the speed of the cross product? Numpy dot and Scipy sparse dot functions are tested.
type: AnsweredQuestion
answer count: 2
possible better answer: http://stackoverflow.com/a/49226994
upvote count: 0
has comment: http://stackoverflow.com/comment/85456846
has answer: http://stackoverflow.com/a/49226994
downvote count: 1
has comment: http://stackoverflow.com/comment/85450532
tagged with: scipy
favorite count: 0
has comment: http://stackoverflow.com/comment/85456893
type: Question

http://stackoverflow.com/q/49142522
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85290712
has comment: http://stackoverflow.com/comment/85290670
possible better answer: http://stackoverflow.com/a/49142592
has comment: http://stackoverflow.com/comment/85290758
tagged with: setter
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85290740
tagged with: getter
tagged with: properties
has answer: http://stackoverflow.com/a/49142616
type: AnsweredQuestion
upvote count: 0
linked to: http://stackoverflow.com/q/1554546
answer count: 2
has comment: http://stackoverflow.com/comment/85290729
has comment: http://stackoverflow.com/comment/85290724
has comment: http://stackoverflow.com/comment/85290747
downvote count: 1
linked to: http://stackoverflow.com/q/1568091
has answer: http://stackoverflow.com/a/49142592
accepted answer: http://stackoverflow.com/a/49142616
has body: im a new python programmer and I recently started learning about @property and the @setter decorators in python. However I am confused about their use in the simplest scripts for example: class Aaron: def __init__(self,name): self.name = name @property def name(self): return self._name @name.setter def name(self,new): self._name = new what is the use of setters and getters?, any help is appreciated Thanks
duplicate of: http://stackoverflow.com/q/1554546
has title: Confused about setters and getters

http://stackoverflow.com/q/49185727
has answer: http://stackoverflow.com/a/49185833
duplicate of: http://stackoverflow.com/q/21592630
has comment: http://stackoverflow.com/comment/85377447
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85389726
tagged with: tkinter-entry
has title: python tkinter use button function to show string on entry
downvote count: 2
tagged with: tkinter
has body: Intro: I want to use a button to get file path, then display the path on the entry Question: I don't know how to display path on the entry, I search and try a lot yesterday, but all the things I try didn't work. I don't know which part is wrong, hope u can help me, thanks a lot. My code here: class PageOne(tk.Frame): def __init__(self, parent, controller): ttk.LabelFrame.__init__(self, parent,text='video detection') self.grid(column=0, row=0, padx=10, pady=10) ttk.Label(self, text="video addr：").grid(column=0, row=0, padx=3, pady=5) self.entry_1 = ttk.Entry(self).grid(column=1, row=0, padx=3, pady=3) ttk.Button(self, text='select', width=8, command = lambda: self.vid_sel_btn()).grid(column=2, row=0, padx=5, pady=5) def vid_sel_btn(self): path = filedialog.askopenfilename() self.entry_1.insert(0,select_path)
has comment: http://stackoverflow.com/comment/85379539
has comment: http://stackoverflow.com/comment/85377630
upvote count: 1
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/21592630
answer count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/85408757
has text: sorry my base case would return the total of lst[0]+lst[0]
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49201719
type: AnswerComment

http://stackoverflow.com/q/49263547
has answer: http://stackoverflow.com/a/49267139
has answer: http://stackoverflow.com/a/67923255
type: UnansweredQuestion
downvote count: 0
tagged with: django
has title: Python 3 Timedelta OverflowError
favorite count: 0
type: Question
upvote count: 8
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/65523707
has answer: http://stackoverflow.com/a/73332602
answer count: 4
score: 8
has comment: http://stackoverflow.com/comment/85530944
tagged with: python-3.x
has body: I have a large database that I am loading into an in-memory cache. I have a process that does this iterating through the data day by day. Recently this process has started throwing the following error: OverflowError: date value out of range for the line start_day = start_day - datetime.timedelta(days = 1) This is running in Python 3.4.3 on Ubuntu 14.04.5
tagged with: overflow
has comment: http://stackoverflow.com/comment/85531530

http://stackoverflow.com/comment/85384764
score: 0
comment on: http://stackoverflow.com/q/49179052
has text: To clarify, what does `main()` do? Is it _just_ to initialise this variable? Or does it do other stuff too?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85316876
comment on: http://stackoverflow.com/q/49155950
score: 1
has text: What do you want to achieve in the end?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85422216
comment on: http://stackoverflow.com/q/49208794
score: 0
type: Comment
type: QuestionComment
has text: @jonrsharpe : why does this work then '[dict(zip(l1, l2))[x] for x in rawdata]' ?? Sorry i dint actually get what you are tying to say. :(

http://stackoverflow.com/q/49245618
type: UnansweredQuestion
tagged with: web
tagged with: forms
has answer: http://stackoverflow.com/a/55193029
has body: I'm kinda new to django, I need to set a dynamic initial value to my modelform field. I have a database field in my model name 'author' it has a foreignkey that connects it to the django user model. I need to automatically set this to the current user anytime a user fills in information into the form. from what I gathered about this problem, I'd have to define an __init__ function inside the MyHouseEditForm below, I'm new to django and all the examples I've seen a pretty confusing. forms.py from django import forms from django.contrib.auth.models import User from .models import Myhouses class MyHouseEditForm(forms.ModelForm): class Meta: model = Myhouses fields = ('author','name_of_accomodation', 'type_of_room', 'house_rent', 'availability', 'location', 'nearest_institution', 'description', 'image') i need to set the value of 'author' to the current user anytime a user logs in. models.py from django.db import models from django.contrib.auth.models import User class Myhouses(models.Model): author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='author') Available = 'A' Not_Available = 'NA' Availability = ( (Available, 'Available'), (Not_Available, 'Not_Available'), ) name_of_accomodation = models.CharField(max_length=200) type_of_room = models.CharField(max_length=200) house_rent = models.IntegerField(null=True) availability = models.CharField(max_length=2, choices=Availability, default=Available,) location = models.CharField(max_length=200) nearest_institution = models.CharField(max_length=200) description = models.TextField(blank=True) image = models.ImageField(upload_to='profile_image') def __str__(self): return self.name_of_accomodation views.py @login_required def addlisting(request): if request.method == 'POST': form = MyHouseEditForm(request.POST, files=request.FILES) if form.is_valid(): Houses = form.save(commit=False) Houses.save() return redirect('addlisting') else: form = MyHouseEditForm() return render(request, 'ho…
upvote count: 3
has comment: http://stackoverflow.com/comment/85496093
answer count: 2
downvote count: 0
tagged with: django
has title: How to set dynamic initial values to django modelform field
favorite count: 0
type: Question
score: 3
has answer: http://stackoverflow.com/a/53758576
tagged with: python

http://stackoverflow.com/comment/85506285
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49251400
has text: @YiyueWang updated my answer, let me know if that works for you
score: 0

http://stackoverflow.com/comment/85421068
type: Comment
type: AnswerComment
has text: Sorry, but it doesn't seem to work. Using the python profile, the TLE is because of reading the input. Reading 50k times takes 0.9 second... I guess python might not be the way to do it, sorry. Thanks for your solution though.
comment on: http://stackoverflow.com/a/49208102
score: 0

http://stackoverflow.com/a/49168172
downvote count: 0
upvote count: 1
has body: The Authorization: &lt;type&gt; &lt;credentials&gt; pattern was introduced by the W3C in HTTP 1.0, and has been reused in many places since. Many web servers support multiple methods of authorization. In those cases sending just the token isn't sufficient. Sites that use the Authorization : token cn389ncoiwuencr format are most likely implementing OAuth 2.0 tokens.The OAuth 2.0 Authorization Framework sets a number of other requirements to keep authorization secure, for instance requiring the use of HTTPS/TLS. For more explantion: Token Based Authentication Having to send the username and the password with every request is inconvenient and can be seen as a security risk even if the transport is secure HTTP, since the client application must have those credentials stored without encryption to be able to send them with the requests. An improvement over the previous solution is to use a token to authenticate requests. The idea is that the client application exchanges authentication credentials for an authentication token, and in subsequent requests just sends this token. Tokens are usually given out with an expiration time, after which they become invalid and a new token needs to be obtained. The potential damage that can be caused if a token is leaked is much smaller due to their short life span.
type: Answer
answers question: http://stackoverflow.com/q/49167705
has comment: http://stackoverflow.com/comment/85348775
score: 1

http://stackoverflow.com/q/49174302
tagged with: python
has answer: http://stackoverflow.com/a/49174649
tagged with: pandas
score: 3
upvote count: 3
tagged with: matplotlib
has answer: http://stackoverflow.com/a/49174980
has body: I'm having some issues with tick marks disappearing when I apply a locator and formatter to them. I want a plot with multiple subplots that share the same x axis, so only the bottom subplot would have the labels, but all subplots should have labels. Below is an example: import matplotlib.pyplot as plt import numpy as np import pandas as pd import datetime import matplotlib.dates as mdates df = pd.DataFrame(np.absolute(np.random.randn(100)), index=pd.date_range('1/1/2000', periods=100, freq='M')) fig, axes = plt.subplots(2,1,sharex=True,figsize=(8,10),dpi=300,tight_layout=True) df.plot.area(ax=axes[1],legend=False) So far so good. Looking at the fig at this point, you can see ticks and year labels. (Note I'm just adding one plot in this example, but the behavior is the same if I have multiple plots and multiple columns.) But I'd like to place ticks at every month, like this example . years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month yearsFmt = mdates.DateFormatter('%Y') for ax in axes: ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) ax.xaxis.set_minor_locator(months) When I do that, things get weird: See image Any ideas?
has comment: http://stackoverflow.com/comment/85353680
favorite count: 0
type: Question
has title: Pandas/Matplotlib date tick marks disappear in subplots
answer count: 2
type: UnansweredQuestion
downvote count: 0

cx-freeze
tags question: http://stackoverflow.com/q/49203133
tag name: cx-freeze
tags question: http://stackoverflow.com/q/49233110
tags question: http://stackoverflow.com/q/49258897
tags question: http://stackoverflow.com/q/49200832
type: Tag
tags question: http://stackoverflow.com/q/49257372

http://stackoverflow.com/q/49179347
has title: publish multiple values to thingspeak using MQTT
type: Question
has answer: http://stackoverflow.com/a/49181931
tagged with: mqtt
tagged with: http://stackoverflow.com/tag/json
tagged with: python
score: 0
type: UnansweredQuestion
has body: I am trying to publish a multiple random data using mqtt to send data from raspberry pi to thingspeaks. i want to publish the 10 values of temp to thingspeaks field but it limits me to one value every 15 seconds. so is there anyway to send a list of values every 15 second to graph it with time in thingspeaks channels?? temp = [] current = [] while(1): # get the system performance data over 20 seconds. for i in range(10): temp.append(random.randint(0, 100)) current.append(random.randint(0, 100)) # build the payload string. payload = "field1=" + str(temp) + "&amp;field2=" + str(current) # attempt to publish this data to the topic. try: publish.single(topic, payload, hostname=mqttHost, transport=tTransport, port=tPort,auth={'username':mqttUsername,'password':mqttAPIKey}) print (" Published temp =",temp," current =", current," to host: " , mqttHost , " clientID= " , clientID) except (KeyboardInterrupt): break except: print ("There was an error while publishing the data.") time.sleep(15)
answer count: 1

http://stackoverflow.com/q/49122089
has answer: http://stackoverflow.com/a/49122122
type: Question
has comment: http://stackoverflow.com/comment/85249825
score: 0
has answer: http://stackoverflow.com/a/49122123
has body: I have two arrays that need to be combined into a single array by adding the together the values from each array. a = [1, 2, 3, 4, 5] b = [1, 2, 3, 4, 5] x = np.sum(a, b) the result I want is: x = [2, 4, 6, 8, 10] then to be able to calculate the average of each value to get results: x = [1, 2, 3, 4, 5] When I run that, it returns the error TypeError: 'list' object cannot be interpreted as an integer
tagged with: python
type: AnsweredQuestion
answer count: 2
has title: Adding together values in 2 different arrays to calculate an average python
possible better answer: http://stackoverflow.com/a/49122122
accepted answer: http://stackoverflow.com/a/49122123

http://stackoverflow.com/comment/85515426
type: Comment
has text: It seems that your problem isn't making your program _stop_ but keeping it _running_ long enough. Do you know that the program exits when the main thread exits? Your main thread exits almost instantly, all it does is write the single string in `log` to a file and then it's done. Perhaps you want to consider join()ing your threads.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49254722

http://stackoverflow.com/q/49263964
answer count: 1
downvote count: 0
has body: I'm using surprise to perform a cross validation def cross_v(data, folds=5): algorithms = (SVD, KNNBasic, KNNWithMeans, NormalPredictor) measures = ['RMSE', 'MAE'] for a in algorithms: data.split(folds); algo = a(); algo.fit(data) I call the function this way data = Dataset.load_builtin('ml-100k') multiple_cv(data) and I get this error Traceback (most recent call last): File "/home/user/PycharmProjects/pac1/prueba.py", line 30, in &lt;module&gt; multiple_cv(data) File "/home/user/PycharmProjects/pac1/prueba.py", line 19, in multiple_cv algo.fit(data) File "surprise/prediction_algorithms/matrix_factorization.pyx", line 155, in surprise.prediction_algorithms.matrix_factorization.SVD.fit File "surprise/prediction_algorithms/matrix_factorization.pyx", line 204, in surprise.prediction_algorithms.matrix_factorization.SVD.sgd AttributeError: 'DatasetAutoFolds' object has no attribute 'global_mean' I missed something??
favorite count: 0
has title: DatasetAutoFolds' object has no attribute 'global_mean' on python surprise
score: 14
has answer: http://stackoverflow.com/a/49869604
tagged with: python
tagged with: recommendation-engine
type: Question
upvote count: 14
type: UnansweredQuestion

http://stackoverflow.com/comment/85278328
comment on: http://stackoverflow.com/q/49136427
has text: My answer should be 11: 2+2+2+5 (weight of node b is 5)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49191549
has comment: http://stackoverflow.com/comment/85388052
type: AcceptedAnswer
has body: What you look for is np.isclose: np.where(np.isclose(x, y))
score: 13
accepted answer of: http://stackoverflow.com/q/49191460
answers question: http://stackoverflow.com/q/49191460
type: Answer
upvote count: 13
downvote count: 0

http://stackoverflow.com/q/49231942
type: Question
has title: how I can connect to compose for rabbitMQ(IBM) with python and amps
has comment: http://stackoverflow.com/comment/89447738
tagged with: python
tagged with: rabbitmq
score: 0
answer count: 0
tagged with: ibm-cloud
has comment: http://stackoverflow.com/comment/89447920
type: UnansweredQuestion
has body: I have a cloudant with python, compose for rabbitMq, and program in python to link with this queue. Ok, for amqp in rabbitmq, I get all correctly working. but compose for rabbitmq use amqps, and I have problem to connect this mq. I reading many post for making security in rabbit and more another post. but I have not connect to mq in ibm.
tagged with: cloud-foundry

http://stackoverflow.com/a/49267404
has body: You were on a good path. You need a function to update your file in the same way you read it. I have written such a function for example. Here you go: import csv with open('stock.csv','r') as STOCK_READ: #Counts the amount of items in the CSV file ITEM_COUNT = 0 reader = csv.reader(STOCK_READ) for line in reader: ITEM_COUNT = ITEM_COUNT + 1 def GET_STOCK_COUNT(): with open('stock.csv', 'r') as STOCK_READ: reader = csv.reader(STOCK_READ) for line in reader: print("{0} - {1} - {2} in stock".format(line[0],line[1],line[2])) def UPDATE_STOCK_COUNT(item_id): with open('stock.csv', 'r') as STOCK_READ: reader = csv.reader(STOCK_READ) output = [] for line in reader: if line[0] == item_id: line[2] = str(int(line[2])-1) output.append(line) with open('stock.csv', 'w', newline='') as STOCK_WRITE: writer = csv.writer(STOCK_WRITE) writer.writerows(output) while True: GET_STOCK_COUNT() CHOSEN_ITEM = input("Input number of desired item: ") UPDATE_STOCK_COUNT(CHOSEN_ITEM)
accepted answer of: http://stackoverflow.com/q/49266871
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49266871
type: Answer

http://stackoverflow.com/a/49151755
upvote count: 2
downvote count: 0
has body: It clearly seems to be a problem of permissions. If you are using Ubuntu or Liux OS, the try using: sudo pip install tensorflow If you are using Windows then: Run the Command prompt as Administrator and the run pip install tensorflow For better getting rid of such issues in future, Using Anaconda.
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49151662

http://stackoverflow.com/a/49135849
type: Answer
answers question: http://stackoverflow.com/q/49135821
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49135821
downvote count: 0
has comment: http://stackoverflow.com/comment/85277710
has body: I believe you're looking for groupby along the 0th column index + cumcount: df['counter'] = df.groupby(level=0).cumcount() + 1 df text counter 0 0 a 1 1 b 2 2 c 3 3 d 4 1 4 e 1 5 f 2 6 g 3 2 7 h 1 8 1 2
score: 2

http://stackoverflow.com/comment/85357400
has text: I modify the class declaration to nextNode = "test" But this situation still occurs.
type: QuestionComment
comment on: http://stackoverflow.com/q/49176041
score: 0
type: Comment

http://stackoverflow.com/comment/85439335
comment on: http://stackoverflow.com/q/49212790
type: QuestionComment
type: Comment
has text: You can always [edit].
score: 1

http://stackoverflow.com/q/49194486
favorite count: 0
score: -1
has answer: http://stackoverflow.com/a/49196265
has comment: http://stackoverflow.com/comment/85396236
tagged with: beautifulsoup
tagged with: python-3.x
type: Question
has body: Hello i am new with python i flip with this look and i would like to create triplets as a result. does anyone have an idea please... name class number p 0 banana green 933 NaN 1 banana yellow 991 0.01 2 banana red 553 0.02) and the results: (banana,class,green),(banana, class, yellow), (banana, class, red) (green,number,933), (green,p,NaN) (yellow,number,911), (yellow,p,0.01) (red,number,533), (red,p,0.02),
type: UnansweredQuestion
tagged with: python
has title: python pandas table structures
has comment: http://stackoverflow.com/comment/85396798
tagged with: pandas
upvote count: 0
answer count: 1
downvote count: 1

http://stackoverflow.com/a/49248448
has body: You can use following function: def multiple_replace(my_dict, text): # first create a new dict by converting key values to lower case # this will help with the lookup later my_dict_lower = {k.lower(): v for k, v in my_dict.items()} # add re.IGNORECASE flag for case insenstivity regex = re.compile("(%s)" % "|".join(map(re.escape, my_dict_lower.keys())), re.IGNORECASE) # you can directly use mo.group() to get the matched text. # convert it to lower case and get the value from dict to replace with. return regex.sub(lambda mo: my_dict_lower[mo.group(0).lower()], text) With the example above: &gt;&gt;&gt; text = "Test one, test One, test Two, tEst three" &gt;&gt;&gt; my_dict = { ... "Test one": "Test 1", ... "Test Two": "Test 2", ... "Test three": "Test 3", ... } &gt;&gt;&gt; multiple_replace(my_dict, text) 'Test 1, Test 1, Test 2, Test 3'
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49248346
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49248346

http://stackoverflow.com/q/49147911
possible better answer: http://stackoverflow.com/a/49148038
has title: Separate list elements by theirs property in Python
has answer: http://stackoverflow.com/a/49148192
accepted answer: http://stackoverflow.com/a/49148192
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85300428
has answer: http://stackoverflow.com/a/49148038
has answer: http://stackoverflow.com/a/49148010
tagged with: python
has comment: http://stackoverflow.com/comment/85301433
has comment: http://stackoverflow.com/comment/85301362
score: 2
upvote count: 2
has body: I have list p1: p1 = [ {'id': 1, 'area': 5}, {'id': 2, 'area': 6}, {'id': 3, 'area': 10}, {'id': 4, 'area': 6}, {'id': 5, 'area': 6}, {'id': 6, 'area': 6}, {'id': 7, 'area': 4}, {'id': 8, 'area': 4} ] And I need to separate this list by area value, like this (p2): p2 = { 4: [ {'id': 7, 'area': 4}, {'id': 8, 'area': 4} ], 5: [ {'id': 1, 'area': 5} ], 6: [ {'id': 2, 'area': 6}, {'id': 4, 'area': 6}, {'id': 5, 'area': 6}, {'id': 6, 'area': 6} ], 10: [ {'id': 3, 'area': 10} ] } My solution is: areas = {x['area'] for x in p1} p2 = {} for area in areas: p2[area] = [x for x in p1 if x['area'] == area] It seems to work, but is there any better and more "pythonic" solution?
type: AnsweredQuestion
downvote count: 0
answer count: 3

http://stackoverflow.com/comment/85295317
score: 0
has text: install official python distribution of windows. it have pip inbuilt or use winpython distribution.
type: QuestionComment
comment on: http://stackoverflow.com/q/49144990
type: Comment

http://stackoverflow.com/comment/85477327
type: Comment
comment on: http://stackoverflow.com/a/49235023
score: 0
type: AnswerComment
has text: there are multiple capturing group in the regex, change them to non-capturing groups (use `(:?...)` instead of `(...)`)

http://stackoverflow.com/comment/85579666
score: 1
type: Comment
has text: Hello, this was resolved by using django-widgets-improved instead of the old django-widgets-tweaks
type: QuestionComment
comment on: http://stackoverflow.com/q/49183133

http://stackoverflow.com/comment/85283092
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49138786
has text: As an aside, If you want to rename the files, do you care that its done in alphabetical order?

http://stackoverflow.com/comment/85436722
score: 0
has text: Try `if 10<=i<20`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49216350

http://stackoverflow.com/a/49242446
has comment: http://stackoverflow.com/comment/85567848
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49240582
has body: Officially, you can't. Selenium uses the WebDriver specification to communicate with browsers, but the spec doesn't support tabs—only windows. As your example shows, you can hack workarounds for specific browsers and operating systems. But what your example doesn't show is why you'd want to. Is there a particular reason why you can't just use a new window? Opening and using a new window from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait initial_windows = driver.window_handles wait = WebDriverWait(driver, 10) opened = EC.new_window_is_opened(initial_windows) driver.execute_script("window.open();") wait.until(opened) initial_window = driver.current_window_handle new_windows = list(set(driver.window_handles) - set(initial_windows)) new_window = new_windows[0] driver.switch_to.window(new_window) try: # ... finally: driver.switch_to.window(initial_window) Bonus: Simplifying with capybara-py from capybara.dsl import page with page.window(page.open_new_window()): # ...
has comment: http://stackoverflow.com/comment/85490083
type: Answer

http://stackoverflow.com/a/49313419
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49269546
type: Answer
answers question: http://stackoverflow.com/q/49269546
has body: Update: I resolved my problem by starting mongod with the --bind_ip_all option (of course, after turning on authentication)

http://stackoverflow.com/comment/85292277
has text: thank you @Adam. I solved it without creating new model, with the help of existing `TimeStamWS` model. See my answer.
comment on: http://stackoverflow.com/a/49131290
score: 0
type: Comment
type: AnswerComment

event-handling
tag name: event-handling
type: Tag
tags question: http://stackoverflow.com/q/49274009

http://stackoverflow.com/comment/85436559
comment on: http://stackoverflow.com/q/49216095
type: QuestionComment
has text: To that point, might I recommend rubber-duck-debugging? Find out more about it [here](https://en.wikipedia.org/wiki/Rubber_duck_debugging). Note: might just work better with an actual rubber duck, results may vary
type: Comment
score: 0

http://stackoverflow.com/comment/85479095
has text: Linearization isn't the issue here; it's understanding which dunder methods are called and why.
type: AnswerComment
comment on: http://stackoverflow.com/a/49237746
score: 1
type: Comment

http://stackoverflow.com/q/49219233
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49220079
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49220079
tagged with: dataframe
tagged with: python
has title: Merged two dataframes and trying to access and use data effectively
has body: I've got an imported template which is a table containing names of probes with assigned True or False (if the probes are to be used for QC purposes later), example: ProbeName QC probe 1 True probe 2 True probe 3 True probe 4 False probe 5 False Secondly I have an imported list of samples, which includes probe names as a merge point and values for the probes. Second import looks like this: SampleName ProbeName Value sample 1 probe 1 0 sample 1 probe 2 0 sample 1 probe 3 0 sample 1 probe 4 0 sample 1 probe 5 0 sample 2 probe 1 0 sample 2 probe 2 0 sample 2 probe 3 0 sample 2 probe 4 0 sample 2 probe 5 0 Merged together this currently looks like this: SampleName ProbeName Value QC sample 1 probe 1 0 True sample 1 probe 2 0 True sample 1 probe 3 0 True sample 1 probe 4 0 False sample 1 probe 5 0 False sample 2 probe 1 0 True sample 2 probe 2 0 True sample 2 probe 3 0 True sample 2 probe 4 0 False sample 2 probe 5 0 False etc... The index is defaulted to the number of lines. I've done this with the following code: template = pd.read_csv("Template.txt", sep='\t') # importing template datain = pd.read_csv("Data.txt", sep = '\t') # import sample data data = pd.merge(datain, template, how='left') # merge template and sample data I tried to make the sample name the index but for some reason when I called the data.values I still could see the numbered index and the sample name was no longer associated. The reason I have a template and merge data in is I have seperate files exported from a genomic analyser and wanted to use this raw output as my main input for my program. The template is there to add the True/False data to the revelant probes which would allow me to create and import different probe lists with different QC probes etc depending on the test analsyed etc. Ideally I want to be able to iterate over each sample and then iterate over each probe and its values. For example, for all samples, what is the sum of the probes marked as True. SampleName ProbeName Value sample…
has comment: http://stackoverflow.com/comment/85443464
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85442162
tagged with: pandas
linked to: http://stackoverflow.com/q/20109391
score: 1

http://stackoverflow.com/comment/85560157
comment on: http://stackoverflow.com/q/49274161
score: 2
type: Comment
type: QuestionComment
has text: My pipeline use essentially ```dask``` but it could be an option even if I read millions of lines (I have a huge csv file...).

http://stackoverflow.com/a/49197763
answers question: http://stackoverflow.com/q/49188162
type: Answer
has comment: http://stackoverflow.com/comment/85486319
has comment: http://stackoverflow.com/comment/85484243
upvote count: 4
has body: Here is Fisher-Yates-Knuth in-place sampling (https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) Memory was stable ~4Gb (yes, I was using 100000000) # Fisher-Yates-Knuth sampling, in-place Durstenfeld version import numpy as np def swap(data, posA, posB): if posA != posB: data[posB], data[posA] = data[posA], data[posB] def get_random_element(data, datalen): pos = datalen while pos &gt; 0: idx = np.random.randint(low=0, high=pos) # sample in the [0...pos) range pos -= 1 swap(data, idx, pos) yield data[pos] length = 100000000 some_long_list = list(range(0, length)) gen = get_random_element(some_long_list, length) for k in range(0, length): print(next(gen)) UPDATE For speed, you might want to inline swap() as well
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85484022
score: 4
accepted answer of: http://stackoverflow.com/q/49188162

http://stackoverflow.com/comment/85495990
score: 1
has text: @MassiveOwl It's either your actual generating more than 2 splits, or possibly a bug from an older pandas version, because it worked for me for this sample -- although that regex is a mess.
comment on: http://stackoverflow.com/a/49245991
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85400409
comment on: http://stackoverflow.com/q/49197644
type: QuestionComment
score: 0
has text: Ive tried something like this (assuming a small sized dictionary):people = [ {'name': "Tom", 'age': 10}, {'name': "Mark", 'age': 5}, {'name': "Pam", 'age': 7} ] def search(name): for p in people: if p['name'] == name: return p search("Pam") This gives the dictionary but I am not able to extrapolate it to the entire text file and then to the other files in the folder
type: Comment

http://stackoverflow.com/comment/85382542
comment on: http://stackoverflow.com/a/49188438
score: 0
has text: Hi @avigil , i don't leave any comment about json deserializer provided by `requests` package. I use `json.loads` for loading huge json stock data everyday. So, from my experiences, i suggest json.loads for the answer. It's an opinion
type: Comment
type: AnswerComment

video
tags question: http://stackoverflow.com/q/49265735
type: Tag
tags question: http://stackoverflow.com/q/49140942
tag name: video

http://stackoverflow.com/a/49172470
has body: Here is one way, using list.index to derive sort order. fruits = ['apple', 'banana', 'orange'] labels = ['banana2', 'apple2', 'orange1', 'banana1', 'apple1', 'apple3'] res = sorted(labels, key=lambda x: fruits.index(x[:-1])) # ['apple2', 'apple1', 'apple3', 'banana2', 'banana1', 'orange1'] You can use a tuple as sort key too, combine with some regular expression to separate integers of any size. import re fruits = ['apple', 'banana', 'orange'] labels = ['banana2', 'apple2', 'orange1', 'banana1', 'apple10', 'apple3'] def sorter(mystr, fruits): str_split = re.match(r'([a-z]+)([0-9]+)', mystr, re.I).groups() return (fruits.index(str_split[0]), int(str_split[1])) res2 = sorted(labels, key=lambda x: sorter(x, fruits)) # ['apple2', 'apple3', 'apple10', 'banana1', 'banana2', 'orange1']
downvote count: 0
answers question: http://stackoverflow.com/q/49172072
type: Answer
has comment: http://stackoverflow.com/comment/85349938
score: 2
upvote count: 2

http://stackoverflow.com/a/49261966
has comment: http://stackoverflow.com/comment/100611038
has comment: http://stackoverflow.com/comment/106247624
answers question: http://stackoverflow.com/q/49260393
has comment: http://stackoverflow.com/comment/100605442
type: Answer
upvote count: 29
has comment: http://stackoverflow.com/comment/104548271
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/100591403
score: 29
has comment: http://stackoverflow.com/comment/96581003
accepted answer of: http://stackoverflow.com/q/49260393
has body: As stated in django docs, only count(), order_by(), values(), values_list() and slicing of union queryset is allowed. You can't filter on union queryset. That means, you have to apply filters on queries before applying union on them. Also, you can achieve your goal without even using union(): Suite.objects.filter(role_set__users=self.get_user(), name="energia") You may need to adjust field name in filter if you've used related_name or related_query_name in definition of suites M2M field in Role model.

http://stackoverflow.com/comment/85289301
comment on: http://stackoverflow.com/a/49141836
type: Comment
type: AnswerComment
has text: I don’t quite understand what u mean by post_context.slug
score: 0

http://stackoverflow.com/a/49160588
type: Answer
accepted answer of: http://stackoverflow.com/q/49160428
has comment: http://stackoverflow.com/comment/105543299
has body: In this case, you can pass the sentences as pandas series. Below is a minimal example for understanding: df = pd.DataFrame({'aaa': ['a','b','c']}) ex = [[1,2,3],[2,3,4],4,5,6] df['sentences'] = pd.Series(ex) print(df) aaa sentences 0 a [1, 2, 3] 1 b [2, 3, 4] 2 c 4
upvote count: 3
type: AcceptedAnswer
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/49160428

http://stackoverflow.com/comment/85258462
score: 0
has text: @Kev1n91: Your problem, however, is that the thread can easily switch between testing if `self.semaphore` is no longer true in a `while` loop, and another thread then setting it to True again. So you exit the `while` loop with `semaphore` set *back to True by another thread*, both threads thinking they have the lock.
comment on: http://stackoverflow.com/q/49126825
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85426073
type: QuestionComment
has text: `=` is assignment operator, for comparison use `==`
comment on: http://stackoverflow.com/q/49210834
type: Comment
score: 1

http://stackoverflow.com/a/61654141
answers question: http://stackoverflow.com/q/49161174
has comment: http://stackoverflow.com/comment/110165300
has comment: http://stackoverflow.com/comment/123620688
type: Answer
has body: I resolved it changing from sparse_categorical_crossentropy to categorical_crossentropy and is now running fine.
downvote count: 0
has comment: http://stackoverflow.com/comment/109636966
upvote count: 53
score: 53

http://stackoverflow.com/q/49133780
tagged with: web-scraping
has title: Issues when scraping a web page using selenium in python
answer count: 1
has body: I have been given a model to run a successful web scraper on a selected website, however, when i alter this to collect data from a second website, it keeps returning as an error. I'm not sure if it is an error in the code or the website is refusing my requests. Could you please look through this and see where my issue lies. Any help hugely appreciated! from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() try: driver.get("http://www.caiso.com/TodaysOutlook/Pages/supply.aspx") # load the page WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.highcharts-legend-item highcharts-pie-series highcharts-color-0'))) # wait till relevant elements are on the page except: driver.quit() # quit if there was an error getting the page or we've waited 15 seconds and the stats haven't appeared. stat_elements = driver.find_elements_by_css_selector('.highcharts-legend-item highcharts-pie-series highcharts-color-0') for el in stat_elements: print(el.find_element_by_css_selector('b').text) print(el.find_element_by_css_selector('br').text) driver.quit()
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49134821
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49134821
tagged with: selenium

http://stackoverflow.com/comment/85282163
type: QuestionComment
has text: C. Braun, I dont need to edit binary files, I need to add metadata. I know how to add binary data. I need to add non binary meta information to the properties (E.g: Name, Type, File Path, attributes, customMetaInfo)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49138450

twilio
tag name: twilio
type: Tag
tags question: http://stackoverflow.com/q/49220952

http://stackoverflow.com/comment/85471345
has text: I just edited my question - if I want to remain first 10 colors in `tab10`, can I just add 2 more colors manually? Instead of changing to `jet` like in the previous question.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49233855

http://stackoverflow.com/a/49276613
answers question: http://stackoverflow.com/q/49272356
score: 0
has body: The OpenCV subtract function requires the both input arrays (if they are two array, not an array and a scalar) to have the same size and number of channels. Check if both are RGB or GRAY, and resize one of them to the other size. An only resize is required.
type: Answer

http://stackoverflow.com/comment/85451311
has text: I'm just curious, how else would one go about ordering the outputs of asynchronous calls other than waiting for them and collating them at the end?
type: QuestionComment
comment on: http://stackoverflow.com/q/49222992
type: Comment
score: 0

http://stackoverflow.com/comment/85327101
comment on: http://stackoverflow.com/q/49160714
type: Comment
type: QuestionComment
score: 0
has text: you're not breaking in the second if. Is that deliberate?

http://stackoverflow.com/comment/85492505
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49244146
has text: @MooingRawr The output of the json file is printing correctly browser side. If I view source, and select one of the links it plays. It is a live stream.

http://stackoverflow.com/comment/85291378
type: AnswerComment
has text: So swap the pipe for a tab character: `\t`. The principle is the same.
comment on: http://stackoverflow.com/a/49142866
score: 1
type: Comment

http://stackoverflow.com/comment/135670347
type: Comment
score: 0
has text: Note that this changes the type from `pandas._libs.tslibs.timestamps.Timestamp` to `str`!
type: AnswerComment
comment on: http://stackoverflow.com/a/49168574

http://stackoverflow.com/comment/85546197
has text: @cᴏʟᴅsᴘᴇᴇᴅ [I'l probably regret this, but…](https://stackoverflow.com/a/49271683/908494)
comment on: http://stackoverflow.com/a/49271219
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85411186
comment on: http://stackoverflow.com/q/49184727
score: 0
type: Comment
has text: @Nebbles Thank you for your advice. I thought a subprocess is part of multiprocessing. I will study on it!
type: QuestionComment

http://stackoverflow.com/q/49161006
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85328455
has comment: http://stackoverflow.com/comment/85328522
type: Question
has answer: http://stackoverflow.com/a/49162831
tagged with: django-cms
tagged with: raspberry-pi
type: UnansweredQuestion
has body: Today I tried to install django CMS for a while on my Raspberry pi but it will not work. I Installed a fresh "RASPBIAN STRETCH LITE" then I entered following commands via an ssh connection: sudo wget https://bootstrap.pypa.io/get-pip.py sudo python get-pip.py sudo pip install Django==1.10 sudo pip install virtualenv cd /srv sudo mkdir django_cms cd django_cms sudo virtualenv env source env/bin/activate sudo pip install --upgrade pip sudo pip install djangocms-installer sudo mkdir django_site cd django_site/ sudo djangocms -f -p . web_site All this follows this guide And this error get thrown after executing the last command above: Creating the project Please wait while I install dependencies ERROR: cmd : [u'pip', u'install', u'-q', u'django-cms&gt;=3.5,&lt;3.6', u'djangocms-admin-style&gt;=1.2,&lt;1.3', u'django-treebeard&gt;=4.0,&lt;5.0', u'https://github.com/divio/djangocms-text-ckeditor/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-file/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-link/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-style/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-googlemap/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-snippet/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-picture/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-video/archive/master.zip?1520455195.14', u'https://github.com/divio/djangocms-column/archive/master.zip?1520455195.14', u'easy_thumbnails', u'django-filer&gt;=1.3', u'Django&lt;2.0', u'pytz', u'django-classy-tags&gt;=0.7', u'html5lib&gt;=0.999999,&lt;0.99999999', u'Pillow&gt;=3.0', u'django-sekizai&gt;=0.9', u'six'] :Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-FFzxtb/Pillow/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exe…
tagged with: django
tagged with: python-2.7
score: 0
has title: Django CMS on Raspberry Pi 3 Fails
has comment: http://stackoverflow.com/comment/85328280

memoization
type: Tag
tag name: memoization
tags question: http://stackoverflow.com/q/49122062

http://stackoverflow.com/comment/85291084
type: Comment
comment on: http://stackoverflow.com/q/49123636
type: QuestionComment
score: 0
has text: @chrisz He actually didn't specify and I didn't ask, but for the sake of this post, let's say yes, it can be another letter, symbol, space, or nothing. That shouldn't make any huge difference.

http://stackoverflow.com/a/49211813
has comment: http://stackoverflow.com/comment/85444871
has body: About decorator signature Doing this... decorated_fun = decorator(myfun, arg1, arg2) ... is not how decorators work. A decorator takes a single argument, a function, and outputs a function. In particular, the above is not equivalent to the correct way to do which is this. @decorator(arg1, arg2) def myfun(...): ... # Which is actually equivalent to... myfun = decorator(arg1, arg2)(myfun) Accessing __init__ arguments in __call__ If you want to have access to the argument passed to __init__, you could store them as instance attributes. class MyDecoratorClass: def __init__(self, *args, **kwargs): # We store the arguments self.args = args self.kwargs = kwargs # Any other code that is needed here def __call__(self, fun_to_decorate): # Single argument def inner(*args, **kwargs): # Here you have access to self.args and self.kwargs return fun_to_decorate(*args, **kwargs) return inner Doing the same with a function Although, keep in mind that you do not need to have a class decorator to accomplish this, the following decorator will have the same behaviour. def my_decorator_function(*args, **kwargs): def wrapper(decorated_func): def inner_wrapper(*inner_args, **inner_kwargs): # args and kwargs can be accessed here return decorated_func(*inner_args, **inner_kwargs) return inner_wrapper return wrapper @my_decorator_function(arg1, arg2) def myfun(*args, **kwargs): print("myfun was called")
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85446668
type: Answer
accepted answer of: http://stackoverflow.com/q/49210552
answers question: http://stackoverflow.com/q/49210552
has comment: http://stackoverflow.com/comment/85445839
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85443353

http://stackoverflow.com/a/49601809
type: AcceptedAnswer
score: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/90958169
type: Answer
has body: Replace your file path to the parent folder path. observer.schedule(event_handler, path='C:/Email_forwarding/Attachments/Sales', recursive=False)
accepted answer of: http://stackoverflow.com/q/49211873
has comment: http://stackoverflow.com/comment/91224440
upvote count: 4
answers question: http://stackoverflow.com/q/49211873

http://stackoverflow.com/comment/85415248
score: 0
comment on: http://stackoverflow.com/a/49204993
type: Comment
type: AnswerComment
has text: Wow, that's amazing, exactly what I was looking for! Thank you so much for that sacul, very appreciated!

http://stackoverflow.com/a/55675487
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/49189484
score: 3
has body: The @MahdiSorkhmiri answer is working perfectly for me. Here is how my file is looking write now. class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( validators=[UniqueValidator(UserModel.objects.all())] ) password = serializers.CharField( min_length=4, write_only=True, required=True, style={'input_type': 'password'} ) def create(self, validated_data): fields = ['username', 'password', 'email'] data = {f: validated_data.get(f) for f in fields} return UserModel.objects.create_user(**data) class Meta: model = UserModel fields = 'username email last_name first_name password'.split()
has comment: http://stackoverflow.com/comment/98036875
downvote count: 1

http://stackoverflow.com/a/49152050
type: Answer
answers question: http://stackoverflow.com/q/49133974
has body: Two issues: Firstly, a few typos/small mistakes: you have an unnecessary closing tag (&gt;)in all your find paths, so they all need removing in your found_provider section, you set found_contextR when I think you mean found_contextP (P, not R) using if elem.find("&lt;path&gt;"): raises warning, you should instead use if elem.find("&lt;path&gt;") is not None: Secondly, you have made a mistake with your child element sections, for example in the found_provider section: if elem.find(".//{http://autosar.org/schema/r4.0}PROVIDER-IREF&gt;"): found_provider = True for child in elem.find(".//{http://autosar.org/schema/r4.0}PROVIDER-IREF&gt;"): if child.find(".//{http://autosar.org/schema/r4.0}CONTEXT-COMPONENT-REF&gt;"): found_contextR = True if child.find(".//{http://autosar.org/schema/r4.0}TARGET-P-PORT-REF&gt;"): found_targetP = True You correctly find for the PROVIDER-IREF element, then you loop over its children trying to match the CONTEXT-COMPONENT-REF and TARGET-P-PORT-REF elements. But you're doing this by searching for them as children of these child elements (ie grandchildren of PROVIDER-IREF), when they themselves are the children. So either you need to be checking the tags of the child elements, rather than searching for elements under them: if elem.find(".//{http://autosar.org/schema/r4.0}PROVIDER-IREF") is not None: found_provider = True for child in elem.find(".//{http://autosar.org/schema/r4.0}PROVIDER-IREF"): if child.tag == "{http://autosar.org/schema/r4.0}CONTEXT-COMPONENT-REF": found_contextP = True if child.tag == "{http://autosar.org/schema/r4.0}TARGET-P-PORT-REF": found_targetP = True or you could try to extract the PROVIDER-IREF element and then find elements under it: provider = elem.find(".//{http://autosar.org/schema/r4.0}PROVIDER-IREF") if provider is not None: found_provider = True if provider.find("{http://autosar.org/schema/r4.0}CONTEXT-COMPONENT-REF") is not None: found_contextP = True if provider.find("{http://autosar.org/schema/r4.0}TARGET-…
accepted answer of: http://stackoverflow.com/q/49133974
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85343662
score: 0

http://stackoverflow.com/q/49155874
upvote count: 1
has title: tensorflow error: index out of bounds? Training data multiplied *3?
favorite count: 0
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/85320423
has comment: http://stackoverflow.com/comment/86325727
tagged with: python
score: 1
has body: I have a problem with the training of a CNN. My dataset has currently 1000 numpy arrays containing an image and a list. This is the code used to train the CNN: import numpy as np from alexnet import alexnet # image resolution WIDTH = 160 HEIGHT = 120 LR = 1e-3 EPOCHS = 8 MODEL_NAME = 'model-{}-{}-{}-epochs.model'.format(LR, 'alexnet',EPOCHS) model = alexnet(WIDTH, HEIGHT, LR) hm_data = 22 for i in range(EPOCHS): for i in range(1,hm_data+1): train_data = np.load('trainmodel_test1.npy'.format(i)) train = train_data[:-100] test = train_data[-100:] X = np.array([i[0] for i in train]).reshape(-1,WIDTH,HEIGHT,1) Y = [i[1] for i in train] test_x = np.array([i[0] for i in test]).reshape(-1,WIDTH,HEIGHT,1) test_y = [i[1] for i in test] # ----------- error happens here: ---------------- model.fit({'input': X}, {'targets': Y}, n_epoch=EPOCHS, validation_set=({'input': test_x}, {'targets': test_y}), snapshot_step=500, show_metric=True, run_id=MODEL_NAME) # ------------------------------------------------ model.save(MODEL_NAME) it initiates: Training samples: 2700 # -----&gt; expected: 900 !!! Validation samples: 300 # -----&gt; expected: 100 -- but the problem is now that it multiplies the dataset *3 and complains afterwards that the indexes are higher than the total dataset range: Exception in thread Thread-3: Traceback (most recent call last): File "..\Python\Python35\Lib\threading.py", line 914, in _bootstrap_inner self.run() File "..\Python\Python35\Lib\threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "..\0.1\venv\lib\site-packages\tflearn\data_flow.py", line 187, in fill_feed_dict_queue data = self.retrieve_data(batch_ids) File "..\0.1\venv\lib\site-packages\tflearn\data_flow.py", line 222, in retrieve_data utils.slice_array(self.feed_dict[key], batch_ids) File "..\0.1\venv\lib\site-packages\tflearn\utils.py", line 187, in slice_array return X[start] IndexError: index 1331 is out of bounds for axis 0 with size 900 hints on that? ~modified code…
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/85320331
type: Question
has comment: http://stackoverflow.com/comment/86332539
answer count: 0
type: UnansweredQuestion
downvote count: 0
tagged with: training-data

http://stackoverflow.com/comment/85526290
type: AnswerComment
has text: Thanks Martin, this method seems to work best for me as it allows floats as well as integers. Since the output doesn't include the upper limit this seems to require more overhead on the coder's part doesn't it? I would really need 3 lines of code to replicate MATLAB's simple operator. I hear Python is supposed to produce simpler code than MATLAB, but I'm not quite seeing it yet. `import numpy` `dx=2.5` `print(numpy.arange(0,10+dx,dx))`
type: Comment
comment on: http://stackoverflow.com/a/49211706
score: 0

http://stackoverflow.com/a/49243294
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49243204
downvote count: 0
answers question: http://stackoverflow.com/q/49243204
type: Answer
has body: One way is to use sum over axis 1 df1.fillna('').sum(1) 0 A 1 B 2 C Option2: use bfill and pick the first column df1.bfill(axis = 1).iloc[:, 0]
upvote count: 2

http://stackoverflow.com/comment/85305416
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49126527
has text: @Maggyero: please don't move the goal posts. Windows passes environment variables to a process using the same codec as command-line arguments.

matrix
tags question: http://stackoverflow.com/q/49210153
tags question: http://stackoverflow.com/q/49131510
tags question: http://stackoverflow.com/q/49158935
tags question: http://stackoverflow.com/q/49193238
tags question: http://stackoverflow.com/q/49276413
tags question: http://stackoverflow.com/q/49162883
tag name: matrix
tags question: http://stackoverflow.com/q/49260934
tags question: http://stackoverflow.com/q/49245271
tags question: http://stackoverflow.com/q/49194152
tags question: http://stackoverflow.com/q/49133166
tags question: http://stackoverflow.com/q/49219585
tags question: http://stackoverflow.com/q/49166156
tags question: http://stackoverflow.com/q/49224713
tags question: http://stackoverflow.com/q/49133317
tags question: http://stackoverflow.com/q/49148915
tags question: http://stackoverflow.com/q/49222880
tags question: http://stackoverflow.com/q/49212929
tags question: http://stackoverflow.com/q/49205948
tags question: http://stackoverflow.com/q/49268410
tags question: http://stackoverflow.com/q/49258716
tags question: http://stackoverflow.com/q/49210506
tags question: http://stackoverflow.com/q/49225693
tags question: http://stackoverflow.com/q/49251312
tags question: http://stackoverflow.com/q/49221909
tags question: http://stackoverflow.com/q/49143433
tags question: http://stackoverflow.com/q/49234160
tags question: http://stackoverflow.com/q/49223697
tags question: http://stackoverflow.com/q/49209700
tags question: http://stackoverflow.com/q/49228144
tags question: http://stackoverflow.com/q/49246127
type: Tag

http://stackoverflow.com/comment/105719846
score: 0
type: Comment
comment on: http://stackoverflow.com/a/59785150
type: AnswerComment
has text: Please provide an explanation to explain how your code fixed the problem.

http://stackoverflow.com/comment/85325386
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49159596
has text: no need to apologize. Note that it's normal that the test fails: the process isn't run.

http://stackoverflow.com/a/49274196
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49273858
score: 4
has body: I find in the interceptors configuration: Axios.interceptors.response.use( res =&gt; { return res; }, error =&gt; { return Promise.reject(error.response.data) } ); I was return the error.response.data directly, I could configure it to error.response, or error. if I configure the error.response, then in the .catch() I can console like bellow: console.log(response.data); console.log(response.status); console.log(response.headers);
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49273858

http://stackoverflow.com/comment/85356960
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49173597
score: 0
has text: OK, so you try solution in chat and get different output? Can you show what you get?

http://stackoverflow.com/q/49258589
has body: I have a dataframe and I would like to list the combinations with value 1. My data is similar to: d = {'Australia' : pd.Series([0,1,1], index=['Australia', 'Belgium', 'France']), 'Belgium' : pd.Series([1,0,1], index=['Australia','Belgium', 'France']), 'France' : pd.Series([1,1,0], index=['Australia','Belgium', 'France'])} df = pd.DataFrame(d) df How could I create a list which would be similar to: &gt; [(Australia, Belgium), (Australia, Belgium), (Belgium, Australia), &gt; (Belgium, France), (France, Australia), (France, Belgium)]
type: Question
has answer: http://stackoverflow.com/a/49258630
has comment: http://stackoverflow.com/comment/85521186
upvote count: 1
accepted answer: http://stackoverflow.com/a/49258630
has title: Create list of combination with value 1
type: AnsweredQuestion
score: 0
tagged with: list
tagged with: pandas
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/q/49180941
answer count: 2
possible better answer: http://stackoverflow.com/a/49187778
tagged with: classification
has body: I have a series of 2d images of two types, either a star or a pentagon. My aim is to classify all of these images respectively. I have 30 star images and 30 pentagon images. An example of each image is shown side by side here: Before I apply the KNN classification algorithm, I need to extract a feature vector from all the images. The feature vectors must all be of the same size however the 2d images all vary in size. I have extracted read in my image and I get back a 2d array with zeros and ones. image = pl.imread('imagepath.png') My question is how do I process image in order produce a meaningful feature vector that contains enough information to allow me to do the classification. It has to be a single vector per image which I will use for training and testing.
tagged with: feature-extraction
has answer: http://stackoverflow.com/a/49187778
tagged with: python
has comment: http://stackoverflow.com/comment/85376666
has title: Extract feature vector from 2d image in numpy
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49185861
has comment: http://stackoverflow.com/comment/85379480
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/85379513
upvote count: 1
has answer: http://stackoverflow.com/a/49185861
downvote count: 1
favorite count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/a/49250395
score: 1
answers question: http://stackoverflow.com/q/49250254
has comment: http://stackoverflow.com/comment/85504219
has comment: http://stackoverflow.com/comment/85504443
type: Answer
downvote count: 0
has body: feature_importances_ attribute can be used. The feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html print(clf.feature_importances_) &gt; [1. 0.] Here second feature importance is zero, it means this feature is not included in the rule tree.
upvote count: 1

http://stackoverflow.com/a/49278809
upvote count: 1
has comment: http://stackoverflow.com/comment/85564020
has body: As a preamble : your whole benchmark is just plain wrong - the "list_comp_a" test doesn't test the construction time of a list using a list comprehension (nor does "iter_list_comp_a" fwiw), and the tests using iter() are mostly irrelevant - iter(iterable) is just a shortcut for iterable.__iter__() and is only of any use if you want to manipulate the iterator itself, which is practically quite rare. If you hope to get some meaningful results, what you want to benchmark are the execution of a list comprehension, a generator expression and a generator function. To test their execution, the simplest way is to wrap all three cases in functions, one execution a list comprehension and the other two building lists from resp. a generator expression and a generator built from a generator function). In all cases I used xrange as the real source so we only benchmark the effective differences. Also we use timeit.timeit to do the benchmark as it's more reliable than manually messing with time.time(), and is actually the pythonic standard canonical way to benchmark small code snippets. import timeit # py2 / py3 compat try: xrange except NameError: xrange = range n = 1000 def test_list_comp(): return [x for x in xrange(n)] def test_genexp(): return list(x for x in xrange(n)) def mygen(n): for x in xrange(n): yield x def test_genfunc(): return list(mygen(n)) for fname in "test_list_comp", "test_genexp", "test_genfunc": result = timeit.timeit("fun()", "from __main__ import {} as fun".format(fname), number=10000) print("{} : {}".format(fname, result)) Here (py 2.7.x on a 5+ years old standard desktop) I get the following results: test_list_comp : 0.254354953766 test_genexp : 0.401108026505 test_genfunc : 0.403750896454 As you can see, list comprehensions are faster, and generator expressions and generator functions are mostly equivalent with a very slight (but constant if you repeat the test) advantage to generator expressions. Now to answer your main question "why and when would you …
has comment: http://stackoverflow.com/comment/85562371
score: 1
answers question: http://stackoverflow.com/q/49275927
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85373580
type: Comment
comment on: http://stackoverflow.com/a/49183795
type: AnswerComment
has text: Preference because it keeps dtype int
score: 1

http://stackoverflow.com/comment/85552730
has text: How do i create a tuple with my arguments?
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49274546

http://stackoverflow.com/comment/85438294
comment on: http://stackoverflow.com/a/49217123
type: Comment
type: AnswerComment
score: 0
has text: why can't we use x=x can you explain it bit more in function we can use it right why not here???

http://stackoverflow.com/comment/85437789
score: 0
type: QuestionComment
has text: *Where* is it saying `p1_move1` isn't defined? Which line? There are three separate places where the error could be being raised, and where the error is might help answer the question.
type: Comment
comment on: http://stackoverflow.com/q/49216244

selenium
tags question: http://stackoverflow.com/q/49150427
tags question: http://stackoverflow.com/q/49271413
tags question: http://stackoverflow.com/q/49223145
tags question: http://stackoverflow.com/q/49169524
tags question: http://stackoverflow.com/q/49180574
tags question: http://stackoverflow.com/q/49134440
tags question: http://stackoverflow.com/q/49198034
tags question: http://stackoverflow.com/q/49245355
tags question: http://stackoverflow.com/q/49260005
tags question: http://stackoverflow.com/q/49155839
tags question: http://stackoverflow.com/q/49265525
tags question: http://stackoverflow.com/q/49125167
tags question: http://stackoverflow.com/q/49152367
tags question: http://stackoverflow.com/q/49220498
tags question: http://stackoverflow.com/q/49258348
tags question: http://stackoverflow.com/q/49171370
tags question: http://stackoverflow.com/q/49223695
tags question: http://stackoverflow.com/q/49273604
tags question: http://stackoverflow.com/q/49257433
tags question: http://stackoverflow.com/q/49221991
tags question: http://stackoverflow.com/q/49252880
tags question: http://stackoverflow.com/q/49274821
tags question: http://stackoverflow.com/q/49146993
tags question: http://stackoverflow.com/q/49158846
tags question: http://stackoverflow.com/q/49239935
tags question: http://stackoverflow.com/q/49228987
tags question: http://stackoverflow.com/q/49228474
tags question: http://stackoverflow.com/q/49241395
tags question: http://stackoverflow.com/q/49224279
tags question: http://stackoverflow.com/q/49210727
tags question: http://stackoverflow.com/q/49221411
tags question: http://stackoverflow.com/q/49201281
tags question: http://stackoverflow.com/q/49205782
tags question: http://stackoverflow.com/q/49153985
tags question: http://stackoverflow.com/q/49216866
tags question: http://stackoverflow.com/q/49168556
tags question: http://stackoverflow.com/q/49211903
tags question: http://stackoverflow.com/q/49261746
tags question: http://stackoverflow.com/q/49210094
tags question: http://stackoverflow.com/q/49176871
tags question: http://stackoverflow.com/q/49193756
tags question: http://stackoverflow.com/q/49267695
tags question: http://stackoverflow.com/q/49217989
tags question: http://stackoverflow.com/q/49270109
tags question: http://stackoverflow.com/q/49247204
tags question: http://stackoverflow.com/q/49160750
tags question: http://stackoverflow.com/q/49220575
tags question: http://stackoverflow.com/q/49128260
tags question: http://stackoverflow.com/q/49177222
tags question: http://stackoverflow.com/q/49148607
tags question: http://stackoverflow.com/q/49170356
tags question: http://stackoverflow.com/q/49122003
tags question: http://stackoverflow.com/q/49159712
tags question: http://stackoverflow.com/q/49240582
tags question: http://stackoverflow.com/q/49244121
tags question: http://stackoverflow.com/q/49237744
tags question: http://stackoverflow.com/q/49234989
tags question: http://stackoverflow.com/q/49192432
tags question: http://stackoverflow.com/q/49146704
tags question: http://stackoverflow.com/q/49177677
tags question: http://stackoverflow.com/q/49141621
tags question: http://stackoverflow.com/q/49205243
tags question: http://stackoverflow.com/q/49151036
tags question: http://stackoverflow.com/q/49172172
tags question: http://stackoverflow.com/q/49230389
tags question: http://stackoverflow.com/q/49277100
tags question: http://stackoverflow.com/q/49276368
tags question: http://stackoverflow.com/q/49122885
tags question: http://stackoverflow.com/q/49275438
tags question: http://stackoverflow.com/q/49168663
tags question: http://stackoverflow.com/q/49261328
tags question: http://stackoverflow.com/q/49249853
type: Tag
tags question: http://stackoverflow.com/q/49253503
tags question: http://stackoverflow.com/q/49216418
tags question: http://stackoverflow.com/q/49258352
tags question: http://stackoverflow.com/q/49145635
tags question: http://stackoverflow.com/q/49193128
tags question: http://stackoverflow.com/q/49206421
tags question: http://stackoverflow.com/q/49123449

http://stackoverflow.com/comment/85464464
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49230489
has text: will update the post with full files @Exprator
score: 0

http://stackoverflow.com/q/49234853
answer count: 1
type: Question
type: UnansweredQuestion
has title: Nipype DataGrabber: The 'in_file' trait of a <> instance must be an existing file name, but a value of <> <class 'list'> was specified
tagged with: python
has answer: http://stackoverflow.com/a/53936945
score: 0
has body: I am trying to build a Workflow for normalization/coregistration. Here is my DataGrabber data_grabber = Node(interface=DataGrabber(infields=['subject_id'], outfields=['t1', 'flair', 'les','ref']), name ='data_grabber') data_grabber.inputs.base_directory = base_dir data_grabber.inputs.template = '*' data_grabber.inputs.sort_filelist = True data_grabber.inputs.field_template = dict(t1='T1/%s_BL_T1.nii', flair='FLAIR/%s_BL_FLAIR.nii', les='Lesions/%s_BL_FLAIR*.nii', ref='/usr/share/data/fsl-mni152-templates/%s') data_grabber.inputs.template_args = dict(t1='subject_id', flair='subject_id', les='subject_id', ref='MNI152_T1_1mm.nii.gz') data_grabber.inputs.subject_id = [217, 221] When I try with only one subject everything runs without problem, with more subjects I receive an the following error. TraitError: The 'in_file' trait of a FLIRTInputSpec instance must be an existing file name, but a value of ['/[...]/FLAIR/217_BL_FLAIR.nii', '/[...]/FLAIR/221_BL_FLAIR.nii'] &lt;class 'list'&gt; was specified. Error setting node input: Node: flair_norm input: in_file results_file: /[...]/data_grabber/result_data_grabber.pklz value: ['/[...]/FLAIR/217_BL_FLAIR.nii', '/[...]/FLAIR/221_BL_FLAIR.nii']
tagged with: nipype

http://stackoverflow.com/comment/85481465
comment on: http://stackoverflow.com/q/49238725
score: 1
has text: Yeah I'm aware of what a unit test is supposed to do. However how would you suggest I test the deletion of an object without creating it first ? (I'm not being flippant - if there's a standard, best practice way to do these kinds of tests I'm interested. At the moment the best I can come up with is to re-use the object created in the creation test as a fixture for the deletion test)
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49162339
has comment: http://stackoverflow.com/comment/85362938
has title: Plotly - Values of dict object not JSON serializable for timestamp?
answer count: 0
has comment: http://stackoverflow.com/comment/85330881
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85330522
has body: I'm trying to use plotly to create a scatter plot, but it seems like my timestamp is not JSON serializable? This is the error I'm getting: TypeError &lt;built-in method values of dict object at 0x7f6f3d8ac910&gt; is not JSON serializable And this is the code I currently have: df = datasets[3] #New column with hour rounded df['hour'] = df['p_time'].dt.floor('h') hour_counts = {} for hour in df['hour']: if hour in hour_counts: hour_counts[hour] = hour_counts[hour] + 1 else: hour_counts[hour] = 1 print hour_counts count = Scatter( x= hour_counts.keys, y= hour_counts.values, name = "Number of Riders", line = dict(color = '#17BECF'), opacity = 0.8) data = [count] layout = dict( title='Time Series with Rangeslider', xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, label='1d', step='day', stepmode='backward'), dict(count=6, label='6d', step='day', stepmode='backward'), dict(step='all') ]) ), rangeslider=dict(), type='date' ) ) fig = dict(data=data, layout=layout) iplot(fig) Can anyone provide some insight? Apologies if this is a stupid question. I'm very new to python. Thank you!
tagged with: python
has comment: http://stackoverflow.com/comment/85330761
tagged with: plotly
score: 0
type: Question

http://stackoverflow.com/comment/85273726
type: Comment
comment on: http://stackoverflow.com/a/49134293
has text: if you type "python", and start python from command line then you've already manually found the interpreter. If you run the script from somewhere else, you need to tell the script where the interpreter is.
score: 0
type: AnswerComment

http://stackoverflow.com/tag/html
tags question: http://stackoverflow.com/q/49225034
tags question: http://stackoverflow.com/q/49173146
tags question: http://stackoverflow.com/q/49200186
tags question: http://stackoverflow.com/q/49260005
tags question: http://stackoverflow.com/q/49265608
tags question: http://stackoverflow.com/q/49197269
tags question: http://stackoverflow.com/q/49245828
tags question: http://stackoverflow.com/q/49244469
tags question: http://stackoverflow.com/q/49184654
tags question: http://stackoverflow.com/q/49266145
tags question: http://stackoverflow.com/q/49124037
tags question: http://stackoverflow.com/q/49259435
tags question: http://stackoverflow.com/q/49164695
tags question: http://stackoverflow.com/q/49239935
tags question: http://stackoverflow.com/q/49230027
tags question: http://stackoverflow.com/q/49203426
tags question: http://stackoverflow.com/q/49175688
tags question: http://stackoverflow.com/q/49205608
tags question: http://stackoverflow.com/q/49155903
tags question: http://stackoverflow.com/q/49200254
tags question: http://stackoverflow.com/q/49191954
tags question: http://stackoverflow.com/q/49268188
tags question: http://stackoverflow.com/q/49268469
tags question: http://stackoverflow.com/q/49277533
tags question: http://stackoverflow.com/q/49221014
tags question: http://stackoverflow.com/q/49214508
tags question: http://stackoverflow.com/q/49171039
tags question: http://stackoverflow.com/q/49176871
tags question: http://stackoverflow.com/q/49267695
tags question: http://stackoverflow.com/q/49275822
tags question: http://stackoverflow.com/q/49174476
tags question: http://stackoverflow.com/q/49260014
tags question: http://stackoverflow.com/q/49244372
tags question: http://stackoverflow.com/q/49209753
tags question: http://stackoverflow.com/q/49245479
tags question: http://stackoverflow.com/q/49122003
tags question: http://stackoverflow.com/q/49209375
tags question: http://stackoverflow.com/q/49263966
tags question: http://stackoverflow.com/q/49200605
tags question: http://stackoverflow.com/q/49261149
tags question: http://stackoverflow.com/q/49168578
tags question: http://stackoverflow.com/q/49247245
tags question: http://stackoverflow.com/q/49225564
tags question: http://stackoverflow.com/q/49275403
tags question: http://stackoverflow.com/q/49140941
tags question: http://stackoverflow.com/q/49271250
tags question: http://stackoverflow.com/q/49122530
type: Tag
tag name: html
tags question: http://stackoverflow.com/q/49277730
tags question: http://stackoverflow.com/q/49172675
tags question: http://stackoverflow.com/q/49182790
tags question: http://stackoverflow.com/q/49241799
tags question: http://stackoverflow.com/q/49132625
tags question: http://stackoverflow.com/q/49171414
tags question: http://stackoverflow.com/q/49269034
tags question: http://stackoverflow.com/q/49143227
tags question: http://stackoverflow.com/q/49221629
tags question: http://stackoverflow.com/q/49204634
tags question: http://stackoverflow.com/q/49157875
tags question: http://stackoverflow.com/q/49259073
tags question: http://stackoverflow.com/q/49266798
tags question: http://stackoverflow.com/q/49215787
tags question: http://stackoverflow.com/q/49226935
tags question: http://stackoverflow.com/q/49162712
tags question: http://stackoverflow.com/q/49188298
tags question: http://stackoverflow.com/q/49159712
tags question: http://stackoverflow.com/q/49242055
tags question: http://stackoverflow.com/q/49200946
tags question: http://stackoverflow.com/q/49242768
tags question: http://stackoverflow.com/q/49146849
tags question: http://stackoverflow.com/q/49224690
tags question: http://stackoverflow.com/q/49193793
tags question: http://stackoverflow.com/q/49181878
tags question: http://stackoverflow.com/q/49219588

http://stackoverflow.com/q/49178620
tagged with: dataframe
downvote count: 1
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49178754
type: UnansweredQuestion
has title: Convert a column of strings into columns of characters
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49178650
score: 0
has body: I have imported CSV file in pandas it contains, 1 column and 25000 rows, I want to transform this file into new data frame sample data: 1 column 4 rows: ABC 122 678 abc I want to create DataFrame with, each element of the list(ABC) as rows columns like, followed by other rows, like this : A B C 1 2 2 6 7 8 a b c How to perform this task, I am new to programming.
tagged with: pandas

http://stackoverflow.com/comment/85422380
comment on: http://stackoverflow.com/q/49208752
type: Comment
type: QuestionComment
has text: AWESOME! THANKYOU SO MUCH
score: 0

http://stackoverflow.com/a/49211052
accepted answer of: http://stackoverflow.com/q/49210866
has comment: http://stackoverflow.com/comment/85426946
has comment: http://stackoverflow.com/comment/85427608
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85427858
has comment: http://stackoverflow.com/comment/85427676
answers question: http://stackoverflow.com/q/49210866
has comment: http://stackoverflow.com/comment/85427760
has comment: http://stackoverflow.com/comment/85427807
has comment: http://stackoverflow.com/comment/85426912
score: 1
type: Answer
has body: I think you want something like this you loop indefinitely because True well... always evaluate to true so the loop will never break unless you explicitly tell it to. from pynput.keyboard import Key,Controller import time keyboard = Controller() while True: keyboard.press(Key.enter) keyboard.release(Key.enter) for i in range(0, 4): keyboard.press(Key.tab) keyboard.release(Key.tab) for i in range(0, 3): keyboard.press(Key.enter) keyboard.release(Key.enter) ... time.sleep(60) It's also better practice to replace the while statements with for loops. That's what is typical practice when you intend to execute a block of code a determinate number of times i.e. 4 times as opposed to when you want to execute a block of code an indeterminate amount of time you use a while loop

http://stackoverflow.com/a/49259606
has comment: http://stackoverflow.com/comment/85524399
upvote count: 11
accepted answer of: http://stackoverflow.com/q/49259361
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85524692
downvote count: 0
score: 11
has body: i suspect you are using some pre-trained model, let's say for instance resnet50 and you are importing decode_predictions like this: from keras.applications.resnet50 import decode_predictions decode_predictions transform an array of (num_samples, 1000) probabilities to class name of original imagenet classes. if you want to transer learning and classify between 7 different classes you need to do it like this: base_model = resnet50 (weights='imagenet', include_top=False) # add a global spatial average pooling layer x = base_model.output x = GlobalAveragePooling2D()(x) # add a fully-connected layer x = Dense(1024, activation='relu')(x) # and a logistic layer -- let's say we have 7 classes predictions = Dense(7, activation='softmax')(x) model = Model(inputs=base_model.input, outputs=predictions) ... after fitting the model and calculate predictions you have to manually assign the class name to output number without using imported decode_predictions
type: Answer
answers question: http://stackoverflow.com/q/49259361

http://stackoverflow.com/a/49239884
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: you can drop columns that you want to hide when rendering HTML: cols_2_hide = ['col1','col2'] df.drop(cols_2_hide, axis=1).style.applymap(color_cell, subset=['columnName']).render()
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49239476
answers question: http://stackoverflow.com/q/49239476

http://stackoverflow.com/q/49171039
tagged with: javascript
tagged with: python
tagged with: flask
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49171798
tagged with: flask-wtforms
answer count: 1
has title: Flask WTForms SelectMultipleField limit maximum number of selections
type: Question
has body: Right now I am building a webapp with Flask, including some WTForms. One of them is a checklist where people can select from multiple options (hence a SelectMultipleField). Now I want to make sure that people can only select a maximum number of options (say 2 out of 3) and if they want to select more first have to de-select one of the other options. I think it might have to do something with validation, but I am really not sure how to do this...Any help is much appreciated! This is my code from forms.py class MultiCheckboxField(SelectMultipleField): option_widget = widgets.CheckboxInput() widget = widgets.ListWidget(prefix_label = False) class ChecklisteForm(FlaskForm): list_of_files = ['politiek', 'economie', 'sport'] files = [(x, x) for x in list_of_files] example = MultiCheckboxField('Label', choices=files) submit = SubmitField('Wijzigen') This is the code from my html template {{ form.hidden_tag() }} Kies kategorie {{form.example(class = "list-unstyled")}} {{form.submit(class = "btn btn-info")}} I thought this might also be related to including some javascript? But if there is any way I could avoid that I'd be happy :)
accepted answer: http://stackoverflow.com/a/49171798
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/49187042
tagged with: python
tagged with: macos
duplicate of: http://stackoverflow.com/q/18176591
linked to: http://stackoverflow.com/q/11815538
type: Question
has body: I'm trying to run a python program that requires matplotlib, which I've already installed via pip. I am running Python 3.6 locally on my Mac, with my .bash_profile updated to reflect this. The import line in question is as seen below: import matplotlib.pyplot as plt Below is the error message I see, as you can figure out from the subject line: ModuleNotFoundError: No module named 'matplotlib' And here's what I see if I try pip install matplotlib: Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/site-packages Requirement already satisfied: python-dateutil in /usr/local/lib/python3.6/site-packages (from matplotlib) Requirement already satisfied: numpy&gt;=1.7.1 in /usr/local/lib/python3.6/site-packages (from matplotlib) Requirement already satisfied: pyparsing!=2.0.0,!=2.0.4,!=2.1.2,!=2.1.6,&gt;=1.5.6 in /usr/local/lib/python3.6/site-packages (from matplotlib) Requirement already satisfied: cycler&gt;=0.10 in /usr/local/lib/python3.6/site-packages (from matplotlib) Requirement already satisfied: pytz in /usr/local/lib/python3.6/site-packages (from matplotlib) Requirement already satisfied: six&gt;=1.10 in /usr/local/lib/python3.6/site-packages (from matplotlib) I've referenced a few other posts like this and this, but without much luck. Am I overlooking an answer that I just didn't follow through with, or could it be something else? Your time is appreciated.
answer count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: pip
has title: ModuleNotFoundError: No module named 'matplotlib'
score: 22
upvote count: 24
favorite count: 0
linked to: http://stackoverflow.com/q/18176591
tagged with: matplotlib

http://stackoverflow.com/comment/85425617
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49210329
has text: @EricDuminil I think what Ryan was saying is that the _code_ is equivalent. [From PEP 498](https://www.python.org/dev/peps/pep-0498/#code-equivalence), the embedded values in an fstring are calling `__format__` with the provided expression and formatter, which is the same thing `str.format` does.

http://stackoverflow.com/a/72090287
answers question: http://stackoverflow.com/q/49270277
has body: These worked fine for me. n*n + (n-1) * (n-1) n * (2*n - 1) - (n-1)
type: Answer
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49197601
has comment: http://stackoverflow.com/comment/85400765
has comment: http://stackoverflow.com/comment/85400992
has comment: http://stackoverflow.com/comment/85400296
has comment: http://stackoverflow.com/comment/85400416
downvote count: 0
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/85401192
has comment: http://stackoverflow.com/comment/85400928
has comment: http://stackoverflow.com/comment/85400639
has body: Your file path contains the character \U which has a special meaning in Python (Unicode). You are probably receiving an error similar to: File "C:/Python34/Testing.py", quotes = open ("C:\Users\HP\Downloads\book\just.txt") ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape When this happens you will need to use a double backslash: def read_text(): quotes = open("C:\\Users\HP\Downloads\book\just.txt")
score: 1
answers question: http://stackoverflow.com/q/49197240
has comment: http://stackoverflow.com/comment/85401130

http://stackoverflow.com/a/49197992
score: 4
upvote count: 4
has body: As @cs95 has pointed out, the function is re-created each time, which can be seen with dis.dis: &gt;&gt;&gt; import dis &gt;&gt;&gt; code = &quot;&quot;&quot; ... for i in range(3): ... def foo(j): ... print(j) ... foo(i) ... &quot;&quot;&quot; &gt;&gt;&gt; dis.dis(code) 2 0 SETUP_LOOP 32 (to 34) 2 LOAD_NAME 0 (range) 4 LOAD_CONST 0 (3) 6 CALL_FUNCTION 1 8 GET_ITER &gt;&gt; 10 FOR_ITER 20 (to 32) 12 STORE_NAME 1 (i) 3 14 LOAD_CONST 1 (&lt;code object foo at 0x107544810, file &quot;&lt;dis&gt;&quot;, line 3&gt;) 16 LOAD_CONST 2 ('foo') 18 MAKE_FUNCTION 0 20 STORE_NAME 2 (foo) 5 22 LOAD_NAME 2 (foo) 24 LOAD_NAME 1 (i) 26 CALL_FUNCTION 1 28 POP_TOP 30 JUMP_ABSOLUTE 10 &gt;&gt; 32 POP_BLOCK &gt;&gt; 34 LOAD_CONST 3 (None) 36 RETURN_VALUE As @avigil suggested, it would be better to define the function outside the loop and pass loop variables as arguments.
downvote count: 0
has comment: http://stackoverflow.com/comment/85402031
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49197683
accepted answer of: http://stackoverflow.com/q/49197683
type: Answer

http://stackoverflow.com/comment/85319019
type: AnswerComment
has text: Haha, that was the fastest answer so far. Thank you! Never seen the swaplevel-functionality before, but your answer works perfectly!
type: Comment
comment on: http://stackoverflow.com/a/49157029
score: 0

http://stackoverflow.com/a/51207656
answers question: http://stackoverflow.com/q/49218390
type: Answer
has comment: http://stackoverflow.com/comment/101810375
score: 15
upvote count: 15
has body: The fact that there is no PyPi module for this and Ubuntu uses ancient python versions is pretty annoying, it would be nice if someone could fix this. In the meantime: To generate secrets in older versions of Python (>= 2.4 and &lt;= 3.5) you can use the urandom function from the os library. Example: from os import urandom urandom(16) # same as token_bytes(16) urandom(16).hex() # same as token_hex(16) (python &gt;=3.5) To make something backwards compatible that still uses the new secrets library when supported you could do something like try: from secrets import token_hex except ImportError: from os import urandom def token_hex(nbytes=None): return urandom(nbytes).hex()
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49218390

http://stackoverflow.com/a/49250667
score: 4
has comment: http://stackoverflow.com/comment/85506849
has comment: http://stackoverflow.com/comment/85505224
answers question: http://stackoverflow.com/q/49250515
downvote count: 0
type: AcceptedAnswer
has body: You need to use 'urlparse' library. Python2 &gt;&gt;&gt; import urlparse &gt;&gt;&gt; url = "https://www.youtube.com/watch?v=VgC4b9K-gYU" &gt;&gt;&gt; url_parsed = urlparse.urlsplit(url) &gt;&gt;&gt; qsl = urlparse.parse_qs(url_parsed.query) &gt;&gt;&gt; qsl {'v': ['VgC4b9K-gYU']} Python3 from urllib import parse url = "https://www.youtube.com/watch?v=VgC4b9K-gYU" url_parsed = parse.urlparse(url) qsl = parse.parse_qs(url_parsed.query)
accepted answer of: http://stackoverflow.com/q/49250515
has comment: http://stackoverflow.com/comment/85505086
has comment: http://stackoverflow.com/comment/85505234
type: Answer
has comment: http://stackoverflow.com/comment/85506595
upvote count: 4

javascript
tags question: http://stackoverflow.com/q/49128065
tags question: http://stackoverflow.com/q/49268188
tags question: http://stackoverflow.com/q/49266786
tags question: http://stackoverflow.com/q/49208083
tags question: http://stackoverflow.com/q/49241455
tags question: http://stackoverflow.com/q/49143579
tags question: http://stackoverflow.com/q/49144538
tags question: http://stackoverflow.com/q/49277041
tags question: http://stackoverflow.com/q/49203844
tags question: http://stackoverflow.com/q/49203300
tags question: http://stackoverflow.com/q/49141209
tag name: javascript
tags question: http://stackoverflow.com/q/49228987
tags question: http://stackoverflow.com/q/49152232
tags question: http://stackoverflow.com/q/49248022
tags question: http://stackoverflow.com/q/49171039
tags question: http://stackoverflow.com/q/49201067
tags question: http://stackoverflow.com/q/49245150
tags question: http://stackoverflow.com/q/49145259
tags question: http://stackoverflow.com/q/49196889
tags question: http://stackoverflow.com/q/49272177
tags question: http://stackoverflow.com/q/49215541
tags question: http://stackoverflow.com/q/49207457
tags question: http://stackoverflow.com/q/49262352
tags question: http://stackoverflow.com/q/49230389
type: Tag
tags question: http://stackoverflow.com/q/49175720
tags question: http://stackoverflow.com/q/49257981
tags question: http://stackoverflow.com/q/49273858
tags question: http://stackoverflow.com/q/49171414

http://stackoverflow.com/comment/85549630
score: 0
type: AnswerComment
has text: Thanks @Michael, your short code helped me. I've also found something matching better ! :-)
comment on: http://stackoverflow.com/a/49269275
type: Comment

http://stackoverflow.com/comment/85687572
has text: What happens when you comment out the `print i*sizeOfPacket` statement?
comment on: http://stackoverflow.com/q/49170605
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49215277
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85434915
type: UnansweredQuestion
tagged with: function
tagged with: python
has answer: http://stackoverflow.com/a/49215417
score: 0
has body: I am new to programming and I have a simple pig latin code. Just wanted some advice on how the code can ignore special characters, meaning they are returned to the same place. For instance, in pig latin if a word begins with a vowel you add 'hay' to the end: if word[0] in VOWELS: print (word + "hay",end=' ') so egg would become egghay however if the input was !.egg how can I ignore the !. so it becomes !.egghay Is there a way to write code in which each character is looked at and if it is not in string.ascii_letter it is temporarily ignored. ` Thanks
upvote count: 1
answer count: 1
downvote count: 1
has title: Pig Latin keeping special characters python

http://stackoverflow.com/comment/85369573
comment on: http://stackoverflow.com/a/49181872
type: Comment
score: 0
type: AnswerComment
has text: `var` should be the variable `var`, not the string `'var'`. But yes, `isinstance(var, str)` should be true—as it is in the OP's question. If the value of `var` is a string, `'Bitcoin'`, then `getattr(classobj, var)` is the same as `getattr(classobj, 'Bitcoin')`, which is the same as `classobj.Bitcoin`. See [the docs](https://docs.python.org/3/library/functions.html#getattr).

http://stackoverflow.com/q/49132111
has body: I want to create sequences of my dataset. However, Tensorflow only provides the function: tf.parse_single_example() I tried to avoid this problem by using the tf.py_func and smth like this: dataset.map(lambda x: tf.py_func(_parse_tf_record, [x, sequence_length]) for sequence_id in range(0, sequence_length): filename = x # files only contain one record for record in tf.python_io.tf_record_iterator(filename, options): ... tf.parse_single_example() ... break # only one sample per file So for every map call I read #sequence_length files. However, this cannot be done parallel since tf.py_func does not allow for it.
answer count: 1
has comment: http://stackoverflow.com/comment/85270197
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/85270396
type: UnansweredQuestion
tagged with: python
has title: Tensorflow is there anything like parse_multiple_examples
score: 0
has answer: http://stackoverflow.com/a/49133591

http://stackoverflow.com/a/49162524
downvote count: 1
type: Answer
score: -1
answers question: http://stackoverflow.com/q/49162200
upvote count: 0
has body: If you were willing to not use python, and as you are on windows, you could just use Powershell to iterate over lines in the file, see Read file line by line in PowerShell

http://stackoverflow.com/q/49275893
answer count: 0
has comment: http://stackoverflow.com/comment/85560853
has title: Tabula - Read the PDF's table content
type: Question
linked to: http://stackoverflow.com/q/36324
has body: While reading the PDF content, I got the below error. File "PDF_Conversion.py", line 4, in df = tabula.read_pdf("new_20170630.pdf") File "C:\Python27\lib\subprocess.py", line 672, in init errread, errwrite) File "C:\Python27\lib\subprocess.py", line 882, in _execute_child startupinfo) WindowsError: [Error 2] The system cannot find the file specified
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85557584
tagged with: python
has comment: http://stackoverflow.com/comment/85554419
tagged with: tabula
score: 0

http://stackoverflow.com/comment/86085899
score: 0
type: Comment
has text: But this is isolated to Numpy or other similarly referenced libraries as well? If Numpy and your other libraries and resources are in the same location but others can be referenced, then that's very strange.
type: AnswerComment
comment on: http://stackoverflow.com/a/49497946

http://stackoverflow.com/a/49198358
upvote count: 1
has comment: http://stackoverflow.com/comment/85403599
type: Answer
has body: you could do str.replace("DROP TABLE ","") Then str.replace(";","")
accepted answer of: http://stackoverflow.com/q/49198261
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49198261

http://stackoverflow.com/comment/85469442
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49232492
score: 0
has text: Okay I found the issue, see my edit, needs probably a new question.

http://stackoverflow.com/a/49134248
downvote count: 1
has body: I assume you want just the contours to be saved as SVG image. First, you need to compute the contours in your canny image using the findContorus function of OpenCV. Please be careful here, your contours MUST be well defined. Second, having your contours just follow this question: Convert contour paths to svg paths The SVG paths can be opened in any image processing software (e.g. Inkscape, Photoshop, etc)
accepted answer of: http://stackoverflow.com/q/49133484
upvote count: 10
score: 9
answers question: http://stackoverflow.com/q/49133484
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/49218302
upvote count: 51
has body: I have seen both ways but I do not understand what the difference is and what I should use as "best practice": def custom_function(**kwargs): foo = kwargs.pop('foo') bar = kwargs.pop('bar') ... def custom_function2(**kwargs): foo = kwargs.get('foo') bar = kwargs.get('bar') ...
has answer: http://stackoverflow.com/a/49218339
score: 50
has answer: http://stackoverflow.com/a/49218340
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/50215635
answer count: 4
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85440411
has answer: http://stackoverflow.com/a/49218410
has comment: http://stackoverflow.com/comment/96336328
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/98174207
tagged with: keyword-argument
has comment: http://stackoverflow.com/comment/85440391
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/112309159
has title: Python: Difference between kwargs.pop() and kwargs.get()
tagged with: python-2.7

http://stackoverflow.com/q/49128661
tagged with: parsing
type: Question
accepted answer: http://stackoverflow.com/a/49175136
score: 0
tagged with: pycparser
answer count: 1
has answer: http://stackoverflow.com/a/49175136
type: AnsweredQuestion
has title: pycparser ParseError
has body: I am trying to creat AST usinfg pyCparser, The following error printed: Traceback (most recent call last): File "C:\Work\RE\Tools\VarsExporter\BuildExportedDb.py", line 1076, in main() File "C:\Work\RE\Tools\VarsExporter\BuildExportedDb.py", line 1032, in main ast = parse_file(i_file) File "C:\Python27\lib\site-packages\pycparser_init_.py", line 93, in parse_file return parser.parse(text, filename) File "C:\Python27\lib\site-packages\pycparser\c_parser.py", line 152, in parse debug=debuglevel) File "C:\Python27\lib\site-packages\pycparser\ply\yacc.py", line 331, in parse return self.parseopt_notrack(input, lexer, debug, tracking, tokenfunc) File "C:\Python27\lib\site-packages\pycparser\ply\yacc.py", line 1199, in parseopt_notrack tok = call_errorfunc(self.errorfunc, errtoken, self) File "C:\Python27\lib\site-packages\pycparser\ply\yacc.py", line 193, in call_errorfunc r = errorfunc(token) File "C:\Python27\lib\site-packages\pycparser\c_parser.py", line 1761, in p_error column=self.clex.find_tok_column(p))) File "C:\Python27\lib\site-packages\pycparser\plyparser.py", line 67, in _ parse_error raise ParseError("%s: %s" % (coord, msg)) ParseError: Objectffly\SerDb.i:43:18: before: __loff_t What causes the above issue? How Can I handle it? Any suggestions how can I debug it, and find out what's going on?
tagged with: python
tagged with: http://stackoverflow.com/tag/c

http://stackoverflow.com/comment/85436608
score: 0
type: Comment
has text: Update: There was no performance gain. The query took the exact amount of time to display the output.
type: QuestionComment
comment on: http://stackoverflow.com/q/49199100

http://stackoverflow.com/a/49266322
type: Answer
answers question: http://stackoverflow.com/q/49265975
downvote count: 0
upvote count: 1
score: 1
has body: Your print statement is in an inner loop. You can fix your code like this: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] x = [] def less_than_five(): for item in a: if item &lt; 5: x.append(item) print(x) less_than_five()

http://stackoverflow.com/q/49264265
tagged with: server
has comment: http://stackoverflow.com/comment/85532015
tagged with: sockets
tagged with: ssl
tagged with: python
has comment: http://stackoverflow.com/comment/85535163
has comment: http://stackoverflow.com/comment/85532387
has comment: http://stackoverflow.com/comment/85537766
favorite count: 0
type: Question
score: 2
has title: Received data from python SSL server is incorrect
has comment: http://stackoverflow.com/comment/85534371
upvote count: 2
has comment: http://stackoverflow.com/comment/85536913
accepted answer: http://stackoverflow.com/a/49267998
has comment: http://stackoverflow.com/comment/85539379
has comment: http://stackoverflow.com/comment/85535919
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49267998
has comment: http://stackoverflow.com/comment/85534044
has comment: http://stackoverflow.com/comment/85539770
has body: I am trying to modify a socket server I wrote with the python socket library to use encryption using python's SSL library. I am no able to successfully open a connection to the server, wrap it with an SSL context and send data to the server, but data sent back to the client is not what it should be. My suspicion is that the server responses are not being decrypted on the client side, but I don't know why. I'm pretty new to SSL/TLS, and networking in general so... what am I missing? The client is also written in python (for now, to facilitate testing) Code: Relevant Server stuff: def sslServerLoop(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen(5) context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) context.load_cert_chain('cert.pem') while True: conn, addr = s.accept() sslConn = context.wrap_socket(conn, server_side=True) data = sslConn.recv(1024) sslConn.sendall(response) sslConn.close() Relevant Client stuff: context = ssl.create_default_context(cafile='cert.pem') s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = context.wrap_socket(s, server_hostname=server_addr) s.connect((address, port)) s.sendall(msg) s.shutdown(socket.SHUT_WR) response = s.recv(1024) Sending from client to server works fine, but data sent back to the client is wrong. For example if I set response = bytes([1]) on the server side, I receive b'\x17\x03\x03\x00\x19\xac\xb6\x7f@\xc0\xd3\xce%\x13G\x01\xbd\x88y\xf0\xda..\x02\xf9\xe4o\xdd\x1a\xdb' on the client side. Most of that changes every time I try to run it, but the first 5 bytes are always the same (which is partly why I suspect it isn't being decrypted). cert.pem is a self signed certificate generated using openssl as described in the python 3 SSL module documentation
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85534762

http://stackoverflow.com/a/49302004
upvote count: 1
has comment: http://stackoverflow.com/comment/85614587
answers question: http://stackoverflow.com/q/49279387
has comment: http://stackoverflow.com/comment/85614579
has comment: http://stackoverflow.com/comment/85616235
has comment: http://stackoverflow.com/comment/85616875
accepted answer of: http://stackoverflow.com/q/49279387
type: Answer
has comment: http://stackoverflow.com/comment/85616226
has comment: http://stackoverflow.com/comment/85626365
has comment: http://stackoverflow.com/comment/85614647
has body: Let's first make our two DataFrames, circles and squares. import pandas as pd import numpy as np circles = pd.DataFrame({'circle': {0: 1.0, 1: 2.0, 2: 3.0, 3: 4.0, 4: 5.0, 5: 6.0}, 'time': {0: 1.0, 1: 1.0, 2: 1.0, 3: 2.0, 4: 4.0, 5: 5.0}, 'x': {0: 235, 1: 236, 2: 245, 3: 215, 4: 287, 5: 394}, 'y': {0: 133, 1: 133, 2: 425, 3: 325, 4: 203, 5: 394}}) circles ------------------------------- circle time x y 0 1.0 1.0 235 133 1 2.0 1.0 236 133 2 3.0 1.0 245 425 3 4.0 2.0 215 325 4 5.0 4.0 287 203 5 6.0 5.0 394 394 squares = pd.DataFrame({'square': {0: 1.0, 1: 1.0, 2: 2.0, 3: 2.0, 4: 3.0, 5: 3.0}, 'time': {0: 1.0, 1: 2.0, 2: 3.0, 3: 4.0, 4: 4.0, 5: 5.0}, 'x': {0: 243, 1: 293, 2: 189, 3: 189, 4: 176, 5: 374}, 'y': {0: 233, 1: 436, 2: 230, 3: 233, 4: 203, 5: 394}})\ .set_index('time') squares ------------------ square x y time 1.0 1.0 243 233 2.0 1.0 293 436 3.0 2.0 189 230 4.0 2.0 189 233 4.0 3.0 176 203 5.0 3.0 374 394 So those are our DataFrames, let's define a function that we can apply to each circle in circles which will return us the corresponding closest square. def closest_square(circleseries): """ This function takes a pd.Series which is what pd.DataFrame.apply gives the function that you apply, in this case to the DataFrame circles. So the pd.Series it will get from apply will represent a single circle. We use loc to get the squares at the correct time point which gives us a DataFrame that is a subset of squares. We then use assign to give that DataFrame an extra column with the distance and the ID of the circle. Finally we sort this whole thing in ascending order by the distance to our circle, take the square with the lowest distance to our circle (iloc[0]). We also reset the index because we don't want the time column from squares to be our but a regular column. """ return squares.loc[[circleseries.time], :]\ .assign(distance = lambda s: np.sqrt( (s.x- circleseries.x)**2 + (s.y- circleseries.y)**2), circle=circleseries.circle)\ .sort_values('distance', ascending…
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85536566
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49266014
score: 0
has text: So if @ImportanceOfBeingErnest is correct, seaborn just samples a bunch of data randomly from my data. Is that right? It would make sense since the visualizations done with it seemed not to fully represent the data.

http://stackoverflow.com/comment/85350327
score: 0
type: QuestionComment
type: Comment
has text: I guess you are familiar with storing and accessing objects in AWS (s3?), since you say that the images are stored on AWS. In general you convert the image to bytes string, upload this file object to AWS and then store key (usually a filename) in your database, because you'll be accessing files with this key. I suggest you update your question, because this is really a question about uploading files to AWS. The Django part is basically the simplest thing here.
comment on: http://stackoverflow.com/q/49170964

http://stackoverflow.com/a/61596986
downvote count: 0
answers question: http://stackoverflow.com/q/49255283
has body: What I did was: which flask, to find flask binary executable path (in my case /home/myuser/.local/bin/flask edit /home/myuser/.local/bin/flask, changing the first line from #!/usr/bin/python to #!/usr/bin/python3 In summary, making flask use python3, regardless of which shebang was specified in other scripts, since those scripts are not the entrypoint of execution, but flask is. I didn't have to change the shebang in any of my scripts, just the flask executable.
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/a/49203158
has body: Django docs don't make this particularly clear, but the clean() method on a model is only called when processing data with a ModelForm, or when you copy the approach that a ModelForm takes for validation: i.e., following the three steps listed here: https://docs.djangoproject.com/en/2.0/ref/models/instances/#validating-objects Edit: As in, if you call clean() by itself, you will likely find null values as you did, since Model.clean_fields() hasn't been run yet.
upvote count: 0
downvote count: 2
score: -2
type: Answer
has comment: http://stackoverflow.com/comment/85411773
answers question: http://stackoverflow.com/q/49202578

http://stackoverflow.com/comment/85278860
has text: The regex I am using matches with the rest of the nmap out put format which is as follows. PORT STATE SERVICE REASON VERSION 22/tcp closed service1 reason one 52 1883/tcp closed service3 reason two 52 8883/tcp open service4 reason four 52
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49131708
type: Comment

http://stackoverflow.com/a/49225474
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49225346
has body: A superficial examination of your code checks out. When you write a generator function and call it the call returns a generator whose __next__ method is typically repeatedly called by an iteration until it raises the StopIteration exception. A generator is a special case of an iterator. Iterables like lists have an __iter__ method that produce an iterator. Unless you want to send values into your generator as well as get them out, your DataGenerator is a reasonable way to implement an iterator, but to write an iterable you'd need another class whose __iter__ method returns an instance of DataGenerator. The answers at How to implement __iter__(self) for a container object (Python) might also be helpful.
accepted answer of: http://stackoverflow.com/q/49225346
type: Answer
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/85428879
type: QuestionComment
has text: Also, thanks for the link, @PatrickArtner, it is helpful.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49211520

http://stackoverflow.com/comment/85369154
type: AnswerComment
has text: Worked like a charm. Kept the original formatting which may help in the end. Thanks!
comment on: http://stackoverflow.com/a/49149378
type: Comment
score: 0

http://stackoverflow.com/a/49247346
has comment: http://stackoverflow.com/comment/114351433
answers question: http://stackoverflow.com/q/49231442
has comment: http://stackoverflow.com/comment/114352096
upvote count: 2
has comment: http://stackoverflow.com/comment/114352081
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/114352134
has comment: http://stackoverflow.com/comment/114351778
has body: If you are looking for the solution yet, how about this? The structure of attendees is as follows. { "items": [ { "attendees": [ { "email": "### email ###", "displayName": "### name ###", "responseStatus": "#####" } ] } ] } So how about this modification? From : for event in events: start = event['start'].get('dateTime', event['start'].get('date')) end = event['end'].get('dateTime', event['end'].get('date')) attendees = event['attendees'].get('email', event['attendees'].get('email')) print(attendees) To : for event in events: start = event['start'].get('dateTime', event['start'].get('date')) end = event['end'].get('dateTime', event['end'].get('date')) print("{0}, {1}".format(start, end)) for attendee in event['attendees']: attendees = attendee.get('email', attendee.get('email')) print(attendees) If I misunderstand your question and you already have the solution, I'm sorry.
accepted answer of: http://stackoverflow.com/q/49231442

http://stackoverflow.com/q/49244476
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85493265
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85492995
has comment: http://stackoverflow.com/comment/85493314
has title: Add Commas Between Elements
has comment: http://stackoverflow.com/comment/85493135
has answer: http://stackoverflow.com/a/49245120
has comment: http://stackoverflow.com/comment/85493462
tagged with: python
has body: I have a data structure that looks like this: [[ date person 0 1/1/2018 john 1 1/3/2018 jane 2 1/9/2018 john ] [ date person 0 2/1/2018 john 1 2/3/2018 jane 2 2/9/2018 john ]] It is a list of lists, but there are no commas between each element in the list. Therefore, when attempting to convert the list to a pandas DataFrame, assertion errors occur because the nested list is technically one column, whereas the target df is two columns. How would I add commas to the nested list or otherwise convert it into a df that looks like the one below? date person 1/1/2018 john 1/3/2018 jane 1/9/2018 john 2/1/2018 john 2/3/2018 jane 2/9/2018 john
has comment: http://stackoverflow.com/comment/85493307
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/85493214
accepted answer: http://stackoverflow.com/a/49245120
has comment: http://stackoverflow.com/comment/85493069
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85493037

http://stackoverflow.com/a/49128886
type: Answer
has body: This seems like an XY problem. Below are some options, depending on what you are really looking to do. Only include numeric types and return list arr = [[1,'b',2], [3,':',4], [5,':',6]] def is_num(x): return isinstance(x, (int, float)) arr = [[i for i in k if is_num(i)] for k in arr] # [[1, 2], [3, 4], [5, 6]] Only exclude 'b' and ':' characters and return list See @Coldspeed's solution.
has comment: http://stackoverflow.com/comment/85262329
score: 0
has comment: http://stackoverflow.com/comment/85262400
has comment: http://stackoverflow.com/comment/85262284
has comment: http://stackoverflow.com/comment/85262254
answers question: http://stackoverflow.com/q/49128622

http://stackoverflow.com/a/69870853
score: -2
type: Answer
answers question: http://stackoverflow.com/q/49201236
has body: As @fábio-perez mentioned, there is no such built-in function in PyTorch. However, I found this to be a compact and neat way of achieving the same result: num_of_parameters = sum(map(torch.numel, model.parameters()))
upvote count: 0
downvote count: 2

generator
type: Tag
tags question: http://stackoverflow.com/q/49186622
tags question: http://stackoverflow.com/q/49275927
tags question: http://stackoverflow.com/q/49188162
tags question: http://stackoverflow.com/q/49183564
tag name: generator
tags question: http://stackoverflow.com/q/49184345
tags question: http://stackoverflow.com/q/49224363
tags question: http://stackoverflow.com/q/49238992
tags question: http://stackoverflow.com/q/49225346
tags question: http://stackoverflow.com/q/49203550
tags question: http://stackoverflow.com/q/49179509
tags question: http://stackoverflow.com/q/49136756

http://stackoverflow.com/q/49209871
score: 0
tagged with: mongoengine
has comment: http://stackoverflow.com/comment/85426548
has title: django mongoengine unable to login using correct password
has body: I am using mongoengine with django rest framework and default User model： settings.py AUTHENTICATION_BACKENDS = ( 'mongoengine.django.auth.MongoEngineBackend', ) SESSION_ENGINE = 'mongoengine.django.sessions' SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer' MONGOENGINE_USER_DOCUMENT = 'mongoengine.django.auth.User' AUTH_USER_MODEL = 'mongo_auth.MongoUser' views.py from django.contrib.auth import login, logout from mongoengine.django.auth import User @csrf_exempt def log_in(request): js = json.loads(request.body) try: #user = User.objects.get(username=request.POST['username']) user = User.objects.get(username=js['username']) print user.username print user.password print js['username'] print js['password'] print user.password==js['password'] #if user.check_password(request.POST['password']): if user.check_password(js['password']): user.backend = 'mongoengine.django.auth.MongoEngineBackend' user = authenticate(username=js['username'], password=js['password']) login(request, user) request.session.set_expiry(60 * 60 * 1) # 1 hour timeout return HttpResponse(user) else: return HttpResponse('login failed') except DoesNotExist: return HttpResponse('user does not exist') except Exception: return HttpResponse('unknown error') With the correct password, I am getting login failed. What can be the reason for this?
type: Question
answer count: 0
tagged with: django
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85426998

http://stackoverflow.com/a/49185409
has body: What happened? All magic in here, function PySlice_AdjustIndices: if (*start &lt; 0) { *start += length; if (*start &lt; 0) { *start = (step &lt; 0) ? -1 : 0; } } else if (*start &gt;= length) { *start = (step &lt; 0) ? length - 1 : length; } if (*stop &lt; 0) { *stop += length; if (*stop &lt; 0) { *stop = (step &lt; 0) ? -1 : 0; } } else if (*stop &gt;= length) { *stop = (step &lt; 0) ? length - 1 : length; } if (step &lt; 0) { if (*stop &lt; *start) { return (*start - *stop - 1) / (-step) + 1; } } else { if (*start &lt; *stop) { return (*stop - *start - 1) / step + 1; } } In your case, start = 6, stop = -1, step = -1, length = 5 After calculated, start = 4, stop = 4, step = -1 Sum up: 5 = s[4:4:-1] 4 e = s[4:3:-1] 3 ed = s[4:2:-1] 2 edc = s[4:1:-1] 1 edcb = s[4:0:-1] 0 = s[4:4:-1] How to solve? s = 'abcde' length = len(s) for i in reversed(range(length + 1)): print(i, f'{s[-1:i-length-1:-1]:&gt;6}', f'{s[:i]:6}') output: 5 abcde 4 e abcd 3 ed abc 2 edc ab 1 edcb a 0 edcba
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49184565
has comment: http://stackoverflow.com/comment/85379119
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49184565
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49265308
accepted answer of: http://stackoverflow.com/q/49265027
type: Answer
has comment: http://stackoverflow.com/comment/85534165
score: 4
answers question: http://stackoverflow.com/q/49265027
has body: i, j = np.triu_indices(len(df), 1) pd.Series( df.values[i, j], df.index[i] + df.index[j] ).sort_values(ascending=False) EF 9 CF 9 CE 8 DF 6 BC 3 DE 2 AE 2 CD 1 BF 1 BE 1 BD 1 AD 1 AB 1 AF 0 AC 0 dtype: object Setup txt = """\ A B C D E F A 0 1 0 1 2 0 B 0 3 1 1 1 C 0 1 8 9 D 0 2 6 E 0 9 F 0""" df = pd.read_fwf(pd.io.common.StringIO(txt), index_col=0).fillna('') df A B C D E F A 0 1 0 1 2 0 B 0 3 1 1 1 C 0 1 8 9 D 0 2 6 E 0 9 F 0
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85534459
has comment: http://stackoverflow.com/comment/85534818
has comment: http://stackoverflow.com/comment/85534684

http://stackoverflow.com/q/49160429
tagged with: tensorflow
favorite count: 0
type: AnsweredQuestion
has body: Just a beginner with Tensorflow. I am trying to run a classification model with multiple numpy arrays as input with two possible categories that it would be classified it into. I am not able to get it run. I tried looking at the tutorials and other threads but I haven't gotten any ideas. Does anyone know how to create a model that accepts multiple parameters as arrays? feedmag feedlat feedtime and feedlong are numpy arrays Here is the error message: label_ids format(labels.dtype)) ValueError: Labels dtype should be integer. Instead got . Here is my code. for i in range (0,34): labels = np.append(labels,int(1)); for i in range (0,34): labels = np.append(labels,int(2)); feature = {'magnitude': feedmag, 'time': feedtime, 'latitude': feedlat, 'longitude': feedlong} my_feature_columns = [] for key in feature.keys(): my_feature_columns.append(tf.feature_column.numeric_column(key=key)) classifier = tf.estimator.DNNClassifier( feature_columns=my_feature_columns, # Two hidden layers of 10 nodes each. hidden_units=[10, 10], n_classes = 4; # The model must choose between 3 classes. optimizer=tf.train.ProximalAdagradOptimizer( learning_rate=0.1, l1_regularization_strength=0.001)) with tf.Session() as session: train_input_fn = tf.estimator.inputs.numpy_input_fn( feature, labels, num_epochs=1, shuffle=True, batch_size=33) test_input_fn = tf.estimator.inputs.numpy_input_fn( feature, labels, num_epochs=1, shuffle=False, batch_size=33) classifier.train(input_fn = lambda: train_input_fn) print('starting') print(classifier.evaluate( input_fn=test_input_fn, steps = 33)) print("ending") print(tf.VERSION)
score: 1
tagged with: python
has title: Tensorflow classification program with multiple parameters
has comment: http://stackoverflow.com/comment/85326479
type: Question
has comment: http://stackoverflow.com/comment/85326891
tagged with: classification
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49160480
upvote count: 1
tagged with: machine-learning
has answer: http://stackoverflow.com/a/49160480

http://stackoverflow.com/comment/85382770
type: Comment
comment on: http://stackoverflow.com/a/49188242
type: AnswerComment
score: 0
has text: Not pretty sure why numpy doesn't have this indexing mode. Adding a slice version to range indexing sounds very reasonable.

http://stackoverflow.com/comment/85257220
type: Comment
comment on: http://stackoverflow.com/a/49126113
score: 0
type: AnswerComment
has text: This works thanks, but I wanted it so that code, name, total orders don't repeat when I export it to csv. I am thinking it should be possible using group by.

http://stackoverflow.com/q/49226804
possible better answer: http://stackoverflow.com/a/49226867
has answer: http://stackoverflow.com/a/49226880
type: Question
has answer: http://stackoverflow.com/a/49226867
has body: I'm quite new to Python and I am trying to make a little adventure game, just to develop my skills. So, for my game, I want there to be a few options, and the player will pick one and it will return a different result. However, the options will not always be the same, so I decided to make a function, so the options and results could differ. Here is the code for my function: def action(act1, act2, act3, act4): loop = True while loop: print(menu) player_action = input("Where would you like to go? ") if player_action == '1': act1 return elif player_action == '2': act2 return elif player_action == '3': act3 return elif player_action == '4': act4 return else: print("Please type \'1\', \'2\', \'3\', or \'4\'") The parameters are functions for what I want to print out. My problem is, when I call this function and run the code, Python executes each function in every if and elif statement. For example, when I call this: def home_act1(): print("Welcome to the wilderness!") def home_act2(): print("Welcome to the town!") def home_act3(): print("Welcome to the store!") def home_act4(): print("You left the adventure.") exit() action(home_act1(), home_act2(), home_act3(), home_act4()) I run the program and it does this: Welcome to the wilderness! Welcome to the town! Welcome to the store! You left the adventure. Process finished with exit code 0 It seems to just be running all four of my parameters, it worked before I made it a function but something isn't working right. Thanks to any help!
tagged with: python
accepted answer: http://stackoverflow.com/a/49226907
has answer: http://stackoverflow.com/a/49226907
tagged with: python-3.x
type: AnsweredQuestion
answer count: 3
downvote count: 0
has title: Python - Input Menu Function
upvote count: 1
score: 1
favorite count: 0

http://stackoverflow.com/comment/85252246
type: QuestionComment
score: 0
has text: Which part confuse you? Anyway I got `10123`.
comment on: http://stackoverflow.com/q/49123464
type: Comment

http://stackoverflow.com/comment/85418702
comment on: http://stackoverflow.com/q/49206811
type: Comment
has text: You say two answers both worked, but one used `raw_input()`, which is Python 2, and one used `input()`, which is Python 3 (the Python 2 version of `input()` has a different use). Which version of Python are you using?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85552840
type: Comment
comment on: http://stackoverflow.com/q/49271785
type: QuestionComment
has text: does your template.html refer only to {0} and {1} or also to a missing {2} ?
score: 1

http://stackoverflow.com/q/49272452
has title: Aggregate multiple columns in a dataframe based on custom functions
score: 2
type: AnsweredQuestion
tagged with: pandas
tagged with: summary
possible better answer: http://stackoverflow.com/a/49274216
has answer: http://stackoverflow.com/a/49274216
accepted answer: http://stackoverflow.com/a/49273942
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49273942
type: Question
has body: Afternoon All, I have been trying to resolve this for awhile, any help would be appreciated. Here is my dataframe: Channel state rfq_qty A Done 10 B Tied Done 10 C Done 10 C Done 10 C Done 10 C Tied Done 10 B Done 10 B Done 10 I would like to: Group by channel, then state Sum the rfq_qty for each channel Count the occurences of each 'done' string in state ('Done' is treated the same as 'Tied Done' i.e. anything with 'done' in it) Display the channels rfq_qty as a percentage of the total number of rfq_qty (80) Channel state rfq_qty Percentage A 1 10 0.125 B 3 30 0.375 C 4 40 0.5 I have attempted this with the following: df_Done = df[ ( df['state']=='Done' ) | ( df['state'] == 'Tied Done' ) ]'Channel','state','rfq_qty' df_Done['Percentage_Qty']= df_Done['rfq_qty']/df_Done['rfq_qty'].sum() df_Done['Done_Trades']= df_Done['state'].count() display( df_Done[ (df_Done['Channel'] != 0) ].groupby(['Channel'])['Channel','Count of Done','rfq_qty','Percentage_Qty'].sum().sort_values(['rfq_qty'], ascending=False) ) Works but looks convoluted. Any improvements?
answer count: 2
upvote count: 2
tagged with: group-by
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/49142500
downvote count: 0
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49142309
has body: Method Create a list of targets. Create a dictionary which will associate to each column name, the list of the percentages corresponding to the targets. Loop on the targets, and for each target, loop on the columns to calculate the percentage and put it in the dictionary. Create a DataFrame with the dictionary and the list of targets. Code df_A = pd.DataFrame(data = { "d01": [ 0.028, 0.051, 0.084, 0.061, 0.015], "d02": [ 0.021, 0.063, 0.084, 0.061, 0.015], "d03": [ 0.028, 0.093, 0.084, 0.072, 0.015] }) target = [.02, .04, .06, .08, .15, .20, .25, .30] dic = {key: [] for key in df_A} for t in target: for key in dic: s = 0 for val in df_A[key]: if val &gt;= t: s += 1 dic[key].append(s / len(df_A[key])) df_B = pd.DataFrame(data = dic, index = target) Result on the example df_B d01 d02 d03 0.02 0.8 0.8 0.8 0.04 0.6 0.6 0.6 0.06 0.4 0.6 0.6 0.08 0.2 0.2 0.4 0.15 0.0 0.0 0.0 0.20 0.0 0.0 0.0 0.25 0.0 0.0 0.0 0.30 0.0 0.0 0.0

http://stackoverflow.com/comment/85590743
type: AnswerComment
has text: Wow... I didn't know it reasons this way :( now I'm going to figure out how to fix this. No idea at the moment, I'll let you know asap. Thank you
comment on: http://stackoverflow.com/a/49278909
type: Comment
score: 0

http://stackoverflow.com/a/49258320
upvote count: 1
score: 1
type: AcceptedAnswer
has body: You can use to_datetime to transform to datetime format, and then strftime to adjust your format: df['col_date'] = pd.to_datetime(df['col_date'], format="%b-%y").dt.strftime('%b-%Y') Input: col_date val 0 Oct-12 1154293 1 Nov-12 885773 2 Dec-12 -448704 3 Jan-13 563679 4 Feb-13 555394 5 Mar-13 631974 6 Apr-13 957395 7 May-13 1104047 8 Jun-13 693464 Output: col_date val 0 Oct-2012 1154293 1 Nov-2012 885773 2 Dec-2012 -448704 3 Jan-2013 563679 4 Feb-2013 555394 5 Mar-2013 631974 6 Apr-2013 957395 7 May-2013 1104047 8 Jun-2013 693464 Note the lower case y for 2 digits year and upper case Y for 4 digits year.
has comment: http://stackoverflow.com/comment/85533444
answers question: http://stackoverflow.com/q/49242856
type: Answer
accepted answer of: http://stackoverflow.com/q/49242856
downvote count: 0

http://stackoverflow.com/q/49275602
score: 3
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/119021326
tagged with: python-2.7
upvote count: 3
type: UnansweredQuestion
answer count: 1
downvote count: 0
has body: I am using the Python logging module in my application. Here is my current format. LOGGER_FORMAT = '%(asctime)s %(levelname)-5s [%(threadName)-10s] %(name)s.%(module)s.%(funcName)s : %(message)s' logging.basicConfig(level=logging.INFO, format=LOGGER_FORMAT) And a sample output: 2018-03-14 11:35:27,257 INFO [Thread-2 ] my_app.util.get_login_info : Log line 1 2018-03-14 11:35:27,257 INFO [Thread-2 ] my_app.cache.call : Log line 2 2018-03-14 11:35:27,257 INFO [Thread-2 ] my_app.web.parse_response : Log line 3 What I am looking for is that I get the message displayed from the fixed position instead of varying start points. I am able to configure the fixed length for each individual attribute, but I wanted to configure a fixed length for the entire name.module.funcName part, so that my output is like below: 2018-03-14 11:35:27,257 INFO [Thread-2 ] my_app.util.get_login_info : Log line 1 2018-03-14 11:35:27,257 INFO [Thread-2 ] my_app.cache.call : Log line 2 2018-03-14 11:35:27,257 INFO [Thread-2 ] my_app.web.parse_response : Log line 3 Is it possible, and how can I configure this?
has answer: http://stackoverflow.com/a/49284249
tagged with: flask
favorite count: 0
tagged with: logging
tagged with: python-3.x
has title: Fixed Length Formatting for Combination of Fields in Python logging modules

http://stackoverflow.com/comment/85442669
has text: seems that `followers_count` might be a second level key? inside another one? It would be much more easier to give a proper answer if you posted the output of `print(obj.keys())`, otherwise is just guesswork.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49219352

http://stackoverflow.com/comment/85488950
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49242539
score: 0
has text: No i'm not signed in currently

http://stackoverflow.com/a/49210641
has body: As @jrjames83 has already explained in his answer after reshaping (.reshape(1,-1)) you were feeding a data set containing one sample (row) and four features (columns): In [103]: x.shape Out[103]: (1, 4) most probably you wanted to reshape it this way: In [104]: x = df['x'].values.reshape(-1, 1) In [105]: x.shape Out[105]: (4, 1) so that you would have four samples and one feature... alternatively you could pass DataFrame columns to your model as follows (no need to pollute your memory with additional variables): In [98]: clf = lm.LinearRegression(fit_intercept =True) In [99]: clf.fit(df'x',df['y']) Out[99]: LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False) In [100]: clf.coef_ Out[100]: array([0.247]) In [101]: clf.intercept_ Out[101]: 4.5
answers question: http://stackoverflow.com/q/49209949
type: Answer
score: 0

http://stackoverflow.com/a/49137981
score: 1
upvote count: 1
has body: The construct would be recursion. But recursion requires that your call stack ends at some point. Such a case could work with an algorithm such as: if(x == 0): return 1 # this will make sure it ends at the preceding line in the next call return f(x - 1) This is typically the approach used to compute results such as the factorial. To use an example, adding a requirement (that you only compute if x &lt; 2, just as an example): def f(x): if(x &lt; 2): return 1 return f(x/2+1) The key is that there be a point at which the call stack starts returning (to avoid an overflow)
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49137796

http://stackoverflow.com/comment/85540819
has text: Just unindent that line and put a `:` at the end...
comment on: http://stackoverflow.com/q/49268770
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49272597
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/49294171
has answer: http://stackoverflow.com/a/64165798
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49294171
has body: I am trying to implement multi-task CNN using adaptive loss_weight, which decays as the epoch increases. I referred to this Github issue. # callback for adaptive loss_weight class LossWeightCallback(Callback): def __init__(self, alpha): self.alpha = alpha def on_epoch_end(self, epoch, logs={}): self.alpha = self.alpha * 0.9 # initial loss_weight alpha = K.variable(10) # model img_input = Input(shape=(224, 224, 3), name='input') ... model = Model(inputs=img_input, outputs=[y1, y2]) # compile model.compile(keras.optimizers.SGD(lr=1e-4, momentum=0.9), loss={'output1': 'categorical_crossentropy', 'output2': 'mse'}, loss_weights={'output1': 1, 'output2': alpha}, metrics={'output1': 'accuracy', 'output2': 'mse'}) # Fit model checkpointer = ModelCheckpoint('multitask_model.h5', monitor='val_output1_acc', verbose=1, save_best_only=True) results = model.fit(x_train, {'output1': y_train1, 'output2': y_train2}, validation_split=0.1, batch_size= 100, epochs=50, callbacks=[checkpointer, LossWeightCallback(alpha)]) But this code returns an error after the 1st epoch ends: TypeError: ('Not JSON Serializable:', &lt;tf.Variable 'Variable_1:0' shape=() dtype=float32_ref&gt;) Is there any solution to this error? Thank you in advance.
tagged with: tensorflow
type: Question
has title: TypeError: ('Not JSON Serializable:', <tf.Variable 'Variable_1:0' shape=() dtype=float32_ref>)
answer count: 2
upvote count: 2
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/64165798

http://stackoverflow.com/q/49268153
has answer: http://stackoverflow.com/a/49268198
has answer: http://stackoverflow.com/a/49268183
has comment: http://stackoverflow.com/comment/85539695
type: AnsweredQuestion
answer count: 3
has body: So the goal is to return "true" if the number 9 appears in the first 4 numbers of a list. I've done this by first creating a new list that contains only the first 4 numbers, and then checking if 9 appears there. def array_front9(nums): lst = [] lst.append(nums[:4]) if 9 in lst: return True else: return False for some reason, it always returns False. This means that either a) numbers are not being transferred to the new list or b) none of the numbers are visible when searching through it. I tested the first one by printing the new list, but I don't have any clue why the numbers wouldn't be visible. Please help!
downvote count: 2
has comment: http://stackoverflow.com/comment/85540305
possible better answer: http://stackoverflow.com/a/49268182
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49268182
upvote count: 0
score: -2
accepted answer: http://stackoverflow.com/a/49268198
has title: Checking for item in derived list
has comment: http://stackoverflow.com/comment/85539697
has comment: http://stackoverflow.com/comment/85539981
tagged with: python

http://stackoverflow.com/a/49166267
upvote count: 2
downvote count: 0
has body: Rather than using variables to store each letter, it would be more concise and easier to scale if you use a list and append each raw_input to the list. print "Welcome to the encoder" code_length = 12 code = [] for index in xrange(0, code_length): letter = raw_input ("Please input letter " + str(index) + " of the word: ") ordinal = ord(letter) - 96 code.append(str(ordinal)) print ' '.join(code)
has comment: http://stackoverflow.com/comment/85338037
has comment: http://stackoverflow.com/comment/85338013
has comment: http://stackoverflow.com/comment/85338156
type: Answer
answers question: http://stackoverflow.com/q/49166171
score: 2

http://stackoverflow.com/comment/85424164
comment on: http://stackoverflow.com/q/49206726
type: QuestionComment
has text: Hi @hwhite4, I think there's a problem because if the issue was from sandbox then it shouldn't send a signal from IPN sandbox.
type: Comment
score: 0

http://stackoverflow.com/q/49231584
has comment: http://stackoverflow.com/comment/85466675
tagged with: python
has body: I have a bit of an challenge before me. Currently I'm trying to accomplish this process: Feed a decimal, or any number really, into a binary converter Now that we possess a binary string, we must measure the length of the string. (as in, numstr="10001010" - I want the return to count the characters and return "8") Finally, I need to extract a section of said string, if I want to cut out the first half of the string "10001010" and save both halves, I want the return to read "1000" and "1010" Current Progess: newint=input("Enter a number:") newint2= int(newint) binStr="" while newint2&gt;0: binStr= str(newint2%2) + binStr newint2= newint2//2 print (binStr) newint = input("Enter a binary number:") temp=newint power = 0 number = 0 while len(temp) &gt; 0: bit=int(temp[-1]) number = number + bit * 2 ** power power+=1 temp = temp[:-1] print(number) //This works for integer values, how do I get it to also work for decimal values, where the integer is either there or 0 (35.45 or 0.4595)? This is where I'm lost, I'm not sure what the best way to attempt this next step would be. Once I convert my decimal or integer into binary representation, how can I cut my string by varying lengths? Let's say my binary representation is 100 characters, and I want to cut out lengths that are 10% the total length, so I get 10 blocks of 10 characters, or blocks that are 20% total length so I have 5 blocks of 20 characters. Any advice is appreciated, I'm a super novice and this has been a steep challenge for me.
score: -1
type: Question
linked to: http://stackoverflow.com/q/18854620
answer count: 2
has title: Python: Setting up a binary-number string converter, then indexing the result
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49233847
has comment: http://stackoverflow.com/comment/85466726
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49232142

http://stackoverflow.com/q/49222761
has body: I ran this code in Mac OS High Sierra terminal pip install -U spyder How do I open spyder as an interface? Thanks
has title: Spydr install and open - Mac
tagged with: spyder
tagged with: python
score: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49222891
answer count: 1
type: Question

http://stackoverflow.com/comment/85325842
type: QuestionComment
has text: @AnnaRudzińska I tried running $ chmod +x testris.py but the $ made it screw up. when I input chmod +x testris.py it just printed out another command line. I then tried to run learntris.py and got permission denied errors after the first test and the second test.
comment on: http://stackoverflow.com/q/49159808
score: 0
type: Comment

http://stackoverflow.com/q/49209771
has comment: http://stackoverflow.com/comment/85428375
has title: irregular Python/Scrapy scraping behaviour: Status 200 but data not always returned
tagged with: python
has comment: http://stackoverflow.com/comment/85429186
answer count: 0
downvote count: 0
upvote count: 1
tagged with: web-scraping
tagged with: scrapy
favorite count: 0
type: Question
has body: I've written a Python Scrapy spider to scrape 60,000 pages from a website. Each of the items extracted work greats, and when scraping approximately 4000 pages, I have no issues, I get a 200 status from each page and all data required is extracted. However when I start to scrape 8000 pages upwards, I am sometimes able to scrape all the data with 200 status codes, but on other occasions I get very few items returned. The output still displays all 8000 urls and a 200 status code for each, but very few associated items extracted. I notice that if the crawler has successfully scraped all 8000 pages, and is then run almost immediately again, this behaviour occurs. Its the same behaviour seen when trying to scrape all 60,000 pages. I have the following enabled within the settings.py file: ROBOTSTXT_OBEY = True My code is as follows: import scrapy import re import sqlite3 import time from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class UserItem(scrapy.Item): url = scrapy.Field() status = scrapy.Field() registered = scrapy.Field() class TestSpider(scrapy.Spider): name = "website" allowed_domains = ['source_website'] start_urls = ['http://source_website/page1', 'http://source_website/page2', 'http://source_website/page3', 'http://source_website/page4', 'http://source_website/page5',] def parse(self, response): hxs = scrapy.Selector(response) all_links = hxs.xpath('*//a/@href').extract() for link in all_links: yield scrapy.http.Request(url=response.urljoin(link), callback=self.ParseContents) def ParseContents(self, response): item = UserItem() item['url'] = response.url item['status'] = response.status data = (response.xpath('//html//text()').extract()) data = iter(data) for object in data: if "Registered" in object: item['registered'] = (next(data)) yield item Successful scrape log: 2018-03-10 17:49:09 [scrapy.statscollectors] INFO: Dumping Scrapy stats: {'downloader/exception_count': 1, 'downloader/exception_type_count/scrapy.exc…
type: UnansweredQuestion
score: 1

http://stackoverflow.com/a/49256982
score: 0
has body: @Rakesh - I got it worked after converting the output to strings. for vs in vser: as = str(vs.name) if re.match("(^(.)video(.)", as, re.I): print(as)
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49254242
answers question: http://stackoverflow.com/q/49254242
type: Answer

http://stackoverflow.com/a/51386680
type: Answer
accepted answer of: http://stackoverflow.com/q/49164809
has body: RESULT: Fixed it myself by reaching out to the developer team managing the API. I was using the wrong endpoint. I changed token_url to the following: token_url = 'https://api.manheim.com/oauth2/token.oauth2'
upvote count: 4
answers question: http://stackoverflow.com/q/49164809
type: AcceptedAnswer
downvote count: 0
score: 4

http://stackoverflow.com/q/49166819
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49167836
has answer: http://stackoverflow.com/a/49167836
tagged with: python
tagged with: lstm
type: AnsweredQuestion
has title: KeyError : The tensor variable , Refer to the tensor which does not exists
upvote count: 2
score: 2
has body: Using LSTMCell i trained a model to do text generation . I started the tensorflow session and save all the tensorflow varibles using tf.global_variables_initializer() . import tensorflow as tf sess = tf.Session() //code blocks run_init_op = tf.global_variables_intializer() sess.run(run_init_op) saver = tf.train.Saver() #varible that makes prediction prediction = tf.nn.softmax(tf.matmul(last,weight)+bias) #feed the inputdata into model and trained #saved the model #save the tensorflow model save_path= saver.save(sess,'/tmp/text_generate_trained_model.ckpt') print("Model saved in the path : {}".format(save_path)) The model get trained and saved all its session . Link to review the whole code lstm_rnn.py Now i loaded the stored model and tried to do text generation for the document . So,i restored the model with following code tf.reset_default_graph() imported_data = tf.train.import_meta_graph('text_generate_trained_model.ckpt.meta') with tf.Session() as sess: imported_meta.restore(sess,tf.train.latest_checkpoint('./')) #accessing the default graph which we restored graph = tf.get_default_graph() #op that we can be processed to get the output #last is the tensor that is the prediction of the network y_pred = graph.get_tensor_by_name("prediction:0") #generate characters for i in range(500): x = np.reshape(pattern,(1,len(pattern),1)) x = x / float(n_vocab) prediction = sess.run(y_pred,feed_dict=x) index = np.argmax(prediction) result = int_to_char[index] seq_in = [int_to_char[value] for value in pattern] sys.stdout.write(result) patter.append(index) pattern = pattern[1:len(pattern)] print("\n Done...!") sess.close() I came to know that the prediction variable does not exist in the graph. KeyError: "The name 'prediction:0' refers to a Tensor which does not exist. The operation, 'prediction', does not exist in the graph." Full code is available here text_generation.py Though i saved all tensorflow varibles , the prediction tensor is not saved in the tensorflow computation …
answer count: 1

http://stackoverflow.com/a/49210508
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49209595
has body: Clearly business.css('a.email-business::attr(href)').extract() returns a list. You need to remove mailto: from an item in list. s = business.css('a.email-business::attr(href)').extract() item['email'] = [item[7:] for item in s] # ['businessname@gmail.com'] Or s = business.css('a.email-business::attr(href)').extract() item['email'] = [item.replace('mailto:', '') for item in s] # ['businessname@gmail.com']
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49209595

http://stackoverflow.com/comment/85370751
has text: @user177324 Well, you can "avoid using a for loop", yes: `np.array(list(map(np.random.normal, mu, sigma, [100] * len(mu))))`. But if you want to know how to avoid calling the function more than once, I think it may not be possible.
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49182508

http://stackoverflow.com/comment/85545842
has text: I'm very sorry,site URL will not be able to access to the members outside of my organization
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49265525
score: 0

http://stackoverflow.com/comment/85522156
type: QuestionComment
comment on: http://stackoverflow.com/q/49259169
has text: Yes, in that case, checking if the last element is empty before removing it is what I would do, too.
score: 1
type: Comment

http://stackoverflow.com/q/49186510
has body: I had to export a table(3.8GB) from BigQuery into GCP, which separated my table into 100 smaller json files, 100mb each. Now I want to be able to put them back into one json file. Is there any efficient way to do that? It could be in R, Python, Java. Or if anybody knows a better way to deal with these files, I appreciate your help.
has answer: http://stackoverflow.com/a/49190076
type: Question
upvote count: 2
has title: Combining 100 json files from BigQuery that have the same structure
has answer: http://stackoverflow.com/a/49186963
has answer: http://stackoverflow.com/a/49193136
tagged with: python
possible better answer: http://stackoverflow.com/a/49193136
favorite count: 0
accepted answer: http://stackoverflow.com/a/49190076
tagged with: http://stackoverflow.com/tag/r
score: 2
type: AnsweredQuestion
downvote count: 0
answer count: 3
tagged with: java
tagged with: http://stackoverflow.com/tag/json
tagged with: google-bigquery

http://stackoverflow.com/a/49214023
score: 0
has body: you can get nan values out by: df = df.loc[df['Values'].isnull()] This will get all of the rows where "Values" is nan
answers question: http://stackoverflow.com/q/49213751
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49213751

http://stackoverflow.com/comment/85326311
type: Comment
has text: I put '$' to indicate the ending of the command prompt - this is what you should see in your terminal as the last character after the name of the directory you are in. When you see people posting a code with '$' just copy only what comes after. Also now I've noticed that your file is named 'learntris.py', not 'tetris.py' (my mistake), run my command with the proper file name and without '$'. Check also [here](https://www.computerhope.com/unix/uchmod.htm) for the syntax of the chmod command.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49159808

http://stackoverflow.com/comment/85455345
type: Comment
comment on: http://stackoverflow.com/a/49225764
score: 0
type: AnswerComment
has text: @Sean When someone suggests something like `collections.Counter`, that means `Counter` isn't a builtin, it's in a module called `collections`. Read the tutorial on imports, but the quick answer here is `from collections import Counter`.

http://stackoverflow.com/q/49247325
has title: Why does this python always result True?
accepted answer: http://stackoverflow.com/a/49247402
type: Question
has answer: http://stackoverflow.com/a/49247357
type: AnsweredQuestion
answer count: 3
downvote count: 3
has answer: http://stackoverflow.com/a/49247441
has body: no matter what numbers I put in for x or y even if I change the values of 16 or 250 x = anyRandomNumber y = anyRandomNumber print ((x + y == 16) == ((10*x) + (25*y) == 250)) This was code provided by an instructor in a lesson and it's only suppose to execute true when x = 10 and y = 6
favorite count: 0
has comment: http://stackoverflow.com/comment/85498394
has comment: http://stackoverflow.com/comment/85498380
upvote count: 0
has answer: http://stackoverflow.com/a/49247402
has comment: http://stackoverflow.com/comment/85498384
tagged with: python
score: -3
has comment: http://stackoverflow.com/comment/85498390
possible better answer: http://stackoverflow.com/a/49247357

http://stackoverflow.com/comment/111001223
has text: @GonzaloGarcia, If your data is clean, probably the list comprehension. It's recommended you test with your data.
type: AnswerComment
comment on: http://stackoverflow.com/a/49149806
score: 1
type: Comment

http://stackoverflow.com/comment/85485789
comment on: http://stackoverflow.com/q/49241035
type: Comment
has text: Do not name lists `list` in python. It overrides the builtin `list`
type: QuestionComment
score: 9

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/49259305
tag name: countvectorizer
tags question: http://stackoverflow.com/q/49152607

http://stackoverflow.com/comment/85380429
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49186317
type: AnswerComment
has text: Thats a confusing one, it works for me in an iPython Notebook... https://snag.gy/BD9lZO.jpg

http://stackoverflow.com/comment/85950323
type: AnswerComment
comment on: http://stackoverflow.com/a/49423913
score: 0
type: Comment
has text: I do not have facebook, so I can't help you anymore. Sorry.

http://stackoverflow.com/a/49187887
type: Answer
has comment: http://stackoverflow.com/comment/85381199
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49187768
has body: A picture like this can be plotted with: from __future__ import division import matplotlib.pyplot as plt from random import randint data = [ ("1 line", [randint(0, 10) / 10 for i in range(20)]), ("2 line", [randint(0, 10) / 10 for i in range(20)]), ("3 line", [randint(0, 10) / 10 for i in range(20)]), ("4 line", [randint(0, 10) / 10 for i in range(20)]) ] for label, y in data: plt.plot(y, label = label) plt.legend() plt.show()

http://stackoverflow.com/q/49134331
answer count: 2
tagged with: visual-studio-code
type: UnansweredQuestion
has body: So, via the anaconda prompt I created an environment and then installed numpy conda -n CT_Bioinformatics python=3.6 conda install numpy And it is installed Then on VSCode (where python interpreter is installed) I changed the interpreter to the one in the Enviroment's folder and it displayed the correct version on the bottom left. When I try to run a file from the terminal it says numpy is not installed and after I created a new file: import sys print (sys.version) The following appeared: 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] Only when I run a file by right clicking and selecting to Run Python File it actually works and displays the right version. PS C:\CT Bioinformatics Coursework&gt; &amp; C:/Anaconda/envs/CT_Bioinformatics/python.exe "c:\CT Bioinformatics Coursework\dp_template.py" I read that you can put in the settings: "python.pythonPath": "C:\\Anaconda\\envs\\CT_Bioinformatics\\python.exe" But it is still the same. Is there anything I am missing so that I can just do python filename on the terminal(so it uses the correct version)? Thanks
downvote count: 0
has answer: http://stackoverflow.com/a/52390014
has title: Why does VSCode doesnt change virtual environment from terminal?
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/91589124
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49134812

http://stackoverflow.com/q/49201693
possible better answer: http://stackoverflow.com/a/49201792
tagged with: python
tagged with: replace
linked to: http://stackoverflow.com/q/1952464
type: AnsweredQuestion
score: 0
tagged with: list
linked to: http://stackoverflow.com/q/2582138
has answer: http://stackoverflow.com/a/61866803
has comment: http://stackoverflow.com/comment/85408633
has answer: http://stackoverflow.com/a/49201752
accepted answer: http://stackoverflow.com/a/49201752
has answer: http://stackoverflow.com/a/49201792
has body: Similar to this question: finding and replacing elements in a list (python) but with a multi-dimensional array. For example, I want to replace all the N's with 0's: list = [['N', 0.21], [-1, 6.6], ['N', 34.68]] I want to change it to: list = [[0, 0.21], [-1, 6.6], [0, 34.68]]
type: Question
has title: finding and replacing elements in a multidimensional list (python)
has answer: http://stackoverflow.com/a/72069888
tagged with: multidimensional-array
tagged with: find
has answer: http://stackoverflow.com/a/49201965
answer count: 5

http://stackoverflow.com/comment/85291038
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49142688
has text: The block of code presented is perfectly valid Python 2.x code, at least syntactically.
score: 1

http://stackoverflow.com/comment/85534224
type: AnswerComment
comment on: http://stackoverflow.com/a/49241875
has text: Thanks @scnerd ! it does exactly what I need if in the end I call a final.groupby().sum . I'll mark this as right answer but I actually have memory issues: the dataset is pretty big and 800gb of ram are not enough. I'll try spark dataframes even though I have never used it.
type: Comment
score: 0

http://stackoverflow.com/q/49139939
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85285545
has answer: http://stackoverflow.com/a/49140411
tagged with: recursion
has title: How to recursively increment a binary number (in list form) without converting to integer?
tagged with: list
has comment: http://stackoverflow.com/comment/85285341
has answer: http://stackoverflow.com/a/49140149
has comment: http://stackoverflow.com/comment/85285527
downvote count: 0
has answer: http://stackoverflow.com/a/49140145
has body: For instance, given list [1, 0, 1] the code would return [1,1,0]. Other examples: [1,1,1] -- &gt; [1,0,0,0] [1,0,0,1] --&gt; [1,0,1,0] I'm having most trouble understanding what my base case for recursion would be and then how to implement for the (n-1) case. def increment_helper(number): newNum = [] if len(number) ==1: if number[0] == 1: carry = 1 newNum.append(0) else: carry = 0 newNum.append(1) else: return increment_helper(number-1) return newNum So I'm sure that there are a lot of errors in here specifically how I am calling my recursion because I am not sure how to recurse on the list while storing the number that is removed somehow. The else return statement is obviously incorrect but I am using that as a placeholder. I am unsure of what condition to use as my base case for incrementation. I think I should be using a carry variable that keeps track of whether I am carrying a one over but other than that I am stuck on how to proceed.
has answer: http://stackoverflow.com/a/49140136
score: 7
upvote count: 7
answer count: 10
favorite count: 0
has comment: http://stackoverflow.com/comment/85285377
tagged with: binary
has answer: http://stackoverflow.com/a/49214974
has answer: http://stackoverflow.com/a/57735067
has answer: http://stackoverflow.com/a/59518914
has comment: http://stackoverflow.com/comment/85285315
has comment: http://stackoverflow.com/comment/85285217
type: Question
has answer: http://stackoverflow.com/a/49140266
has answer: http://stackoverflow.com/a/49140689
has comment: http://stackoverflow.com/comment/85285270
has answer: http://stackoverflow.com/a/49140181
has comment: http://stackoverflow.com/comment/85285208
tagged with: increment
tagged with: python
linked to: http://stackoverflow.com/q/33288846

http://stackoverflow.com/q/49276562
tagged with: python
has comment: http://stackoverflow.com/comment/85556207
has answer: http://stackoverflow.com/a/49277216
has comment: http://stackoverflow.com/comment/85555790
has body: I have a model with two integer fields which are supposed to be foreign keys. In my admin view, those two fields are editable but I would like to display a search icon next to the field, so I can retrieve the id of another model and append to the field. Does django have this feature? class Linkage(models.Model): user_id = models.IntegerField(default=1) parent_id = models.IntegerField(default=0)
has title: Django admin edit integer field
score: 1
has comment: http://stackoverflow.com/comment/86654227
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
answer count: 1
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/85556270

http://stackoverflow.com/comment/85377098
comment on: http://stackoverflow.com/q/49185754
score: 0
has text: What is the purpose of `content.close`?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85441350
comment on: http://stackoverflow.com/q/49218782
type: QuestionComment
has text: Extra forward slashes are used to escape the originals, because the originals would otherwise cause the character(s) following to be interpreted as escape codes themselves. On this occasion python recognises that \u is not a valid escape code so inserts the extra backslashes, because those are the rules.
type: Comment
score: 2

http://stackoverflow.com/q/49260433
has answer: http://stackoverflow.com/a/49260741
favorite count: 0
tagged with: processing
has comment: http://stackoverflow.com/comment/85524295
type: Question
has answer: http://stackoverflow.com/a/49260745
tagged with: arguments
tagged with: python
accepted answer: http://stackoverflow.com/a/49261539
has comment: http://stackoverflow.com/comment/85524716
has answer: http://stackoverflow.com/a/49261539
has title: How to write a Python function that takes in a "Mode" as an argument?
score: 2
upvote count: 2
type: AnsweredQuestion
has body: I am currently writing a color palette generator in Python. I would like to be able to input a Mode as an argument that will produce a specific type of color scheme. Like COMPLEMENTARY or PASTEL etc. I have seen functions like colorMode(HSB) vs. colorMode(RGB) where one of the arguments is a "Mode". I have seen this many times before, they usually are all caps and the IDE usually color codes them in some way. How are these Modes usually stored within the function? Are they color coded because they are some kind of class? Or are they stored as a string or number? Sorry if a question like this already exists, I just have no idea what type of jargon to use to describe this scenario.
answer count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/49260741
has comment: http://stackoverflow.com/comment/85524901

http://stackoverflow.com/q/49172820
favorite count: 0
type: Question
has title: Automatic Download from webpage python
has comment: http://stackoverflow.com/comment/85350573
type: UnansweredQuestion
score: -2
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49173037
has comment: http://stackoverflow.com/comment/85353037
downvote count: 3
answer count: 1
has body: I am trying to download the data from this page https://www.nordpoolgroup.com/Market-data1/Power-system-data/Production1/Wind-Power-Prognosis/DK/Hourly/?view=table As you can see there is a button that can automatically export the data to Excel on the right. I want to create something that is able to automatically export the data present on this to Excel everyday - kind of like a scraper, but I am not able to figure it out. So far this is my code import urllib2 nord='https://www.nordpoolgroup.com/Market-data1/Power-system- data/Production1/Wind-Power-Prognosis/DK/Hourly/?view=table' page=urllib2.urlopen(nord) from bs4 import BeautifulSoup as bs soup=bs(page) pretty=soup.prettify() all_links=soup.find_all("a") for link in all_links: print link.get("href") all_tables=soup.find_all('tables') right_table=soup.find('table', class_='ng-scope') And this is where I am stuck, because it seems that the table class is not defined.
tagged with: web-scraping

http://stackoverflow.com/comment/85480752
has text: [Page Source](view-source:https://www.realtor.com/realestateandhomes-search/48198) It's not confidential - here is the page source. It looks nicer to just point you here than to copy and paste. Properties start at line 2301.
type: AnswerComment
comment on: http://stackoverflow.com/a/49238117
score: 0
type: Comment

http://stackoverflow.com/a/49162639
has comment: http://stackoverflow.com/comment/85333265
has comment: http://stackoverflow.com/comment/85333303
has comment: http://stackoverflow.com/comment/85355196
type: Answer
has body: This is one explicit solution using .loc accessor. import pandas as pd df = pd.DataFrame(np.random.randint(0,100,size=(11, 4)), columns=list('ABCD')) n = len(df.index) df['ticker'] = 'na' df.loc[df.index &lt;= n/4, 'ticker'] = '$' df.loc[(n/4 &lt; df.index) &amp; (df.index &lt;= n/2), 'ticker'] = '$$' df.loc[(n/2 &lt; df.index) &amp; (df.index &lt;= n*3/4), 'ticker'] = '$$$' df.loc[df.index &gt; n*3/4, 'ticker'] = '$$$$' # A B C D ticker # 0 47 64 7 46 $ # 1 53 55 75 3 $ # 2 93 95 28 47 $ # 3 35 88 16 7 $$ # 4 99 66 88 84 $$ # 5 75 2 72 90 $$ # 6 6 53 36 92 $$$ # 7 83 58 54 67 $$$ # 8 49 83 46 54 $$$ # 9 69 9 96 73 $$$$ # 10 84 42 11 83 $$$$
score: 0
has comment: http://stackoverflow.com/comment/85355163
answers question: http://stackoverflow.com/q/49162195

http://stackoverflow.com/q/49170173
downvote count: 0
tagged with: syntax
has answer: http://stackoverflow.com/a/49170294
possible better answer: http://stackoverflow.com/a/49170294
tagged with: mixins
has answer: http://stackoverflow.com/a/49170293
accepted answer: http://stackoverflow.com/a/49170293
has title: How is this execute function referenced in this code?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85345689
has comment: http://stackoverflow.com/comment/85345523
has body: I am a Java programmer that is new to Python. I am having trouble understanding the syntax of the following code from the pymodbus repo in GitHub. Where is the function defined? self.execute(request) The reason I am confused is that AFAIK self refers to variables and functions of the current class, even inherited ones. There is no function defined in the ModBusClientMixIn class, nor the class inherit from any other class. So where is it coming from? There is an execute function defined in the ReadCoilsRequest class, but to invoke that why would you need self? Also, where is context(a variable in the execute function argument list) coming from? Would really appreciate if someone can help me understand the syntax.
tagged with: python
linked to: http://stackoverflow.com/q/2709821
tagged with: design-patterns
linked to: http://stackoverflow.com/q/1984104
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/a/49229665
type: AcceptedAnswer
has body: Select all list items in element with classnames sub-module and performers then parse player details from each list items. e.g. r = requests.get("http://www.espncricinfo.com/series/_/id/8038/season/2018/icc-world-cup-qualifiers/" ) soup = BeautifulSoup(r.text, "html.parser") toprunners = soup.select(".sub-module.performers li") def player(li): name_and_details = li.select_one('p') name = name_and_details.a details = name.nextSibling stats = li.select_one('.overall-stats p') img = li.select_one('.focus-image') return { 'player_name': name.text, 'player_details': details.strip(', '), 'player_image': img.attrs['src'], 'runs': name_and_details.nextSibling.text, 'innings': stats.span.text, 'average': stats.nextSibling.span.text, } players = [player(li) for li in toprunners] In[2]: print(players) [{'player_name': 'TP Ura', 'player_details': 'PNG, Right-hand bat', 'player_image': 'http://a.espncdn.com/combiner/i?img=/i/headshots/cricket/players/default-player-logo-500.png&amp;h=55&amp;w=40&amp;scale=crop&amp;transparent=true', 'runs': '188', 'innings': '2', 'average': '94.00'}, {'player_name': 'Mohammad Nabi', 'player_details': 'AFG, Right-hand bat', 'player_image': 'http://a.espncdn.com/combiner/i?img=/i/headshots/cricket/players/25913.png&amp;h=55&amp;w=40&amp;scale=crop&amp;transparent=true', 'runs': '181', 'innings': '3', 'average': '60.33'}, {'player_name': 'SO Hetmyer', 'player_details': 'WI, Left-hand bat', 'player_image': 'http://a.espncdn.com/combiner/i?img=/i/headshots/cricket/players/default-player-logo-500.png&amp;h=55&amp;w=40&amp;scale=crop&amp;transparent=true', 'runs': '171', 'innings': '3', 'average': '57.00'}, {'player_name': 'Ehsan Khan', 'player_details': 'HKG, Right-arm offbreak', 'player_image': 'http://a.espncdn.com/combiner/i?img=/i/headshots/cricket/players/default-player-logo-500.png&amp;h=55&amp;w=40&amp;scale=crop&amp;transparent=true', 'runs': '9', 'innings': '3', 'average': '12.55'}, {'player_name': 'Mujeeb Ur Rahman', 'player_details': 'AFG, …
has comment: http://stackoverflow.com/comment/85467163
answers question: http://stackoverflow.com/q/49229096
upvote count: 1
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85463146
has comment: http://stackoverflow.com/comment/85464512
accepted answer of: http://stackoverflow.com/q/49229096
has comment: http://stackoverflow.com/comment/85464348
downvote count: 0

http://stackoverflow.com/comment/85567848
comment on: http://stackoverflow.com/a/49242446
type: Comment
has text: I was able to get it working in a stock Windows 8 VM from modern.ie using IE 11.0.9600.18861 with Selenium 3.8.0 and IEDriverServer.exe 3.8.0. (Had to make some adjustments, as the order of `window_handles` was different than I expected.)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85465814
type: Comment
type: QuestionComment
has text: You can use uwsgi with nginx and its location feature to redirect requests to different upstreams listening in different sockets http://uwsgi-docs.readthedocs.io/en/latest/Nginx.html
comment on: http://stackoverflow.com/q/49231130
score: 0

http://stackoverflow.com/comment/85520483
score: 0
type: QuestionComment
has text: @ Aaron, how do I take the browser into account when calculating the crop area?
type: Comment
comment on: http://stackoverflow.com/q/49258352

http://stackoverflow.com/q/49184761
type: Question
has comment: http://stackoverflow.com/comment/85375414
has body: I've this assignment in Python 3 where I get a list of numbers and using at least a for loop I need to find the min, max, sum, and average of the numbers. But the tricky part is that I can only use the len() function, no while loops, def/return, max/min, just len() and for loops, can do if/else statements tho. So please let's say this is the list. numbers=[1,35,54,99,67,2,9] biggest= numbers[0] smallest=numbers[0] for bigs in range(1,len(numbers)): if numbers[bigs] &gt; biggest: biggest = numbers [bigs] print("The max number is", biggest) for smalls in range(1,len(numbers)): if numbers[smalls] &lt; smallest: smallest = numbers [smalls] print("The min number is", smallest) That's what I have for max and min and it does work, a bit messy but it works, but I've no clue how to do sum and average. How could I do all that using only for loops and len()? Thanks!
has comment: http://stackoverflow.com/comment/85375720
has title: For loop that finds min, max, sum and average from a list
tagged with: python
has comment: http://stackoverflow.com/comment/85375542
has comment: http://stackoverflow.com/comment/85375274
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49184817
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49184817
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85375400
tagged with: python-3.x

http://stackoverflow.com/comment/85451098
score: 0
comment on: http://stackoverflow.com/q/49223809
has text: i have a script which takes data from the csv, i dont know how to proceed
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85487893
has text: @cwallenpoole I updated the question with the full error. Thanks
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49241883
type: Comment

http://stackoverflow.com/comment/85288344
comment on: http://stackoverflow.com/a/49140511
has text: Great! I see what you did with `mask`. Neat. Thank you!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49262429
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: For 2.7, 3.5, the command line you show responds, for me, with cp437 - the IBM PC or DOS encoding. Output to the Windows console is limited to a subset of Basic Multilingual Plane (BMP) Unicode characters. For 3.6, Python's handling of the Windows console was drastically improved to use utf-8 and potentially print any unicode character, depending on font availability. For all current versions, IDLE also reports, for me, cp1252 (Latin 1). Since there is an attempt to get the system encoding, I don't know why the difference. But it hardly makes any difference as it is a dummy or fake value. To me, it is deceptive in that non-latin1 chars cannot be encoded with latin1, whereas all BMP chars can be printed in IDLE. So I have thought about a replacement. When (unicode) strings are written to sys.stdout (usually with print), the string object is pickled to bytes in the user process, sent through a socket (implementation detail subject to change) to the IDLE process, and unpickled back to a string object. The effect is as if the string was encoded and decoded with one of the non-lossy utf codings. UTF-32 might be the closest to what pickling does. The IDLE process calls tkinter text.insert(index, string), which asks tk to insert the string in the widget. But that only works for BMP characters. The net effect is as if the output encoding were ucs-2, though I believe tk uses a truncated utf-8 internally. Similarly, any BMP character you enter in the shell or editor can be sent to the user process stdin after being displayed. Anyway, changing pseudofile.encoding has no effect, which is why it was made read-only by this part of the patch for issue 9290 - self.encoding = encoding + self._encoding = encoding + + @property + def encoding(self): + return self._encoding The initial underscore means that _encoding is a private (not hidden) implementation detail that should be ignored by users.
has comment: http://stackoverflow.com/comment/85621927
answers question: http://stackoverflow.com/q/49254893
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49254893

http://stackoverflow.com/comment/85548390
has text: Thank you! It is true that there is more than one way to skin a cat. Thanks for you input. :)
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49272813

http://stackoverflow.com/q/49222986
has title: how to install packages inside virtualenv
has comment: http://stackoverflow.com/comment/85450676
has body: I have a virtualenv created for a Django project. Inside this project I have app folder with 'views.py'. I have installed beautiful soup and requests inside this virtualenv and they import correctly into the 'views.py'. However, for testing puroposes I have another script created inside the same folder as 'views.py' but when I try to import same modules there I get 'no module named...' error. Virtualenv pip freeze looks like that: beautifulsoup4==4.6.0 certifi==2018.1.18 chardet==3.0.4 Django==2.0.3 idna==2.6 pkg-resources==0.0.0 pytz==2018.3 requests==2.18.4 selenium==3.10.0 urllib3==1.22 Views.py: from django.shortcuts import render import os import webbrowser import requests, bs4 import re from .forms import RoomForm from django.shortcuts import render from django.http import HttpResponseRedirect #~ #-*- coding: utf-8 -*- #~ # Create your views here. def index(request): if request.method == 'POST': print('PPPPPPOOOOOOOOSSSSSSSTTTTTTT') form = RoomForm(request.POST) if form.is_valid(): print('VAAAALLLLLLIIIIIIDDDDDDDD') global form_data form_data = form.cleaned_data return HttpResponseRedirect('results') else: print('GGGGEEEEEETTTTT') form = RoomForm() context = {'form': form} return render(request, 'javascript/index.html', context) def results(request): print(request.method) city = form_data['city'].title() print(city) prices = [] real_prices = [] url = 'https://www.airbnb.pl/s/' + city +'--Hiszpania/homes?refinement_paths%5B%5D=%2Fhomes&amp;query=' + city + '%2C%20Hiszpania&amp;checkout=2018-04-22&amp;children=0&amp;infants=0&amp;adults=2&amp;guests=2&amp;allow_override%5B%5D=&amp;price_max=252&amp;room_types%5B%5D=Entire%20home%2Fapt&amp;min_beds=0&amp;s_tag=Ph6ohhjw' webbrowser.open(url) response = requests.get(url) response_text = response.text airbnb_soup = bs4.BeautifulSoup(response_text) page_selectors = airbnb_soup.select('._1bdke5s') print(len(page_selectors)) last_page_selector = page_selectors[len(page_selectors) - 1]##############-15 last_page_selecto…
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85449575
has comment: http://stackoverflow.com/comment/85449482
tagged with: django
tagged with: python
tagged with: virtualenv
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49223056
has comment: http://stackoverflow.com/comment/85449689
has comment: http://stackoverflow.com/comment/85449486
has comment: http://stackoverflow.com/comment/85452983
answer count: 1
has comment: http://stackoverflow.com/comment/85450563
score: -1
type: Question
has comment: http://stackoverflow.com/comment/85454589
has comment: http://stackoverflow.com/comment/85449623
has comment: http://stackoverflow.com/comment/85452319

http://stackoverflow.com/comment/85511423
type: QuestionComment
comment on: http://stackoverflow.com/q/49252844
score: 0
has text: i agree this is primarily opinion based, personally i prefer putting all methods relating to the GUI into a single class that inherits from a tk widget. as this keeps related code together.
type: Comment

http://stackoverflow.com/comment/85434096
has text: Are you running the scripts in a shell or terminal? If you're running a script in the shell, you'll press control C to cancel the script, and then run the other script.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49214848

http://stackoverflow.com/q/49177869
answer count: 4
type: AnsweredQuestion
downvote count: 0
has body: The question is styled in python 2.7 . I'm using OrderedDict to store some items as follows: d = OrderedDict(zip(['a', 'b', 'c', 'd'], range(4))) (d equals to {'a': 0, 'b': 1, 'c': 2, 'd': 3}) Is there a way iterating dictionary d, starting from specific key? For instance, I'd like to iterate d items starting from key 'b' Many thanks in advance!
favorite count: 0
has comment: http://stackoverflow.com/comment/85361315
has answer: http://stackoverflow.com/a/49178010
has answer: http://stackoverflow.com/a/49178438
has comment: http://stackoverflow.com/comment/85361375
accepted answer: http://stackoverflow.com/a/49178443
has comment: http://stackoverflow.com/comment/85361365
type: Question
has comment: http://stackoverflow.com/comment/85361285
has answer: http://stackoverflow.com/a/49178443
has comment: http://stackoverflow.com/comment/85361243
has title: Iterating ordered dict items starting from specific key
tagged with: python
possible better answer: http://stackoverflow.com/a/49178022
tagged with: dictionary
tagged with: slice
has answer: http://stackoverflow.com/a/49178022
score: 4
upvote count: 4
tagged with: python-2.7

function
tags question: http://stackoverflow.com/q/49213807
tags question: http://stackoverflow.com/q/49263903
tags question: http://stackoverflow.com/q/49180872
tags question: http://stackoverflow.com/q/49168762
tags question: http://stackoverflow.com/q/49263071
type: Tag
tags question: http://stackoverflow.com/q/49159238
tags question: http://stackoverflow.com/q/49216095
tags question: http://stackoverflow.com/q/49256431
tag name: function
tags question: http://stackoverflow.com/q/49246460
tags question: http://stackoverflow.com/q/49173633
tags question: http://stackoverflow.com/q/49209006
tags question: http://stackoverflow.com/q/49155950
tags question: http://stackoverflow.com/q/49248036
tags question: http://stackoverflow.com/q/49155280
tags question: http://stackoverflow.com/q/49258872
tags question: http://stackoverflow.com/q/49241719
tags question: http://stackoverflow.com/q/49240964
tags question: http://stackoverflow.com/q/49215277
tags question: http://stackoverflow.com/q/49227517
tags question: http://stackoverflow.com/q/49241335
tags question: http://stackoverflow.com/q/49270330
tags question: http://stackoverflow.com/q/49157033
tags question: http://stackoverflow.com/q/49229538
tags question: http://stackoverflow.com/q/49237663
tags question: http://stackoverflow.com/q/49135754
tags question: http://stackoverflow.com/q/49258987
tags question: http://stackoverflow.com/q/49154405
tags question: http://stackoverflow.com/q/49250833
tags question: http://stackoverflow.com/q/49130053
tags question: http://stackoverflow.com/q/49123814
tags question: http://stackoverflow.com/q/49156743
tags question: http://stackoverflow.com/q/49205092
tags question: http://stackoverflow.com/q/49171780
tags question: http://stackoverflow.com/q/49154677
tags question: http://stackoverflow.com/q/49202684
tags question: http://stackoverflow.com/q/49155381
tags question: http://stackoverflow.com/q/49184811
tags question: http://stackoverflow.com/q/49225343
tags question: http://stackoverflow.com/q/49205128
tags question: http://stackoverflow.com/q/49227652
tags question: http://stackoverflow.com/q/49148378
tags question: http://stackoverflow.com/q/49202126
tags question: http://stackoverflow.com/q/49187237
tags question: http://stackoverflow.com/q/49241194
tags question: http://stackoverflow.com/q/49175334
tags question: http://stackoverflow.com/q/49209916
tags question: http://stackoverflow.com/q/49273317
tags question: http://stackoverflow.com/q/49179509
tags question: http://stackoverflow.com/q/49240801
tags question: http://stackoverflow.com/q/49219009

http://stackoverflow.com/comment/85278953
type: AnswerComment
has text: I did not downvote you. Thanks for the reply! It works too! :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49133512

http://stackoverflow.com/a/49205849
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49205526
type: Answer
has body: I think you need DatetimeIndex.strftime for hours and days of week and for minutes from timedeltas use Series.dt.floor + Series.dt.total_seconds: a = s.index.strftime('%H') b = s.index.strftime('%a') c = s.dt.floor('T').dt.total_seconds().div(60).astype(int) #alternative #c = s.dt.total_seconds().floordiv(60).astype(int) df = pd.DataFrame({'hour':a,'day':b,'minute':c.values}, columns=['hour','day','minute']) print (df) hour day minute 0 22 Tue 27 1 23 Tue 60 2 00 Wed 60 3 01 Wed 32
downvote count: 0

http://stackoverflow.com/a/49153635
upvote count: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49153502
accepted answer of: http://stackoverflow.com/q/49153502
score: 2
has body: Sorry I can't comment but I think your if statement is gonna run after self.stopTimer returns and gonna change the text back
type: AcceptedAnswer

performance
tags question: http://stackoverflow.com/q/49201735
tags question: http://stackoverflow.com/q/49274174
tags question: http://stackoverflow.com/q/49263362
tags question: http://stackoverflow.com/q/49266939
tags question: http://stackoverflow.com/q/49127258
tags question: http://stackoverflow.com/q/49150120
tags question: http://stackoverflow.com/q/49233188
tags question: http://stackoverflow.com/q/49239437
tags question: http://stackoverflow.com/q/49148383
tags question: http://stackoverflow.com/q/49245538
tags question: http://stackoverflow.com/q/49186684
tag name: performance
tags question: http://stackoverflow.com/q/49164134
tags question: http://stackoverflow.com/q/49190186
tags question: http://stackoverflow.com/q/49225534
type: Tag
tags question: http://stackoverflow.com/q/49259580
tags question: http://stackoverflow.com/q/49176797
tags question: http://stackoverflow.com/q/49157396
tags question: http://stackoverflow.com/q/49219454
tags question: http://stackoverflow.com/q/49147550
tags question: http://stackoverflow.com/q/49147413
tags question: http://stackoverflow.com/q/49275927
tags question: http://stackoverflow.com/q/49176652

http://stackoverflow.com/a/59778075
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49211006
type: Answer
accepted answer of: http://stackoverflow.com/q/49211006
score: 2
upvote count: 2
has body: With HoloViews >= 1.13, you can now use keyword .opts(xticks) and .opts(yticks) for setting continuous (non-categorical) ranges. Example: data = [(i, j, i*j) for i in range(10) for j in range(10)] hv.HeatMap(data).opts(xticks=[0, 3, 6, 9], yticks=[0, 5, 9]) Resulting plot:

http://stackoverflow.com/q/49213512
score: 0
has title: Exceptions are seeing while Monitoring Ethernet interface kernel events using pyroute2 IPDB functionality
answer count: 1
tagged with: netlink
accepted answer: http://stackoverflow.com/a/49214349
has body: I am trying to monitor the kernel network interface(link) up or down events using pyroute2 IPDB functionality. Exceptions are seen while fetching the interface index information from the callback function. But here in the "msg" there is an index field. I coded based on this reference http://docs.pyroute2.org/ipdb.html. Any ideas to solve exception. #!/usr/bin/python import pyroute2 # Create Instance of IPDB ipdb = pyroute2.IPDB() action = 'RTM_NEWLINK' def my_call_back(ipdb, msg, action): index = msg['index'] print msg print index ipdb.register_callback(my_call_back, mode='post') while(True): pass Expection: root@VirtualBox:/home/# python notification.py {'index': 2, 'family': 0, '__align': (), 'header': {'pid': 0, 'length': 1276, 'flags': 0, 'error': None, 'type': 16, 'sequence_number': 0}, 'flags': 4098, 'ifi_type': 1, 'event': 'RTM_NEWLINK', 'change': 1, 'attrs': [('IFLA_IFNAME', 'eth0'), ('IFLA_TXQLEN', 1000), ('IFLA_OPERSTATE', 'DOWN'), ('IFLA_LINKMODE', 0), ('IFLA_MTU', 1500), ('IFLA_GROUP', 0), ('IFLA_PROMISCUITY', 0), ('IFLA_NUM_TX_QUEUES', 1), ('IFLA_GSO_MAX_SEGS', 65535), ('IFLA_GSO_MAX_SIZE', 65536), ('IFLA_NUM_RX_QUEUES', 1), ('IFLA_CARRIER', 0), ('IFLA_QDISC', 'pfifo_fast'), ('IFLA_CARRIER_CHANGES', 21), ('IFLA_PROTO_DOWN', 0), ('IFLA_MAP', {'dma': 0, 'base_addr': 0, 'irq': 0, 'mem_end': 0, 'port': 0, 'mem_start': 0}), ('IFLA_ADDRESS', '08:00:27:5f:7d:3e'), ('IFLA_BROADCAST', 'ff:ff:ff:ff:ff:ff')) 2 Exception in thread IPDB callback 140583224088768: Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner self.run() File "/usr/lib/python2.7/threading.py", line 754, in run self.__target(*self.__args, **self.__kwargs) File "/usr/local/lib/python2.7/dist-packages/pyroute2/ipdb/main.py", line 968, in safe callback(*argv, **kwarg) File "notification.py", line 11, in my_call_back index = msg['index'] KeyError: 'index' Exception in thread IPDB callback 140583224088768: Traceback (most recent call last): File "/u…
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49214349
type: AnsweredQuestion

http://stackoverflow.com/comment/93524758
type: Comment
has text: cur.execute() returns `None` http://initd.org/psycopg/docs/cursor.html#cursor.execute under normal circumstances (or throws an exception if there is a problem). You are assigning the value `None` to the variable `result` and then when you run the line `if result > 0` you are trying to check if `None` is less than 0. The `NoneType() > int()` error message is telling you that `None` is unorderable. It can't order `None` as less ( or equal or greater) than 0. @piro has the answer below for you, mark that correct.
score: 0
comment on: http://stackoverflow.com/q/49254588
type: QuestionComment

http://stackoverflow.com/comment/85550645
has text: You can't append two items at once. And its not in fixed width format
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49272585
type: Comment

http://stackoverflow.com/comment/99672278
comment on: http://stackoverflow.com/a/49244224
score: 0
has text: My pleasure, @SamCreamer!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85286888
type: AnswerComment
score: 0
has text: It's not really advisable to ask for different things in the same question especially not after it has been answered. You will find solutions to placing the colorbar [in this question](https://stackoverflow.com/questions/13784201/matplotlib-2-subplots-1-colorbar) - and I would recommend to you the last option from my own answer to it, using `InsetPosition`. If you have problems implementing it, ask a new question clearly stating the problem.
comment on: http://stackoverflow.com/a/49139150
type: Comment

http://stackoverflow.com/a/49177675
downvote count: 0
answers question: http://stackoverflow.com/q/49177214
has comment: http://stackoverflow.com/comment/85361378
has comment: http://stackoverflow.com/comment/85361116
has comment: http://stackoverflow.com/comment/85360901
type: Answer
score: 4
has body: When creating venvs (python -m venv, not virtualenv), I've had success by including the version number in the call to create; python3.6 -m venv myvenv
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49177214
type: AcceptedAnswer

http://stackoverflow.com/a/49226310
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49226200
type: Answer
answers question: http://stackoverflow.com/q/49226200
has body: Correct approach would be this: d.get('persons')[0].get('name') get() applied on dictionary returns value of given key, if possible. Then we access list inside it and try to get() value of key called name again. This can raise IndexError or KeyError exceptions if there's no list or no persons or name key, but you can handle this with try .. except block as outlined in iBug's answer.
downvote count: 0

http://stackoverflow.com/comment/85286218
has text: I edited the question, if you have time could you edit your answer accordingly? That would be great
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49139150
type: Comment

photologue
tag name: photologue
tags question: http://stackoverflow.com/q/49177889
type: Tag

http://stackoverflow.com/comment/85402658
has text: @LeonardoFerreira if the file is very large, it is likely that your machine is running out of memory to load the file from desk to RAM. You cannot load a 8GB CSV to a Pandas dataframe if your computer doesn'thave 8GB ram free. Consider using a large VM or Spark cluster in Azure or AWS to process your data. Also, please mark the question as solved as this answer addresses your original problem.
comment on: http://stackoverflow.com/a/49185740
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85276944
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49135716
has text: Thank you very much! sorry if I was confusing, I will read the link you posted earlier for next time! (https://stackoverflow.com/help/mcve)
type: Comment

http://stackoverflow.com/a/49211064
has comment: http://stackoverflow.com/comment/85427885
has comment: http://stackoverflow.com/comment/85427801
has comment: http://stackoverflow.com/comment/85429054
has comment: http://stackoverflow.com/comment/85428356
has comment: http://stackoverflow.com/comment/85427630
answers question: http://stackoverflow.com/q/49203268
has comment: http://stackoverflow.com/comment/85428178
has comment: http://stackoverflow.com/comment/85427143
has body: The execute_cb parameter of the constructor of SimpleActionServer defines a callback function taking a goal parameter. The documentation of the callback is not very good but a look into source code will show the passed parameter. To notify a client about success, you need to set the service as succeeded. A result is allowed to pass as optional parameter in this case. Adding parameter and notify about success in your callback implementation should do the trick: def execute_cb(self, goal): rospy.loginfo("starting callback") self.__as.set_succeeded()
has comment: http://stackoverflow.com/comment/85427556
type: Answer
has comment: http://stackoverflow.com/comment/85440608
score: 0

http://stackoverflow.com/comment/94877077
type: AnswerComment
has text: Hah, thanks, I did the same thing. Your post saved me a lot of work :)
score: 1
comment on: http://stackoverflow.com/a/49134182
type: Comment

http://stackoverflow.com/comment/85609847
score: 0
has text: Or follow this guide using Audacity: https://manual.audacityteam.org/man/tutorial_vocal_removal_and_isolation.html
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49279425

http://stackoverflow.com/comment/85358013
score: 0
has text: Great! Just to be clear, I do not know what specific address I am looking for. I am looking for any duplicates that might exist. So I dont have that match = "e-mail address" that is specified in the beginning of the script. Will this work anayway? Again, tank you for taking your time!
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49175797

http://stackoverflow.com/q/49230486
has comment: http://stackoverflow.com/comment/85464367
type: AnsweredQuestion
score: 0
has title: What is happening when I run `python manage.py test` and on which port the django test server is listening?
answer count: 1
tagged with: django
has body: I wrote a test for for a signup feature. When I do manually, the signup process sends email to the user, but when I do it with test script the email is not sent. So I was wondering what is happening inside? And what is the port for the test server? Is there any relation for the test server to send mail with it? Can I specify the test server port?
type: Question
accepted answer: http://stackoverflow.com/a/49231798
tagged with: python
has answer: http://stackoverflow.com/a/49231798

http://stackoverflow.com/comment/85521945
comment on: http://stackoverflow.com/a/49257142
score: 0
has text: Thanks, After renaming I just need to remove the 2nd index column, so that I can transform to 3d data using `panel`
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49244814
answers question: http://stackoverflow.com/q/49244613
score: 2
has body: Changing u"C:\\'Program Files (x86)'\\SAP\\FrontEnd\\SAPgui\\saplogon.exe" to r'C:\\Program Files (x86)\\SAP\\FrontEnd\\SAPgui\\saplogon.exe' resolved the issue
type: Answer
accepted answer of: http://stackoverflow.com/q/49244613
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49160408
upvote count: 1
downvote count: 1
score: 0
has comment: http://stackoverflow.com/comment/85327304
type: Answer
answers question: http://stackoverflow.com/q/49160142
has comment: http://stackoverflow.com/comment/85327006
has body: _cntr is not part of matplotlib any more. I has not been used for several versions already, and I guess it now has been removed completely. You may of course copy a version of it from a previous release (compiled for the same system) to your matplotlib folder to continue importing it as matplotlib._cntr.
has comment: http://stackoverflow.com/comment/85411177

http://stackoverflow.com/a/50252271
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49202007
answers question: http://stackoverflow.com/q/49202007
type: Answer
has comment: http://stackoverflow.com/comment/87550064
has body: Have you tried to add convolutional layers as the first layers of your model? I am using right now this approach in order to classify EMG signals into 53 classes. The convolutional layers are supposed to automatically learn the features from the data, and them feed the LSTM layers with them. There are several possible architectures, DeepConvLstm is one of them: DeepConvLstmArch DeepConvLstm paper: Deep Convolutional and LSTM Recurrent Neural Networks for Multimodal Wearable Activity Recognition
score: 2

http://stackoverflow.com/comment/85538335
has text: It's one of the most widely used python packages, and should work for any recent python, including 3.3, it's probably just that you don't have it installed. Try `pip install numpy` from your command prompt (not in your `python` interperter), assuming you have pip installed. Here's a [link](https://docs.scipy.org/doc/numpy/user/install.html) to get your installation running
comment on: http://stackoverflow.com/a/49267449
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/85539024
type: Comment
comment on: http://stackoverflow.com/q/49267706
score: 2
type: QuestionComment
has text: Also, instead of placing a new label over the old one, you probably want to remember the existing labels, and re-`config` the appropriate one with the new image. If you don't want to do that, you should at least destroy the old labels instead of just hiding them. Otherwise, you end up with an extra 297 widgets that Tkinter has to keep track of that the user isn't seeing or interacting with.

http://stackoverflow.com/comment/85327006
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49160408
has text: Copying complied modules between installations is not a good idea.
score: 0

http://stackoverflow.com/comment/85288626
score: 1
has text: Not so bad considering it is not numpy. I fixed the benchmark and this roughly halves the time your solution takes.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49139872

http://stackoverflow.com/comment/85312643
type: QuestionComment
comment on: http://stackoverflow.com/q/49154068
has text: Would you mind posting a few simplified rows of the csv or dataframe?
score: 1
type: Comment

http://stackoverflow.com/comment/85452509
comment on: http://stackoverflow.com/a/49220828
has text: @MartijnPieters Yes, I know. But in some rare cases I like and prefer the readability of explicitly named iteration rounds. This looked to me like one of those cases.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85386119
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49190539
has text: Please consider revising the code sample you posted in this question. As it currently stands, its formatting and scope make it hard for us to help you; here is a [great resource](http://stackoverflow.com/help/mcve) to get you started on that. -1, don't take it the wrong way. A down vote is how we indicate a content problem around here; improve your formatting and code sample and I (or someone will) gladly revert it. Good luck with your code!

http://stackoverflow.com/comment/85405890
has text: as @Crawley said, it is better not to use list as a variable but it still works.
comment on: http://stackoverflow.com/a/49200389
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/135353582
score: 0
type: Comment
type: QuestionComment
has text: I got this error on tornado 6.1: module 'tornado.web' has no attribute 'asynchronous'
comment on: http://stackoverflow.com/q/49199638

http://stackoverflow.com/comment/85413834
score: 1
has text: Added an answer.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49204007

http://stackoverflow.com/comment/86712636
has text: Since I changed the distribution as of my answer above, it has not been reproduced. So, my distribution parameters were wrong. Thank you.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49837762

http://stackoverflow.com/comment/85430281
type: Comment
type: QuestionComment
score: 4
comment on: http://stackoverflow.com/q/49212926
has text: Frankly, I'd argue that having all objects be *immutable* is the better model, if you care about encouraging development of reliable software (explicit state management, &c) -- you don't need to worry about locking to control which thread can make changes to an object if your objects can't change. Take a look at how Clojure does it (outside the interop and single-threaded-performance-sensitive corner cases).

http://stackoverflow.com/q/49214137
has title: Python code to retrieve Apple Warranty information using serial Numbers
tagged with: python
has body: I am an IT admin and would like to find the warranty information of my apple devices easily. I found this Python code online and it is not working. https://github.com/pudquick/pyMacWarranty I have 100's of apple devices and I hope someone can help me write/fix python code to retrieve warranty information for all the devices quickly.
answer count: 2
possible better answer: http://stackoverflow.com/a/49214240
has answer: http://stackoverflow.com/a/49214240
type: Question
accepted answer: http://stackoverflow.com/a/49214164
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49214164

http://stackoverflow.com/comment/85274713
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49134498
type: AnswerComment
has text: can you please explain the code? that would be much appreciated.

http://stackoverflow.com/comment/85564692
comment on: http://stackoverflow.com/q/49263997
type: QuestionComment
has text: Thank you! I cannot believe I missed that, it should've been obvious.
score: 0
type: Comment

http://stackoverflow.com/q/49200873
tagged with: python
possible better answer: http://stackoverflow.com/a/49201201
answer count: 2
has answer: http://stackoverflow.com/a/49201201
score: 1
downvote count: 0
upvote count: 1
has title: How to concatenate a Series of lists of str with a Series of str
favorite count: 0
type: Question
has body: Starting with a Series of lists of strings and a Series of strings, create a Series of lists where each element of each list is concatenated with the corresponding element of the second Series. For example, series1 = pd.Series([['a','b','c'],['d','e']]) series2 = pd.Series(['1','2']) so that series3 looks like: 0 [a1, b1, c1] 1 [d2, e2]
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49200908
tagged with: pandas
has answer: http://stackoverflow.com/a/49200908

sparse-matrix
tags question: http://stackoverflow.com/q/49254111
tag name: sparse-matrix
tags question: http://stackoverflow.com/q/49189637
type: Tag
tags question: http://stackoverflow.com/q/49264076
tags question: http://stackoverflow.com/q/49201063
tags question: http://stackoverflow.com/q/49223219

http://stackoverflow.com/q/49158367
upvote count: 1
has comment: http://stackoverflow.com/comment/85322591
answer count: 1
has title: Python3. Add few values to existing key
has comment: http://stackoverflow.com/comment/85321658
favorite count: 0
has answer: http://stackoverflow.com/a/49158790
type: Question
accepted answer: http://stackoverflow.com/a/49158790
tagged with: python
score: -1
tagged with: dictionary
has body: I know there is a lot of information about this subject, but I'm really stuck with this problem. I have a dictionary loaded from a file: datastore = json.load(f) print(datastore) {"a": "999", "b": "345"} Now, I need to add more values to the existing key. But instead I receive an error: AttributeError: 'str' object has no attribute 'append' Here's what I've tried so far: if key in datastore: temp = [] [temp.extend([k, v]) for k, v in datastore.items()] print(temp) print(type(temp)) i = temp.index(key) print(i) temp[i].append(value) print(temp) and: if key in datastore: datastore.setdefault(key, []) datastore[key].append(value) Result is the same: 'str' object has no attribute 'append' Please help! Full code below: import os import json import argparse import sys if len(sys.argv) &gt; 3: parser = argparse.ArgumentParser() parser.add_argument("--key") parser.add_argument("--val") args = parser.parse_args() key = args.key value = args.val storage = {} storage[key] = value if os.path.exists('storage_file'): with open('storage_file', 'r') as f: datastore = json.load(f) if key in datastore: datastore.setdefault(key, []) datastore[key].append(value) else: datastore.update({key: value}) with open('storage_file', 'w') as f: json.dump(datastore, f) else: with open('storage_file', 'w') as f: json.dump(storage, f) else: parser = argparse.ArgumentParser() parser.add_argument("--key", action="store") args = parser.parse_args() key = args.key with open('storage_file', 'r') as f: datastore = json.load(f) print(datastore.get(key))
type: AnsweredQuestion
downvote count: 2

http://stackoverflow.com/comment/85372514
has text: Who told you that it's easier to search in a list? You can search `my_dict.items()` just as easily as `my_list`, and without the extra line of code, the potential for confusion, the cost of a copy, etc.
comment on: http://stackoverflow.com/q/49181855
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85336450
type: Comment
has text: Ended up using Jinja2 (because using python) to render a template in the lambda function from S3 and returned this from the lambda, thanks so much!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49123293

http://stackoverflow.com/comment/85593603
comment on: http://stackoverflow.com/q/49256507
type: Comment
type: QuestionComment
has text: You should try to find out if this is a problem with the FFT or a problem with PyAudio, and ask your question about just one of them. You could try to save the result of the FFT/IFFT to a file and analyze it with an external program. If that looks fine, you could try to play some "correct" sound with PyAudio, to see if you are using it right.
score: 0

http://stackoverflow.com/q/49268606
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49268705
accepted answer: http://stackoverflow.com/a/49268705
has body: I'm working on a small project where I have a folder that contains about 20 photos. I made a for loop using os.listdir and it prints all the photo names out into the console correctly. The main issue is that I want it to randomly pick one of the photos in the folder and print its name out. Whats happening is that its doing something tottaly else and printing multiple one letter characters to the console. for photos in os.listdir(photoPath): if photos.endswith(".jpg"): choice = random.choice(photos) print(choice) output: J B p _ g O C K j . . _ _ L _ _ D . g _ j E N _ . E F . g F _ _ _ g j K g _ . _ j p . . p
tagged with: python
has answer: http://stackoverflow.com/a/49268656
possible better answer: http://stackoverflow.com/a/49268656
type: AnsweredQuestion
score: 0
type: Question
answer count: 2
has title: random.choice printing out letter by letter

http://stackoverflow.com/comment/85554995
comment on: http://stackoverflow.com/a/49276296
score: 3
type: Comment
type: AnswerComment
has text: Without repeating the key (prone to copy-paste errors): `if x.get('gender') == "Male"`, `get` returning `None` if the key is not present.

http://stackoverflow.com/q/49225553
downvote count: 0
has body: Suppose we have a toy example like below. np.random.seed(seed=1) df = pd.DataFrame(np.random.randint(low=0, high=2, size=(5, 2))) df 0 1 0 1 1 1 0 0 2 1 1 3 1 1 4 1 0 We want to return the indices of all rows like a certain row. Suppose I want the indices of all rows like row 0, which has a 1 in both column 0 and column 1. I would want a data structure that has: (0, 2, 3).
favorite count: 0
tagged with: indexing
has answer: http://stackoverflow.com/a/49225923
type: Question
tagged with: pandas
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49226216
score: 2
upvote count: 2
answer count: 2
has title: Python pandas: Return indices of all rows like another row

http://stackoverflow.com/q/49188515
tagged with: selenium
tagged with: python-requests
has comment: http://stackoverflow.com/comment/85383932
has comment: http://stackoverflow.com/comment/85383845
has comment: http://stackoverflow.com/comment/85383875
has comment: http://stackoverflow.com/comment/85384242
tagged with: python
has comment: http://stackoverflow.com/comment/85384402
has title: How to use requests to replace selenium in Python?
has body: I used Selenium to get the result using the following code. import requests import selenium import time driver.get(r'http://www.example.com') a = driver.find_element_by_xpath("//input[@type='file']") a.send_keys(r'C:\mypic.jpg') time.sleep(5) driver.find_element_by_xpath("//result[@output='data']").click() c = driver.find_element_by_xpath("//category[@id='front']").text How to use requests to get the result? Thank you.
has comment: http://stackoverflow.com/comment/85382681
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85383924

http://stackoverflow.com/q/49141017
tagged with: python
possible better answer: http://stackoverflow.com/a/49158301
tagged with: flask
has answer: http://stackoverflow.com/a/49158301
tagged with: internationalization
score: 2
type: AnsweredQuestion
has body: I am building and international website using Flask framework that can handle two languages (for now): English and French, using Flask-Babel and I have data stored in SQL database using SQLAlchemy as a toolkit. Currently, my models have several duplicated attributes for each language: from project import db class Model(db.Model) [...] name_en = db.Column(db.String) name_fr = db.Column(db.String) description_en = db.Column(db.String) description_fr = db.Column(db.String) And in my .html template I am displaying the value using things like: {% if g.locale == 'fr' %} {{ model.name_fr }} {% else %} {{ model.name_en }} {% endif %} Is there a better way managing this? If I want to add a new language it will be tedious to modify all the templates. Ideally I would like to put in my template something like: {{ model.name[g.locale] }} Is it achievable?
has comment: http://stackoverflow.com/comment/85287520
answer count: 3
upvote count: 2
has title: How to structure database with localization?
downvote count: 0
tagged with: database-design
has answer: http://stackoverflow.com/a/49251044
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85288403
has answer: http://stackoverflow.com/a/49141263
accepted answer: http://stackoverflow.com/a/49251044

http://stackoverflow.com/q/49155168
has answer: http://stackoverflow.com/a/49156646
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49156646
type: AnsweredQuestion
tagged with: terminal
linked to: http://stackoverflow.com/q/49171769
tagged with: stdout
tagged with: python
has body: Ok, so I have this very simple python script: import time import sys for i in range(25): time.sleep(1) print(i) sys.exit() When I use python to run it (/usr/local/bin/python3.6 testscript.py), all works fine and the output reads: 1 2 3 4 etc.. With each number printed 1 second after the other. However when I run: /usr/bin/osascript -e 'do shell script "/usr/local/bin/python3.6 testscript.py" with prompt "Sart Testing " with administrator privileges' There isn't any output for 25 seconds and finally it prints: 24 To the terminal. The question is: How can I make osascript print the exact same output as when I run the Python script directly?
tagged with: applescript
has title: Make osascript print stdout interactively / in real-time
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: osascript

adaboost
tag name: adaboost
tags question: http://stackoverflow.com/q/49196102
type: Tag

http://stackoverflow.com/comment/85268801
comment on: http://stackoverflow.com/a/49131889
type: AnswerComment
has text: df3 = df1.join(df2.reset_index('gene'), on = ['project','sample']) df3.set_index(['project','sample','gene']) -> I reset the index after and it looked just the way I wanted it to
score: 1
type: Comment

http://stackoverflow.com/q/49271613
has answer: http://stackoverflow.com/a/49272409
has comment: http://stackoverflow.com/comment/85546829
has comment: http://stackoverflow.com/comment/85546897
score: 0
has body: I am having these lines in text file. First line is the column name. Data is not in fixed format so I cannot split it with slicing the string with index range. a b c d e f g h i j SEMESTER 24 18 0 74 28 0 74 VISU Burf 13+1/2 9+5/8 0 1,122 320 0 1,122 VISU 1ST 8+3/4 4+1/2 8,192 1,280 3,570 8,192 CBL Burf 13+1/2 9+5/8 36 0 1,235 592 0 1,235 VISU SEMESTER 26 16 Line 0 160 212 0 160 CALC 8+3/4 7 26 0 8,243 734 970 8,243 CBL OPEN WORK 6+1/8 WiseLine 8243 10,239 SEMESTER 19 16 line pipe 0 105 0 0 105 CALC SEMESTER 16 65# 0 100 0 89 CALC 2ND 6+1/8 4+1/2 0 9,257 SEMESTER 20 16 65# 0 89 100 0 89 CALC 2ND 6+1/8 4+1/2 0 9,257 I want to split all the lines and need output like this. ["SEMESTER", "24", "18", "", "0", "74", "28", "0", "74", "SUVI"] ["BURF", "13+1/2", "9+5/8", "", "0", "1122", "320", "0", "1122", "SUVI"] ["1ST", "8+3/4", "4+1/2", "", "", "8192", "1280", "3570", "8192", "BCL"] ["BURF", "13+1/2", "9+5/8", "36", "0", "1235", "592", "0", "1235", "SUVI"] ["SEMESTER", "26", "16", "Line", "0", "160", "212", "0", "160", "CALC"] ["", "8+3/4", "7", "26", "0", "8243", "734", "970", "8243", "BCL"] ["OPEN WORK", "6+1/8", "", "Wiseline", "8243", "10239", "", "", "", ""] ["SEMESTER", "19", "16", "line wise", "0", "105", "0", "0", "105", "CALC"] ["SEMESTER", "", "16", "65#", "0", "", "100", "0", "89", "CALC"] ["2ND", "6+1/8", "4+1/2", "", "0", "9257", "", "", "", ""] ["SEMESTER", "20", "16", "65#", "0", "89", "100", "0", "89", "CALC"] ["2ND", " 6+1/8", "4+1/2", "", "0", "9257", "", "", "", ""] I would appreciate if someone can help me in this problem.
has comment: http://stackoverflow.com/comment/85546918
has comment: http://stackoverflow.com/comment/85547010
tagged with: string
has comment: http://stackoverflow.com/comment/85546659
type: Question
tagged with: python-3.x
tagged with: split
has title: How to split the string into multiple sub-strings with python?
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85546791
tagged with: python

http://stackoverflow.com/q/49181258
tagged with: pybind11
tagged with: python
has title: Pybind11: Create numpy view of data
tagged with: c++
score: 2
type: AnsweredQuestion
has body: I want to create numpy view of the data in a C++ class. But the following makes a copy instead of a view. The python test: import _cpp a = _cpp.A() print(a) a.view()[:] = 100 # should make it all 100. print(a) Result: 40028064 0 0 0 // Fail: Modifying a.mutable_data() in C++ doesn't // change _data[4] 40028064 0 0 0 // Fail: Modifying a.view() in Python 3 doesn't // change data in a The C++ line a.mutable_data()[0] = -100; doesn't change the 0th element to -100. This shows py::array_t&lt;int&gt; a(4, &amp;_data[0]); creates a copy instead of a view of int _data[4]; Modifying the array a.view() doesn't change the data in a to 100s. This shows that a.view() is a copy instead of a view of the data in a. main.cpp: #include &lt;iostream&gt; #include "pybind11/pybind11.h" #include "pybind11/numpy.h" namespace py = pybind11; class A { public: A() {} std::string str() { std::stringstream o; for (int i = 0; i &lt; 4; ++i) o &lt;&lt; _data[i] &lt;&lt; " "; return o.str(); } py::array view() { py::array_t&lt;int&gt; a(4, &amp;_data[0]); a.mutable_data()[0] = -100; return a; } int _data[4]; }; PYBIND11_MODULE(_cpp, m) { py::class_&lt;A&gt;(m, "A") .def(py::init&lt;&gt;()) .def("__str__", &amp;A::str) .def("view", &amp;A::view, py::return_value_policy::automatic_reference); } CMakeLists.txt: cmake_minimum_required(VERSION 3.9) project(test_pybind11) set(CMAKE_CXX_STANDARD 11) # Find packages. set(PYTHON_VERSION 3) find_package( PythonInterp ${PYTHON_VERSION} REQUIRED ) find_package( PythonLibs ${PYTHON_VERSION} REQUIRED ) # Download pybind11 set(pybind11_url https://github.com/pybind/pybind11/archive/stable.zip) set(downloaded_file ${CMAKE_BINARY_DIR}/pybind11-stable.zip) file(DOWNLOAD ${pybind11_url} ${downloaded_file}) execute_process(COMMAND ${CMAKE_COMMAND} -E tar xzf ${downloaded_file} SHOW_PROGRESS) file(REMOVE ${downloaded_file}) set(pybind11_dir ${CMAKE_BINARY_DIR}/pybind11-stable) add_subdirectory(${pybind11_dir}) include_directories(${pybind11_dir}/include) # Make pyth…
accepted answer: http://stackoverflow.com/a/49181769
answer count: 1
has answer: http://stackoverflow.com/a/49181769
favorite count: 0
type: Question
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/85368910
type: QuestionComment
has text: dataframes have a `.shift` method that is quite handy for situations like this and let you avoid writing loops
score: 0
comment on: http://stackoverflow.com/q/49181653
type: Comment

http://stackoverflow.com/comment/85432508
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49213278
has text: New to Python, but you use Python2.7? [You might want to reconsider](https://pythonclock.org/)
type: Comment

http://stackoverflow.com/comment/85548264
has text: I believe only the first point of your list is really relevant, and there is an easy way to avoid it: 1) never use a bare `except`, and never catch `GeneratorExit` inside a generator. The points about threads/killing the process/segfaulting/power off are expected, python can't do magic. Also: exceptions in `finally` are obviously a problem but this does not change the fact that the control flow *was* moved to the `finally` block. Regarding `Ctrl+C`, you can add a signal handler that ignores it, or simply "schedules" a clean shutdown after the current operation is completed.
comment on: http://stackoverflow.com/a/49262664
type: Comment
score: 20
type: AnswerComment

http://stackoverflow.com/q/49198342
favorite count: 0
type: Question
tagged with: pandas
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49198947
accepted answer: http://stackoverflow.com/a/49198947
has title: How can I compare values to each other in two different pandas dataframes
has comment: http://stackoverflow.com/comment/85403743
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85401657
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/49198447
upvote count: 1
has comment: http://stackoverflow.com/comment/85401653
has body: I have two different pandas data frames. One is called 'price' and it has the schema SKU, price The second data frame is called sales_tracking which contains information about the number of sales for a SKU at a given price. It's schema is SKU, price, total_orders, total_visits But when we add a new price point for a SKU in the 'price' data frame, there won't be a matching record in the 'sales_tracking' data frame, at which point I have to add a new entry to the 'sales_tracking' data frame where the total_orders and total_visits is estimated from another data set (we're doing this to estimate conversion rates). The problem I'm having is being able to check to see if the value for price in the pricing data frame also exists in the sales_tracking data frame. Before doing the comparison, I first create temporary data frames for both the pricing data and the sales data as follows: sku_specific_sales_records = sales_tracking[sales_tracking['product']==product] sku_specific_price = sku_specific_price [sku_specific_price ['product']==product] To be clear, both sku_specific_sales_records and sku_specific_price may contain multiple record. I'm trying to identify the case when there is a row in sku_specific_price where sku_specific_price['price'] is not in sku_specific_sales_records['price']. I have tried various different things. Something as simple as if sku_specific_sales_records['price'] == sku_specific_price['price']: doesn't work, I get a ValueError "can only compare identically-labeled Series objects'. So I also tried if sku_specific_price['price'].isin(sku_specific_sales_records['price']): doTheThingIfTheyMatch else: doTheOtherThing And that generates a different ValueError: "The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). So I tried using a.bool() if sku_specific_price['price'].isin(sku_specific_sales_records['price']).bool(): doTheThingIfTheyMatch else: doTheOtherThing but that brought me back full circle to the "ValueEr…
has answer: http://stackoverflow.com/a/49198447

http://stackoverflow.com/comment/85857950
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49413380
has text: I also noticed that you used a generator function instead of a `list comprehension`. This also improved the performance. Great answer!
score: 1

http://stackoverflow.com/q/49216249
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49218472
favorite count: 0
has comment: http://stackoverflow.com/comment/85440643
score: 1
has title: How could I restart my Pong game and keep my score working?
has body: I have been developing a Pong game for my first complete Python project, mostly using tkinter for most of the operations. However, I could not figure out how to restart the programme using the restart button I added without disabling the score counter in the top left corner. The following text is my code: from tkinter import * import random import time import pygame import os, sys import time class Ball: def __init__(self, canvas, paddle, color): self.canvas = canvas self.paddle = paddle self.id = canvas.create_oval(10, 10, 25, 25, fill='red') self.canvas.move(self.id, 245, 100) starts = [-3, -2, -1, 1, 2, 3] random.shuffle(starts) self.x = starts[0] self.y = -3 self.canvas_height = self.canvas.winfo_height() self.canvas_width = self.canvas.winfo_width() self.hit_bottom = False self.score = 0 def hit_paddle(self, pos): paddle_pos = self.canvas.coords(self.paddle.id) if pos[2] &gt;= paddle_pos[0] and pos[0] &lt;= paddle_pos[2]: if pos[3] &gt;= paddle_pos[1] and pos[3] &lt;= paddle_pos[3]: return True return False def draw(self): self.canvas.move(self.id, self.x, self.y) pos = self.canvas.coords(self.id) if pos[1] &lt;= 0: self.y = 3 if pos[3] &gt;= self.canvas_height: self.hit_bottom = True if self.hit_paddle(pos) == True: self.y = -3 if pos[0] &lt;= 0: self.x = 3 if pos[2] &gt;= self.canvas_width: self.x = -3 if self.hit_paddle(pos) == True: self.score += 1 class Paddle: def __init__(self, canvas, color): self.canvas = canvas self.id = canvas.create_rectangle(0, 0, 150, 10, fill='blue') self.canvas.move(self.id, 450, 750) self.x = 0 self.y = 0 self.canvas_width = self.canvas.winfo_width() self.canvas.bind_all('&lt;KeyPress-Left&gt;', self.turn_left) self.canvas.bind_all('&lt;KeyPress-Right&gt;', self.turn_right) self.canvas.bind_all('&lt;KeyRelease-Left&gt;', self.stop_left) self.canvas.bind_all('&lt;KeyRelease-Right&gt;', self.stop_right) self.canvas.bind_all('&lt;KeyPress-Up&gt;', self.turn_up) self.canvas.bind_all('&lt;KeyPress-Down&gt;', self.turn_down) self.can…
tagged with: python
type: Question
tagged with: tkinter
type: UnansweredQuestion
answer count: 1

http://stackoverflow.com/comment/85273479
type: Comment
type: QuestionComment
has text: Have you tried ``?
comment on: http://stackoverflow.com/q/49134141
score: 1

http://stackoverflow.com/a/49532735
has body: We tried the same in virtual box and host machine, we got the following observations: Code executed in Virtual box image of code executed in virtual box Virtual box CPU info Image of Virtual box CPU info Code executed in Host machine Image of code executed in Host machine Host machine CPU info Image of Host machine CPU info For more reference on Recommended settings for calling Intel MKL routines from multi-threaded applications you can refer following link: https://software.intel.com/en-us/articles/recommended-settings-for-calling-intel-mkl-routines-from-multi-threaded-applications
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49157336
score: 2

http://stackoverflow.com/a/49210732
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49201540
has body: Of course you may change the scatter, e.g. to set the size of the points without energy to 0. import matplotlib.pyplot as plt import numpy as np data = np.genfromtxt('data/some_solidstate_physics_data.txt') x=data[:,0]; y=data[:,1]*3.0; z=data[:,2] plt.scatter(x,y,c=z, s=np.log10(z+1), cmap="PuRd", vmin=-500) plt.show() Since the data is already gridded, there is for sure no need to use griddata, this will only smooth out the data. Instead just reshaping the data into a grid is enough. import matplotlib.pyplot as plt import numpy as np data = np.genfromtxt('data/some_solidstate_physics_data.txt') x=data[:,0]; y=data[:,1]*3.0; z=data[:,2] ux = np.unique(x); uy = np.unique(y) Z = z.reshape(len(ux),len(uy)).T dx = np.diff(ux[:2])[0]; dy = np.diff(uy[:2])[0] ext = [ux.min()-dx/2.,ux.max()+dx/2.,uy.min()-dy/2., uy.max()+dy/2.] plt.imshow(Z, extent=ext, aspect="auto", cmap="magma") plt.show() Since the grid is very dense, it looks somehow pixelated. You may of course also bin your data into larger chunks. For example joining the data of 3x3 pixels into one and taking the maximum value, using scipy.stats.binned_statistic_2d import matplotlib.pyplot as plt import numpy as np from scipy.stats import binned_statistic_2d data = np.genfromtxt('data/some_solidstate_physics_data.txt') x=data[:,0]; y=data[:,1]*3.0; z=data[:,2] ux = np.unique(x); uy = np.unique(y) h, ex, ey,_ = binned_statistic_2d(x, y, z, bins=[ux[::3],uy[::3]], statistic='max') dx = np.diff(ex[:2])[0]; dy = np.diff(ey[:2])[0] ext = [ux.min()-dx/2.,ux.max()+dx/2.,uy.min()-dy/2., uy.max()+dy/2.] plt.imshow(h.T, extent=ext, aspect="auto", cmap="magma") plt.show() Having those techniques at your disposal you may then decide to beautify your result at the expense of quantitative accuracy. E.g. applying a gaussian filter, scipy.ndimage.filters.gaussian_filter as well as interpolation="gaussian" in the plotting. import matplotlib.pyplot as plt import numpy as np import scipy.ndimage.filters data = np.genfromtxt('data/so…
type: Answer
has comment: http://stackoverflow.com/comment/85430831
has comment: http://stackoverflow.com/comment/85427767
accepted answer of: http://stackoverflow.com/q/49201540

http://stackoverflow.com/comment/85450339
comment on: http://stackoverflow.com/q/49222992
has text: Can the `requests` happen concurrently?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85402962
has text: Tks @Ron Norris. Both solutions are not working though. The error message for both cases are: NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="div1"]"} Very interesting your comments on scrolled view. Maybe the error is because there are 2 scrolls inside the same page. I will look for more info on this. Tks!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49194339
type: AnswerComment

http://stackoverflow.com/comment/85329388
has text: matplotlib doesn't work in Jython - it relies on C modules. You could try generating the data in TopSpin, then loading the processed result in the normal environment of your machine. See NMRglue - https://github.com/jjhelmus/nmrglue/issues/13 - which can read Bruker data.
type: Comment
comment on: http://stackoverflow.com/q/49161570
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85532915
has text: May you better explain what do you mean my Copy, and a file containing many pages? Why not just upload the file to a FileField?
score: 0
comment on: http://stackoverflow.com/q/49264618
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49209172
score: 3
accepted answer of: http://stackoverflow.com/q/49209024
type: Answer
answers question: http://stackoverflow.com/q/49209024
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: top isn't the parent of your custom widget. You're never passing it. Your Scrollygrid is being passed a parent parameter and that's it. Nothing tells it to assign it as the parent as an attribute even. So the parent defaults to the Tk instance, root. Replace: super(Scrollygrid, self).__init__() with: super(Scrollygrid, self).__init__(parent) In order to pass the given widget argument as the parent to the superclass, Frame. Essentially making the Toplevel, top your custom class' parent. Upon which you'll get further error(s) but the parent is correctly assigned. Verify by: print(repr(self.winfo_toplevel()))

http://stackoverflow.com/a/49192499
accepted answer of: http://stackoverflow.com/q/49192335
type: Answer
has body: I think that it may be related to the tolerance of KMeans. The default value is 1e-4, so setting a lower value, i.e. tol=1e-8 gives: import pandas as pd import numpy as np from sklearn.cluster import KMeans np.random.seed(0) x = np.random.normal(size=5000) x_z = (x - x.mean() / x.std()).reshape(5000,1) cluster=KMeans(n_clusters=2, tol=1e-8).fit(x_z) df = pd.DataFrame(x_z) df['label'] = cluster.labels_ difference = np.abs(df.groupby('label').mean() - cluster.cluster_centers_) print(difference) 0 label 0 9.99200722e-16 1 1.11022302e-16 Hope it helps.
answers question: http://stackoverflow.com/q/49192335
score: 3
has comment: http://stackoverflow.com/comment/85389884
has comment: http://stackoverflow.com/comment/85391714
upvote count: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49157510
has comment: http://stackoverflow.com/comment/85321114
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49157120
downvote count: 0
has body: You may name the route when you add it: router.register( r'the-url_pattern$', TheViewSet, base_name='put-something-here', ) As an aside, it's strange to specify both queryset class attribute and get_queryset method, and this could be what was confusing DRF. Pick one way or the other.
has comment: http://stackoverflow.com/comment/85321620
type: Answer

http://stackoverflow.com/comment/85411604
type: Comment
score: 0
type: AnswerComment
has text: Amazing! Thank you so much for your help :). I am fairly new to python and not a big fan of arrays. Especially Multidimensional ones. This has helped me a lot. Thank you!
comment on: http://stackoverflow.com/a/49201117

http://stackoverflow.com/q/49248645
type: Question
score: 0
tagged with: list
answer count: 1
type: AnsweredQuestion
has title: How do I fill an empty list in a for loop?
tagged with: python
accepted answer: http://stackoverflow.com/a/49248703
has body: I was trying to do this in code, it's like filling an empty list with more lists. #These are the components I'm gonna use. I'm not using all of them. nc3=[-970689, 7.151, -.7698, 13.7097, 1872.82, -25.1011] ic4=[-1166846, 7.727, -0.9221, 13.8137, 2150.23, -27.6228] nc4=[-1280557, 7.95, -0.9646, 13.9836, 2292.44, -27.8623] ic5=[-1481583, 7.581, -0.9316, 13.6106, 2345.09, -40.2128] nc5=[-1524891, 7.331, -0.8914, 13.9778, 2554.6, -36.2529] nc6=[-1778901, 6.968, -0.8463, 14.0568, 2825.42, -42.7089] nc7=[-2013803, 6.529, -0.7954, 13.9008, 2932.72, -55.6356] nc9=[-255104, 5.693, -0.6782, 13.9548, 3290.56, -71.5056] components=input("How many components are you gonna use? ") g=[] for i in range (components): But I'm stuck there. How do I fill g without typing so much code? There can be the case where I use 4 components, but they can be different. How can I do something more general? Is for the correct command or do I need to do it in a while loop?
has answer: http://stackoverflow.com/a/49248703

http://stackoverflow.com/comment/85334834
type: Comment
score: 3
type: QuestionComment
has text: see https://github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10_multi_gpu_train.py to understand how to provide custom gradients for optimizer
comment on: http://stackoverflow.com/q/49155119

http://stackoverflow.com/q/49194081
has answer: http://stackoverflow.com/a/49194128
tagged with: pandas
tagged with: duplicates
has title: How to get dataframe of unique ids
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/49194128
answer count: 1
tagged with: python
type: AnsweredQuestion
has body: I'm trying to group the following dataframe by unique binId and then parse the resulting rows based of 'z' and pick the row with highest value of 'z'. Here is my dataframe. import pandas as pd df = pd.DataFrame({'ID':['1','2','3','4','5','6'], 'binId': ['1','2','2','1','1','3'], 'x':[1,4,5,6,3,4], 'y':[11,24,35,16,23,34],'z':[1,4,5,2,3,4]}) ` I tried following code which gives required answer, def f(x): tp = df[df['binId'] == x]'binId','ID','x','y','z'.sort_values(by='z', ascending=False).iloc[0] return tp` and then, binids= pd.Series(df.binId.unique()) print binids.apply(f) The output is, binId ID x y z 0 1 5 3 23 3 1 2 3 5 35 5 2 3 6 4 34 4 But the execution is too slow. What is the faster way of doing this?

http://stackoverflow.com/comment/85486400
type: Comment
score: 0
type: AnswerComment
has text: Your initial answer solved my problem. My program has a "save as" feature and, to take the name input, I could have had the menu call a Toplevel with an Entry and a button in it, but (from past experience) that's a massive pain for something that I might as well just use the input() for, so I wanted to know if there was a more efficient way. Your answer provided that. I only asked the in the way I did because I thought it would be more likely to get answered.
comment on: http://stackoverflow.com/a/49239818

http://stackoverflow.com/q/49169465
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/85344403
tagged with: python
has comment: http://stackoverflow.com/comment/85344261
has comment: http://stackoverflow.com/comment/85344247
has body: At this code, I have a data with lots combinations from 'a' 'b' 'c' 'd' and I am trying to find out how often each combination is existing.(example of the data: abdc, abcc, abcd, abbb, aaaa, abdc,...) After that I want to have the answer in percentage from 0% to 100% of each letter combination. Also if it's zero. Example Input: letters: ['abc','aaa','abb','acc','aac','abc','bbb','ccc','ddd','abc','adc','acd','acd','aac','aad','bba','bab','abb','abc','abd'...] I get df from this: ( tab_files is the file where get my data) for i, tab_file in enumerate(tab_files): df = pd.DataFrame.from_csv(tab_file, sep='\t') Here is my try: #letter_l = all combinations of letters (abcd) together nt_l = "abcd" letter_l = [] for i1 in nt_l: for i2 in nt_l: for i3 in nt_l: letter = i1+i2+i3 letter_l.append(letter) #print(letter_l) #calculates the amount of each letter combination and shows the percentage x = [] number_per_combination = {} for b in letter_l: counter = 0 number_per_combination[b] = 0 for c2 in df.letter: if c2 == b: counter +=1 number_per_combination[b] += 1 # amount of each letter combination divided through the whole amount x.append(counter/(len(df.letter))) but I get strange percentages as answer... I don't understand why. Can somebody help me? Output I want: number_per combination 'abc': 20% (40) 'aaa': 10% (20) 'ccd': 0% (0) 'ddd': 3% (6)...
answer count: 2
has title: Calculate percentages in Python (0% to100%)
has answer: http://stackoverflow.com/a/49171293
upvote count: 0
downvote count: 3
has answer: http://stackoverflow.com/a/49170071
favorite count: 0
type: Question

http://stackoverflow.com/q/49187748
tagged with: list
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85666335
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49188084
downvote count: 0
has answer: http://stackoverflow.com/a/49192018
has title: Add value to key, depending on if the value is in another key
tagged with: key
favorite count: 0
type: Question
tagged with: python
tagged with: dictionary
has body: I have the following dictionary: {'Atlanta': [['Bear', 34274], ['Deer', 13747], ['Bee', 83743]], 'New York': [['Bear', 987], ['Dove', 2635]]} A key that has a list as a value that contains lists with pairs of Animals and a number. Now I want that if a Animal exists in of of the keys, I want it also in all other keys but with a Zero instead of the number, so the dictionary should look like this: {'Atlanta': [['Bear', 34274], ['Deer', 13747], ['Bee', 83743], ['Dove', 0]], 'New York': [['Bear', 987], ['Dove', 2635], ['Deer', 0], ['Bee', 0]]} I cannot figure out how to do this. Can someone help me?
score: 2

http://stackoverflow.com/comment/85352422
score: 0
type: Comment
has text: Are there any methods to stop the moving point "my_line" showing again,after some running time
type: AnswerComment
comment on: http://stackoverflow.com/a/49139449

http://stackoverflow.com/a/49231013
answers question: http://stackoverflow.com/q/49178231
score: 1
type: Answer
has body: I posted this on pybind11 issues page as well, and received an answer, which I will copy here for other users encountering the same issue. jagerman's answer: The issue here is that when multiple inheritance is involved we rely on a constructor compatible with std::shared_ptr's aliasing constructor (constructor (8) here), which lets us create a holder containing a recast pointer (i.e. an A *) that keeps the original C * alive (and, if it ends up being the last object, destroys the C * rather than the A *). If you add: MyHolder( const MyHolder &amp;other, T* ptr ) : ptr_(ptr) {} the example will work. (Your example holder doesn't do any actual memory management, of course; in reality it would need to support the sort of aliasing described above).
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/49150587
tagged with: tensorflow
favorite count: 0
type: Question
score: 3
has body: I've read Distributed TensorFlow Doc and this question on StackOverflow but I still have some doubt about the dynamics behind the distributed training that can be done with TensorFlow and its Parameter Server Architecture. This is a snipped of code from the Distributed TensorFlow Doc: if FLAGS.job_name == "ps": server.join() elif FLAGS.job_name == "worker": # Assigns ops to the local worker by default. with tf.device(tf.train.replica_device_setter( worker_device="/job:worker/task:%d" % FLAGS.task_index, cluster=cluster)): # Build model... loss = ... global_step = tf.contrib.framework.get_or_create_global_step() train_op = tf.train.AdagradOptimizer(0.01).minimize( loss, global_step=global_step) And here part of the answer of the StackOverflow question that I read: The worker reads all of the shared model parameters in parallel from the PS task(s), and copies them to the worker task. These reads are uncoordinated with any concurrent writes, and no locks are acquired: in particular the worker may see partial updates from one or more other workers (e.g. a subset of the updates from another worker may have been applied, or a subset of the elements in a variable may have been updated). The worker computes gradients locally, based on a batch of input data and the parameter values that it read in step 1. The worker sends the gradients for each variable to the appropriate PS task, and applies the gradients to their respective variable, using an update rule that is determined by the optimization algorithm (e.g. SGD, SGD with Momentum, Adagrad, Adam, etc.). The update rules typically use (approximately) commutative operations, so they may be applied independently on the updates from each worker, and the state of each variable will be a running aggregate of the sequence of updates received. I have to reproduce this kind of parameter server architecture in another environment and I need to deeply understand how workers and PS tasks interact with each other inside the TensorFlow …
linked to: http://stackoverflow.com/q/43147435
tagged with: python
type: AnsweredQuestion
has title: Distributed TensorFlow [Async, Between-Graph Replication]: which are the exactly interaction between workers and servers regarding Variables update
accepted answer: http://stackoverflow.com/a/49151500
upvote count: 3
tagged with: distributed
answer count: 1
has answer: http://stackoverflow.com/a/49151500
downvote count: 0
tagged with: asynchronous

http://stackoverflow.com/a/49151166
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49144470
type: Answer
accepted answer of: http://stackoverflow.com/q/49144470
has body: You need to add a delay after each role removal. Just import asyncio and add an await asyncio.sleep(1). Your code should look like: if message.content.startswith("!unassign"): roles_cleared = True for r in role_list: # Check every role role = discord.utils.get(message.server.roles, name=r) if role in message.author.roles: # If they have the role, get rid of it try: await client.remove_roles(message.author, role) await asyncio.sleep(1) except discord.Forbidden: await client.send_message(message.author, "I don't have perms to remove roles.") roles_cleared = False break if roles_cleared: await client.send_message(message.author, "Roles successfully cleared.")
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/85442949
has text: But isn't the whole point that you don't know (to begin with) which word is in which list? `zip` only works if this ordering is guaranteed..
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49216777
type: AnswerComment

http://stackoverflow.com/comment/85369094
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49135355
type: Comment
has text: @PatrickArtner: thanks for your nice comment, I suppose the vote is from you. No wonder, that you could not help, I found out that this is a bug in wxPython 4 (see my edit above).

http://stackoverflow.com/a/49272033
type: Answer
has body: I am trying to solve adding the line if not exist in the data (data is multiline string input content). This can be done using pandas with the easy way, also solution will scales if you use pandas. I did not focus on the randomizing the number assigned to each line, I just cycling from 1 to 255 and once idx is reached I am starting from 1 again. :) this part you can take care... My quick solution is: import cStringIO as io import pandas as pd from itertools import cycle text_data = """abcd11 11 abcd12 12 abcd13 13 abcd21 14 abcd22 15 abcd23 16 abcd101 17 abcd102 18 abcd103 19 abcd501 1 abcd502 2""" def get_next_id(): cyc = cycle(range(1,256)) for i in cyc: yield i next_id = get_next_id() def load_data(): content = io.StringIO(text_data) df = pd.read_csv(content, header=None, sep="\s+", names=["txt", "num"]) print "Content is loaded to pandas dataframe\n", df return df def add_line_to_df(txt, df): idx = next_id.next() df2 = pd.DataFrame(txt, idx, columns=["txt", "num"]) df.loc[len(df.index)] = df2.iloc[0] #print df #res_df return df # res_df def insert_valid_line(line, df): if line in pd.Series(df["txt"]).values: print "{}: already existed.".format(line) else: print "{}: adding to existing df.".format(line) add_line_to_df(line, df) def main(): df = load_data() new_texts = ["abcd501", "abcd502", "abcd402", "abcd403"] for txt in new_texts: print "-" * 20 insert_valid_line(txt, df) print "-" * 20 print df #In this place df is holding all the data if __name__ == '__main__': main() Output looks like this...: Content is loaded to pandas dataframe txt num 0 abcd11 11 1 abcd12 12 2 abcd13 13 3 abcd21 14 4 abcd22 15 5 abcd23 16 6 abcd101 17 7 abcd102 18 8 abcd103 19 9 abcd501 1 10 abcd502 2 -------------------- abcd501: already existed. -------------------- abcd502: already existed. -------------------- abcd402: adding to existing df. -------------------- abcd403: adding to existing df. -------------------- txt num 0 abcd11 11 1 abcd12 12 2 abcd13 13 3 abcd21 14 4 abcd22 …
score: 0
answers question: http://stackoverflow.com/q/49270354

http://stackoverflow.com/q/49231823
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85467970
tagged with: tensorflow
favorite count: 0
type: Question
has title: Binary classification, prediction is 0
has body: I am training to create CNN to play geometry dash. I use AlexNet, which is little bit modified to produce output between -1 to 1. When output> 0 then it should jump. When output&lt; 0 then it should do nothing. My training data are 80x60 gray images pair with value -1 or 1 , which indicates, what it should do at this frame. I have 7700 images. (1 is jump) (-1 is to do nothing) My AlexNet: network = input_data(shape=[None, width, height, 1], name='input') network = conv_2d(network, 96, 11, strides=4, activation='relu') network = max_pool_2d(network, 3, strides=2) network = local_response_normalization(network) network = conv_2d(network, 256, 5, activation='relu') network = max_pool_2d(network, 3, strides=2) network = local_response_normalization(network) network = conv_2d(network, 384, 3, activation='relu') network = conv_2d(network, 384, 3, activation='relu') network = conv_2d(network, 256, 3, activation='relu') network = max_pool_2d(network, 3, strides=2) network = local_response_normalization(network) network = fully_connected(network, 4096, activation='tanh') network = dropout(network, 0.5) network = fully_connected(network, 4096, activation='tanh') network = dropout(network, 0.5) network = fully_connected(network, output, activation='sigmoid') network = regression(network, optimizer='adam', loss='binary_crossentropy', learning_rate=lr, name='targets') model = tflearn.DNN(network, checkpoint_path='model_alexnet', max_checkpoints=1, tensorboard_verbose=2, tensorboard_dir='log') If I want to learn the CNN, it all the time predicts something around 0 for all inputs. What should I do? I want to predict for each frame 1 or -1. I know that sigmoid can t reach 1 or -1, so I shift it by 0.001 to 0.999 and -0.999, but it still doesn t work. EDIT: Data are balanced, but shuffled. Same number images for jump and not jump. Moreover I tried to use inbalanced data, but it ended in the different number for all the images.
has comment: http://stackoverflow.com/comment/85622941
tagged with: tflearn
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85468328
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/49317744
accepted answer: http://stackoverflow.com/a/49317744
score: 1
answer count: 1

http://stackoverflow.com/comment/86059076
has text: yes, already tried, but package needed SKLEARN,Numpy and Pandas with no conflict with version.
comment on: http://stackoverflow.com/q/49276118
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49152131
score: 4
tagged with: multiple-axes
duplicate of: http://stackoverflow.com/q/29046057
type: UnansweredQuestion
tagged with: bar-chart
has body: I need to plot a grouped bar chart with two y axes and one x axis. The plot looks like the following if drawn in matplotlib I want it by python plotly but I could not find a solution. There seems to be a similar question two years ago, but I did not get it to work when I tried to do it similarly. Here is the code snippet that I tested: import plotly import plotly.graph_objs as go import numpy as np import pandas as pd from io import StringIO s = StringIO(""" amount price A 40929 4066443 B 93904 9611272 C 188349 19360005 D 248438 24335536 E 205622 18888604 F 140173 12580900 G 76243 6751731 H 36859 3418329 I 29304 2758928 J 39768 3201269 K 30350 2867059""") df = pd.read_csv(s, index_col=0, delimiter=' ', skipinitialspace=True) plotly.offline.plot({ "data": [go.Bar(x=df.index, y=df.price, name="price"), go.Bar(x=df.index, y=df.amount, name="amount", yaxis='y2'), ], "layout": go.Layout(title="Amount and price", yaxis=dict( title='price', autorange = True, range = [0, max(df.price)], ), yaxis2=dict( title='amount', autorange = True, range = [0, max(df.amount)], overlaying='y', side='right' ), barmode='group', autosize=True), }) please note that I gave barmode='group' but this does not take effect.
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/58785299
favorite count: 0
tagged with: plotly
has title: How to plot grouped bar chart with multiple y axes in python plotly
linked to: http://stackoverflow.com/q/29046057
tagged with: python
has comment: http://stackoverflow.com/comment/124911523
type: Question
upvote count: 4

http://stackoverflow.com/a/78169321
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49128964
has body: See NLTK Documentation under Manual Installation: Create a folder nltk_data, e.g. C:\nltk_data, or /usr/local/share/nltk_data, and subfolders chunkers, grammars, misc, sentiment, taggers, corpora, help, models, stemmers, tokenizers. Download individual packages from https://www.nltk.org/nltk_data/ (see the “download” links). Unzip them to the appropriate subfolder. For example, the Brown Corpus, found at: https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages/corpora/brown.zip is to be unzipped to nltk_data/corpora/brown. Set your NLTK_DATA environment variable to point to your top level nltk_data folder.

http://stackoverflow.com/comment/86197051
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49426448
has text: @eguaio - Ah well, what matters is spreading useful information. Your answer is good and a worthy choice even if technically not the right one in this specific case. I might ask that you either incorporate a note about GC into yours, post-mortem, or direct people to check out this answer as well. GC behavior is a good thing for people to learn about. I don't care too much about credit; I just want people to learn.

http://stackoverflow.com/q/49146004
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85296749
upvote count: 1
has comment: http://stackoverflow.com/comment/85296903
has comment: http://stackoverflow.com/comment/85296835
favorite count: 0
type: Question
tagged with: python-3.x
has title: Python: Class inherit
has body: What is different between the two situation? # Error: Cannot create a consistent method resolution order (MRO) for bases A, B class A: pass class B(A): pass class C(A, B): pass # Current situation class A: pass class B(A): pass class C(B, A): pass
linked to: http://stackoverflow.com/q/21657822
has comment: http://stackoverflow.com/comment/85296978
has answer: http://stackoverflow.com/a/49146175
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49146175

loops
tags question: http://stackoverflow.com/q/49213155
tags question: http://stackoverflow.com/q/49162588
tags question: http://stackoverflow.com/q/49184828
tags question: http://stackoverflow.com/q/49260329
tags question: http://stackoverflow.com/q/49247407
tags question: http://stackoverflow.com/q/49176797
tags question: http://stackoverflow.com/q/49174910
tags question: http://stackoverflow.com/q/49160579
tags question: http://stackoverflow.com/q/49210113
tags question: http://stackoverflow.com/q/49235666
tags question: http://stackoverflow.com/q/49178102
tags question: http://stackoverflow.com/q/49258269
tags question: http://stackoverflow.com/q/49137151
tags question: http://stackoverflow.com/q/49203568
tags question: http://stackoverflow.com/q/49182170
tags question: http://stackoverflow.com/q/49159102
tag name: loops
tags question: http://stackoverflow.com/q/49165370
tags question: http://stackoverflow.com/q/49247268
tags question: http://stackoverflow.com/q/49266464
tags question: http://stackoverflow.com/q/49165767
tags question: http://stackoverflow.com/q/49122265
tags question: http://stackoverflow.com/q/49221270
tags question: http://stackoverflow.com/q/49226167
tags question: http://stackoverflow.com/q/49243913
tags question: http://stackoverflow.com/q/49278321
tags question: http://stackoverflow.com/q/49215960
tags question: http://stackoverflow.com/q/49205354
tags question: http://stackoverflow.com/q/49219009
tags question: http://stackoverflow.com/q/49147403
tags question: http://stackoverflow.com/q/49227092
type: Tag
tags question: http://stackoverflow.com/q/49220146
tags question: http://stackoverflow.com/q/49248978
tags question: http://stackoverflow.com/q/49157640
tags question: http://stackoverflow.com/q/49179377
tags question: http://stackoverflow.com/q/49184456
tags question: http://stackoverflow.com/q/49140169
tags question: http://stackoverflow.com/q/49158987
tags question: http://stackoverflow.com/q/49186633
tags question: http://stackoverflow.com/q/49129349
tags question: http://stackoverflow.com/q/49261711
tags question: http://stackoverflow.com/q/49172072
tags question: http://stackoverflow.com/q/49155280
tags question: http://stackoverflow.com/q/49205470
tags question: http://stackoverflow.com/q/49262993
tags question: http://stackoverflow.com/q/49203542
tags question: http://stackoverflow.com/q/49225393
tags question: http://stackoverflow.com/q/49224492
tags question: http://stackoverflow.com/q/49276214
tags question: http://stackoverflow.com/q/49184885
tags question: http://stackoverflow.com/q/49159523
tags question: http://stackoverflow.com/q/49221151

http://stackoverflow.com/comment/85456846
comment on: http://stackoverflow.com/q/49223219
type: Comment
has text: The code is one part of my implemented algorithm, and nn is to get the values I need in the matrix.
score: 0
type: QuestionComment

http://stackoverflow.com/a/49216587
has comment: http://stackoverflow.com/comment/123132191
upvote count: 16
type: Answer
score: 16
has comment: http://stackoverflow.com/comment/123129754
has comment: http://stackoverflow.com/comment/85437254
downvote count: 0
type: AcceptedAnswer
has body: I think you are are looking for transform in this situation: df['count'] = df.groupby(['col1', 'col2'])['col3'].transform('count')
has comment: http://stackoverflow.com/comment/101841514
accepted answer of: http://stackoverflow.com/q/49216357
has comment: http://stackoverflow.com/comment/123135024
answers question: http://stackoverflow.com/q/49216357

http://stackoverflow.com/q/49276477
tagged with: python
has comment: http://stackoverflow.com/comment/85555702
has comment: http://stackoverflow.com/comment/85564037
has comment: http://stackoverflow.com/comment/85562115
has body: I have a python script, runned by cron: "*/5 * * * * python /home/alex/scripts/checker > /dev/null &amp;"; It has several purposes, one of them is to check certain programs in ps list and run them if they are not there. The problem is that script when runned by cron not executed programs in backgroung correctly, all of them are in ps list look like: /usr/bin/python /home/alex/exec/runnable So they look like python scripts. When I launch my python script manually it seems that it executes runnable in background corretcly, but with cron nothing works. Here's the example of code: def exec(file): file = os.path.abspath(file) os.system("chmod +x " + file) cmd = file #os.system(cmd) #subprocess.Popen([cmd]) subprocess.call([cmd]) I tried different approaches but nothing seems to work right. Some code update: pids = get_pids(program) if pids == None: exec(program) print 'Restarted'
has comment: http://stackoverflow.com/comment/85561824
type: Question
has comment: http://stackoverflow.com/comment/85555451
has comment: http://stackoverflow.com/comment/85555704
has comment: http://stackoverflow.com/comment/85555434
has comment: http://stackoverflow.com/comment/85564678
has comment: http://stackoverflow.com/comment/85563122
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85564743
has comment: http://stackoverflow.com/comment/85561963
has comment: http://stackoverflow.com/comment/85561872
has comment: http://stackoverflow.com/comment/85555528
score: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/85561836
has comment: http://stackoverflow.com/comment/85564179
tagged with: cron
has title: Python script doesn't run background process, when called by cron
has comment: http://stackoverflow.com/comment/85564092

http://stackoverflow.com/q/49121985
answer count: 1
has comment: http://stackoverflow.com/comment/85249667
has title: extracting single value from json file to text file
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49122087
has answer: http://stackoverflow.com/a/49122087
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has comment: http://stackoverflow.com/comment/85249595
has comment: http://stackoverflow.com/comment/85249747
type: Question
has comment: http://stackoverflow.com/comment/85249647
has body: i have json file like this {"lomx": "3 lokan", "idx": "kojemany94AaABAg", "moraku": "loerlaosjdis hejuyasdb", "keyword": "mekanobhaemausjek14232", "subhen": "koshdeksad"} {"lomx": "3 lokan", "idx": "kojemany94AaABAg", "moraku": "londasjhdj", "keyword": "mekanobhaemausjek223232323", "subhen": "uahdioasdohoasd"} {"lomx": "4 lokan", "idx": "jhalskdjhakljdisoaj", "moraku": "vajdlajd", "keyword": "mekanobhaemausjek3242312345", "subhen": "jshdajshdajhsdjhaksdjhsjdkahsdjkah"} {"lomx": "4 lokan", "idx": "jahdjheuhasndashduasd", "moraku": "morkajsdhu", "keyword": "mekanobhaemausjek273232323232", "subhen": "lokamajuaksdksdasdaahsjdhkajhsdjkahs"} i need to extract all the single values of "keyword" and add it to text file line by line result should be something like this mekanobhaemausjek14232 mekanobhaemausjek223232323 mekanobhaemausjek3242312345 mekanobhaemausjek273232323232 this is what i've tried import json data_file = 'c:\json_file.json' json_data = open(data_file) parsed_json = json.loads(json_data) for mydata in parsed_json['keyword'] print (mydata) f = open('jessers.txt','a') f.write("%s\n" % mydata) f.close()
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85249534
upvote count: 0
score: -2
downvote count: 2

http://stackoverflow.com/a/49207358
has body: use scalar instead of all scalar will extract the first value in the tuple returned so, [('tshibek',)] will be returned as 'tshibek'. @app.route('/login',methods=['GET','POST']) def login(): username = db.session.query(User.username).order_by(User.username.desc()).limit(1).scalar() return render_template("index.html",user = username) if you have a nicknames in a list of tuples rows = [('tshibe',),('tshibek',),('wasda',),('something')] extract the nicknames using list comprehension nicks = [x[0] for x in rows] This will return a list like this: ['tshibe','tshibek','wasda','something'] you can prepend the base url to it like this base = 'http://localhost/profil' urls = ['{}/{}'.format(base, n) for n in nicks]
type: Answer
has comment: http://stackoverflow.com/comment/85419608
upvote count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85419687
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49207257
accepted answer of: http://stackoverflow.com/q/49207257

http://stackoverflow.com/comment/85442787
has text: `['aa ao ooo']` is a list that contains a single element (a string with spaces), so it doesn't make a lot of sense to use as input. It would make more sense to use `['aa', 'ao', 'ooo']`, or simply a string like `'aa ao ooo'` which could be turned into a list with `split()`.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49219328

http://stackoverflow.com/a/49182970
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85386117
has comment: http://stackoverflow.com/comment/85381899
answers question: http://stackoverflow.com/q/49182395
downvote count: 0
has comment: http://stackoverflow.com/comment/85406594
upvote count: 1
has body: Can you confirm you have tesseract installed too? (https://github.com/madmaze/pytesseract#installation) Based on this issue: https://github.com/madmaze/pytesseract/issues/58, the author of the package seems to indicate that your issue is a missing dependency.

http://stackoverflow.com/comment/85303274
comment on: http://stackoverflow.com/q/49149348
score: 3
has text: Under what circumstances does `Sys.which` not work?
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49163099
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/121796055
has answer: http://stackoverflow.com/a/49163584
has comment: http://stackoverflow.com/comment/85346360
has answer: http://stackoverflow.com/a/49163707
has comment: http://stackoverflow.com/comment/85332610
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/68915908
answer count: 2
type: UnansweredQuestion
tagged with: python
upvote count: 4
score: 4
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/85332802
tagged with: aws-lambda
has title: Writing a file to S3 using Lambda in Python with AWS
has comment: http://stackoverflow.com/comment/85332148
has body: In AWS, I'm trying to save a file to S3 in Python using a Lambda function. While this works on my local computer, I am unable to get it to work in Lambda. I've been working on this problem for most of the day and would appreciate help. Thank you. def pdfToTable(PDFfilename, apiKey, fileExt, bucket, key): # parsing a PDF using an API fileData = (PDFfilename, open(PDFfilename, "rb")) files = {"f": fileData} postUrl = "https://pdftables.com/api?key={0}&amp;format={1}".format(apiKey, fileExt) response = requests.post(postUrl, files=files) response.raise_for_status() # this code is probably the problem! s3 = boto3.resource('s3') bucket = s3.Bucket('transportation.manifests.parsed') with open('/tmp/output2.csv', 'rb') as data: data.write(response.content) key = 'csv/' + key bucket.upload_fileobj(data, key) # FYI, on my own computer, this saves the file with open('output.csv', "wb") as f: f.write(response.content) In S3, there is a bucket transportation.manifests.parsed containing the folder csv where the file should be saved. The type of response.content is bytes. From AWS, the error from the current set-up above is [Errno 2] No such file or directory: '/tmp/output2.csv': FileNotFoundError. In fact, my goal is to save the file to the csv folder under a unique name, so tmp/output2.csv might not be the best approach. Any guidance? In addition, I've tried to use wb and w instead of rb also to no avail. The error with wb is Input &lt;_io.BufferedWriter name='/tmp/output2.csv'&gt; of type: &lt;class '_io.BufferedWriter'&gt; is not supported. The documentation suggests that using 'rb' is the recommended usage, but I do not understand why that would be the case. Also, I've tried s3_client.put_object(Key=key, Body=response.content, Bucket=bucket) but receive An error occurred (404) when calling the HeadObject operation: Not Found.
has comment: http://stackoverflow.com/comment/85331954
downvote count: 0

http://stackoverflow.com/q/49241429
tagged with: locking
has comment: http://stackoverflow.com/comment/85491268
tagged with: python
has body: I have this code: SP500 = pd.read_csv("http://trading.chrisconlan.com/SPstocks_current.csv", header=-1, names=['Symbol']).copy() SP500=list(SP500.Symbol) SP500=['AVGO', 'GM', 'FDX', 'goog'] threads = [] lock = threading.Lock() offset = 1 multiply = 1 num_of_threads = 4 for i in range(0, num_of_threads): t = threading.Thread(target=digest_distros, args=(SP500, i * multiply, i * multiply + offset)) t.start() threads.append(t) for t in threads: t.join() This is the func def digest_distros(SPT500, start, finish): for stock in SP500[start:finish]: daily, stock_distro = get_daily_adjusted(stock) if daily is None: continue monthly_adjusted_close=get_monthly_adjusted(stock) if monthly_adjusted_close is None: continue with lock: print "\n" print "############## " + stock + " ##############" print daily'low', 'high', 'open', 'adjusted close'.tail(1) print "\n" curr_monthly_adjusted=monthly_adjusted_close[-1] print "##########################" print "current monthly adjusted close is: {}".format(curr_monthly_adjusted) required_value_for_signal=find_min_signal_value(monthly_adjusted_close) print "Required value for signal tommorow is : {}".format(required_value_for_signal) print "##########################" print "\n" spans = [0.3, 0.5, 1, 2,3,5] for span in spans: mean=stock_distro[span][0] std=stock_distro[span][1] if abs(curr_monthly_adjusted-required_value_for_signal) &lt; 3: print "Time span is {:.3f} years, daily change mean {:.3f}, daily change std {:.3f}".format(span,mean,std) z_value=calculate_z_value(required_value_for_signal, curr_monthly_adjusted, mean, std) # if z_value&gt;0.3: print "Probability is: {:.3f}".format(z_value) When running, if the code reaches the code inside the for loop or inside the if statement (I think), I lose my lock... Can't understand why. Example output for mixed printing. ######## GM # current monthly adjusted close is: 37.64 Required value for signal tommorow is : 38.5 # Time span is 0.300 years, daily change mean -0.083, daily change …
tagged with: concurrency
has comment: http://stackoverflow.com/comment/85493697
has answer: http://stackoverflow.com/a/49261269
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/37534440
accepted answer: http://stackoverflow.com/a/49261269
score: 0
has comment: http://stackoverflow.com/comment/85489176
has comment: http://stackoverflow.com/comment/85494143
tagged with: multithreading
answer count: 1
has title: Locking in python does not behave like expected
has comment: http://stackoverflow.com/comment/85509828
type: Question
has comment: http://stackoverflow.com/comment/85491459

http://stackoverflow.com/a/49184063
has comment: http://stackoverflow.com/comment/85374257
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49183973
has body: You are overwriting the value of vdisks["name"] each time you pass through the for loop. It starts off as "asm" then you add 0 to it, then you add 1 during the next iteration, and finally 2 in the third. You can create a new variable to store the original value and add that instead: vdisks = { "name": "asm", "size": "1024000" } name = vdisks["name"] for i in range(3): new_vdisks = vdisks new_vdisks["name"] = name + str(i) print new_vdisks Because it never passes through the for loop the new variable never changes from asm giving your expected output.

http://stackoverflow.com/comment/85467612
type: AnswerComment
comment on: http://stackoverflow.com/a/49226859
has text: Well, the native API evolves under the hood of the pyzmq. Given the initial versions of PAIR/PAIR were since inception labeled "experimental" and "for inter-thread communications", be rather careful on field deployment, where one has zero-warranty what would be the API version of the remote peer(s). A complete resource-management + error-detection + robust error-recovery strategy is a standard bread & butter in **[tag:distributed-system]**. RADIO/DISH seem to me to be just a re-labeled PUB/SUB Scalable Formal Communication Archetype, se best re-read the native API 4.2+ details.
type: Comment
score: 0

http://stackoverflow.com/q/49137673
has answer: http://stackoverflow.com/a/49138115
downvote count: 1
has comment: http://stackoverflow.com/comment/85280449
favorite count: 0
has comment: http://stackoverflow.com/comment/85280789
linked to: http://stackoverflow.com/q/4110891
has title: Writing to file not working in Python
answer count: 1
tagged with: python
score: -1
type: Question
has body: I'm having issues writing to a text file. The first file gets created but there are no text that is written. Here is my code: def write2file(self): generate_file = ['SHIFT_TRAFFIC_OFF','REMOVE_ADD_BUNDLE','SHIFT_TRAFFIC_ON'] for method in generate_file: f = open("/home/superloop/10gto100g/test/%s_%s" % (self.hostname,method), "w") output = getattr(self,method) # self.SHIFT_TRAFFIC_OFF() f.write(output()) f.close() def SHIFT_TRAFFIC_OFF(self): print "router ospf 1" print " area 0" print " interface Bundle-Ether%s" % self.bundle print " cost 100" print "!" print "router ospfv3 1" print " area 0" print " interface Bundle-Ether%s" % self.bundle print " cost 100" And here is the output when I execute the application: router ospf 1 area 0 interface Bundle-Ether4 cost 100 ! router ospfv3 1 area 0 interface Bundle-Ether4 cost 100 Traceback (most recent call last): File "main.py", line 42, in &lt;module&gt; main() File "main.py", line 20, in main parse_engine(database) File "/home/superloop/10gto100g/parser.py", line 15, in parse_engine device = BaseDevice(list[0],list[1],list[2],list[3],list[4]) File "/home/superloop/10gto100g/objects/basedevice.py", line 12, in __init__ self.write2file() File "/home/superloop/10gto100g/objects/basedevice.py", line 20, in write2file f.write(output()) TypeError: expected a character buffer object What is going on here?
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85280510
tagged with: file-writing

http://stackoverflow.com/comment/85400765
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49197601
has text: @FahimShahriar, is that the full traceback? Also, try replacing the backslashes with forward slashes.

http://stackoverflow.com/a/49203419
type: Answer
answers question: http://stackoverflow.com/q/49203300
score: 2
upvote count: 2
has body: JS: Iterate through the keys of input object, assign each key to output object's country field and corresponding value to its language field. var input = {"spain":"spanish"}; var output = []; Object.keys(input).forEach((key, ind) =&gt; { output.push({country: key, language:input[key]}); }); console.log(output);
downvote count: 0

http://stackoverflow.com/q/49254009
has body: I have two dataframes, df and df1. The first one contains all the information about all the possible combination of a dataset while the second one is just a subset without the information. df x y distance 0 1 4 0 2 3 0 3 2 1 2 2 1 3 5 2 3 1 df1 x y 1 3 2 3 2 3 I would like to merge df and df1 in order to have the following: df1 x y distance 1 3 5 2 3 1 2 3 1
linked to: http://stackoverflow.com/q/41815079
linked to: http://stackoverflow.com/q/53645882
duplicate of: http://stackoverflow.com/q/40468069
has title: Python: how to merge two dataframes with different size?
upvote count: 0
duplicate of: http://stackoverflow.com/q/41815079
tagged with: pandas
duplicate of: http://stackoverflow.com/q/53645882
answer count: 1
score: -6
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85511580
has answer: http://stackoverflow.com/a/49254118
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/40468069
downvote count: 6

http://stackoverflow.com/q/49273406
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85549535
has body: If I go for example from urlib2 import urllib.request response = urllib.request.urlopen('http://python.org/') html = response.read() then it works fine. I was suprised to see that my code req = urllib.request.Request('https://www.tehnomanija.rs/it-shop/laptop-racunari') response = urllib.request.urlopen(req) the_page = response.read() data = json.loads(the_page) print (data) produces error like this data = json.loads(the_page) File "/home/mm/anaconda3/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/home/mm/anaconda3/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/home/mm/anaconda3/lib/python3.6/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Except the other protocol I do not see why this would not work.
type: AnsweredQuestion
has title: HTTPS urllib.request,read into JSON
answer count: 1
accepted answer: http://stackoverflow.com/a/49273428
downvote count: 1
has answer: http://stackoverflow.com/a/49273428
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85549598
upvote count: 0

qwidget
tag name: qwidget
tags question: http://stackoverflow.com/q/49171587
type: Tag

http://stackoverflow.com/q/49188198
tagged with: numpy
tagged with: python-3.x
type: UnansweredQuestion
has body: Is there a function like numpy.save but such that it saves a list (not an array) to a binary file? Let's say I want to save a heterogeneous list that contains numbers and characters a = [1,2,3,4,'a'] If I save it with numpy.save, and then load it np.save('a.npy',a) b = np.load('a.npy').tolist() then I get a list of characters only: print(type(b),b) &lt;class 'list'&gt; ['1', '2', '3', '4', 'a']
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85385401
has answer: http://stackoverflow.com/a/49188303
upvote count: 1
has comment: http://stackoverflow.com/comment/85382521
score: 1
tagged with: python
has title: Is there an analog of numpy.save for lists?
favorite count: 0
type: Question

http://stackoverflow.com/a/49178883
score: 4
has comment: http://stackoverflow.com/comment/90210996
accepted answer of: http://stackoverflow.com/q/49172201
has comment: http://stackoverflow.com/comment/132199248
has comment: http://stackoverflow.com/comment/90198852
has comment: http://stackoverflow.com/comment/133058707
has comment: http://stackoverflow.com/comment/133064659
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/132253564
answers question: http://stackoverflow.com/q/49172201
type: AcceptedAnswer
has body: There's nothing built in to Bokeh to do this. You could accomplish something with a custom extension: from bokeh.models CategoricalTicker JS_CODE = """ import {CategoricalTicker} from "models/tickers/categorical_ticker" export class MyTicker extends CategoricalTicker type: "MyTicker" get_ticks: (start, end, range, cross_loc) -&gt; ticks = super(start, end, range, cross_loc) # drops every other tick -- update to suit your specific needs ticks.major = ticks.major.filter((element, index) -&gt; index % 2 == 0) return ticks """ class MyTicker(CategoricalTicker): __implementation__ = JS_CODE p.xaxis.ticker = MyTicker() Note that the simple get_ticks defined above will not handle more complicated situations with nested categories, etc.
downvote count: 0

http://stackoverflow.com/q/49131012
downvote count: 1
favorite count: 0
type: Question
has title: Infinite loop using a for loop python
has comment: http://stackoverflow.com/comment/85266568
has comment: http://stackoverflow.com/comment/85267124
has comment: http://stackoverflow.com/comment/85268910
has answer: http://stackoverflow.com/a/49131065
has body: So I'm trying to make a infinite loop that uses a for loop instead of a while loop. This is my current code. If this code works it should produce x infinitely. Current code: z=1 for x in range(0,z): print(x) z=z+1
has answer: http://stackoverflow.com/a/49131181
has answer: http://stackoverflow.com/a/49131131
tagged with: for-loop
has comment: http://stackoverflow.com/comment/85266555
score: 0
has comment: http://stackoverflow.com/comment/85269630
answer count: 3
upvote count: 1
tagged with: python
tagged with: variables
type: UnansweredQuestion

http://stackoverflow.com/a/49267123
type: Answer
answers question: http://stackoverflow.com/q/49266999
has body: Are you trying to make the tick labels readable by changing the aspect ratio of the figure itself or by moving the tick labels themselves? The aspect ratio can be configured to make the labels more readable by: graph = plt.figure(figsize=(x, y)) While you can simply configure the positioning of the labels themselves by rotation or a number of other methods: plt.xticklabels(rotation=90)
score: 0

http://stackoverflow.com/comment/114352096
has text: @Linh Nguyễn Ngọc Thank you for replying. I'm glad your issue was resolved. I apologize that I was not useful.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49247346

http://stackoverflow.com/a/49233568
has body: You can set Log Level to ERROR, so it will only show ERROR logs: sc.setLogLevel("ERROR") # sc is a SparkContext() object from the pyspark lib But if you want to disable all PySpark logs you can do this: sc.setLogLevel("OFF") Check this Stack Thread
has comment: http://stackoverflow.com/comment/85504113
upvote count: 1
has comment: http://stackoverflow.com/comment/85474871
answers question: http://stackoverflow.com/q/49232611
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85515349
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49232611

http://stackoverflow.com/q/49173655
answer count: 1
tagged with: elasticsearch
downvote count: 1
accepted answer: http://stackoverflow.com/a/49173957
favorite count: 0
tagged with: curl
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49173957
has comment: http://stackoverflow.com/comment/85352302
tagged with: python
has title: Files and values in python
score: -1
tagged with: python-3.6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85352479
upvote count: 0
has body: the below query is reading from a file called number.txt and prints out the numbers. i want to some how read the number.txt file and then run a update curl query against the numbers in the txt file. the query for reading the file f = open('number.txt', 'r') file_contents = f.read() print (file_contents) f.close() this is the update curl query, as you can i want to update the color to red. so i want to read the number txt file which contains ID and then updated the colour against those ID to red. curl query coll.update(index='stories-test',doc_type='news',id=hit.meta.id, body={"doc": {"colour": red }}) number.txt (this contains ID for unique people) 20170512 20170512 20170908 20170908 anyone able to help and show me how to do this. thanks

http://stackoverflow.com/comment/85541057
has text: Hi, I did what you suggested and found the error from a different part of the code. Thanks so much, i'll remember to try these stuffs next time~
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49268504
type: Comment

http://stackoverflow.com/comment/85355514
comment on: http://stackoverflow.com/a/49174902
score: 0
type: AnswerComment
has text: Thnx. so the key was reset index at every group by of ID
type: Comment

http://stackoverflow.com/comment/85548458
has text: Note that this will lead to an `IndexError`, the way the list is used here…
score: 1
comment on: http://stackoverflow.com/a/49272921
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85383135
comment on: http://stackoverflow.com/a/49188144
type: Comment
score: 0
type: AnswerComment
has text: @lotteryman, check my edit. I add some annotation and explain the key of the solution.

http://stackoverflow.com/q/49252573
has comment: http://stackoverflow.com/comment/85509177
linked to: http://stackoverflow.com/q/10901161
tagged with: python
has comment: http://stackoverflow.com/comment/85508963
tagged with: optimization
type: Question
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/49253792
downvote count: 0
has comment: http://stackoverflow.com/comment/85509031
upvote count: 1
type: UnansweredQuestion
score: 1
has body: I wrote a function which converts the unicode encoding in my input data to utf-8 encoding. The function is capable to handle the raw string OR dict OR list as an input and returns the respective utf-8 encoded output. This function is a part of bigger project that i am working on. This function is giving correct output as expected. The problem is that it is becoming a bottleneck for me in terms of execution time. Though the current execution time is turning out to be close to ~1ms but as i said, its a part of bigger project where i had to call this function repetitively which ultimately is harming my response time of API def fix_unicode(self, data): if isinstance(data, unicode): return data.encode('utf-8') elif isinstance(data, dict): data = dict((fix_unicode(k), fix_unicode(data[k])) for k in data) elif isinstance(data, list): for i in xrange(0, len(data)): data[i] = fix_unicode(data[i]) return data Can i further optimise this function ? if yes how ?
has answer: http://stackoverflow.com/a/49739683
has title: Optimising python encoding function
has comment: http://stackoverflow.com/comment/85509870
has comment: http://stackoverflow.com/comment/85508869
favorite count: 0
has comment: http://stackoverflow.com/comment/85510927

http://stackoverflow.com/comment/85523366
has text: @Dadep I saw that, but I have only one plot instead of many
comment on: http://stackoverflow.com/q/49259569
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85288721
score: 0
type: Comment
has text: in the HTML code that I have it doesn't have the closing character `/` at the end.
comment on: http://stackoverflow.com/q/49141584
type: QuestionComment

http://stackoverflow.com/comment/85279664
score: 0
comment on: http://stackoverflow.com/q/49136897
type: QuestionComment
type: Comment
has text: It is not. I want to change TemplateView.as_view(template_name="ang_home.html") to index.html in the static files

http://stackoverflow.com/q/49197916
type: Question
tagged with: cpu-usage
tagged with: python
accepted answer: http://stackoverflow.com/a/49212252
has answer: http://stackoverflow.com/a/49212252
upvote count: 15
score: 15
linked to: http://stackoverflow.com/q/582336
type: AnsweredQuestion
tagged with: profiling
downvote count: 0
linked to: http://stackoverflow.com/q/44637844
tagged with: keras
answer count: 1
favorite count: 0
has body: Ideally what I want is to record the CPU usage of a Python script that is executing a deep neural net Keras model. I'm looking for the CPU equivalent of memory_profiler, which provides the memory consumption of a process. I have looked at using psutil (suggested in this answer) which would indicate my script could contain some variant of p = psutil.Process(current_pid) p.cpu_percent() but the problem is the important function call I really want to capture the effect of would be the inference stage of the model model.predict(x_test) and if I run psutil before/after this step the CPU usage recorded won't be a true reflection of the CPU usage of the process. So then I was thinking could I use something like top/htop to log the CPU usage of the script to some file, capturing the fluctuating CPU usage while the process is running, and then calculate an average (or something similar) after the fact. The issue I see with this, however, is don't I need to know the PID to utilise top, so how can I use top to monitor the script before it is executed (and hasn't even been assigned a PID)? I can see this highly-ranked answer suggests cProfile which gives the running time of functions within a script. Although this isn't exactly what I want I do notice that it returns the total number of CPU seconds, which would at least let me compare CPU usage in that regard.
has title: How to profile CPU usage of a Python script?

http://stackoverflow.com/a/49219296
type: Answer
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49218936
has body: The issue was the firewall permissions for python
score: 0
accepted answer of: http://stackoverflow.com/q/49218936

http://stackoverflow.com/comment/85368295
comment on: http://stackoverflow.com/a/49177793
type: Comment
has text: it's not the config, it looks like rather a setup issue. So you have an ssh tunnel - port forwarding via putty, then you proxy one more time through squid? Would be good to understand your traffic flow of network packets...
score: 0
type: AnswerComment

http://stackoverflow.com/a/49231252
type: Answer
answers question: http://stackoverflow.com/q/49230302
has comment: http://stackoverflow.com/comment/134101951
has comment: http://stackoverflow.com/comment/85466206
has comment: http://stackoverflow.com/comment/85466526
has comment: http://stackoverflow.com/comment/85466607
downvote count: 0
upvote count: 1
score: 1
has body: What array array indexing rule applies to following code? That's how numpy's advanced indexing works. The shape of result array is related to shape of index array, the array's shape and the axis you're passing the index. Here are some examples that passes a 3D array as index to the first axis of arrays with different shapes. In [47]: a.shape Out[47]: (2, 5) In [48]: b = a[np.array([[[0],[1]],[[1],[1]]])] In [49]: b.shape Out[49]: (2, 2, 1, 5) In [50]: arr.shape Out[50]: (3, 3, 3) In [51]: b = arr[np.array([[[0],[1]],[[1],[1]]])] In [52]: b.shape Out[52]: (2, 2, 1, 3, 3) And here is what you get when you pass different arrays to different axises: In [61]: b = arr[[[0],[2]],[[1],[0]]] In [62]: b.shape Out[62]: (2, 1, 3) In [63]: arr.shape Out[63]: (3, 3, 3) In all of these indexings, Numpy will check multiple things, first off, it checks the type of the objects passed as index. Secondly, it compares the shapes of your index array with the shape of respective axis of your array. Thirdly, it checks if the result produces a valid Numpy array. Here are some other examples: In [64]: b = arr[[[[0],[2]]],[[1],[0]]] In [65]: b.shape Out[65]: (1, 2, 1, 3) In [66]: b Out[66]: array([[[[ 3, 4, 5]], [[18, 19, 20]]]]) In [67]: b = arr[[[[0],[2]]],[1],[0]] In [68]: b Out[68]: array([[[ 3], [21]]]) In [69]: b = arr[[[['a'],[2]]],[1],[0]] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-69-dba030ba9787&gt; in &lt;module&gt;() ----&gt; 1 b = arr[[[['a'],[2]]],[1],[0]] IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices In [70]: b = arr[[[[0],[2]]],[1],0] In [71]: b = arr[[[[0],[2]]],[5],0] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-71-0962012e570a&gt; in &lt;module&gt;() ----&gt; 1 b = arr[[[[0],[2]]],[5],0] IndexError: index…

http://stackoverflow.com/q/49200745
has answer: http://stackoverflow.com/a/49201399
has body: My laboratory is working with a software that generates a mess of data as output, so I’m trying to make things easier using Python. So far, I believe that the best approach is to generate lists and treat it as chunks of data, but that is not so easy: The first chunk of data is easy: the 3 columns are fixed and can be obtained simply with: chunk1 = my_data[:3] The 2nd chunk of data is not easy because it can have 2, 3 or 4 columns. I believe that the key here is that the 2nd chunk ends when we find a letter (something like 1 3 7 CCC). In this case I believe that it is possible to use the re module to parse the two, three or four columns and stop before the first letter, but I don’t know how to do it. I intend to “normalize” these columns by filling the vacant spots with zeros or “-”, so if I have the 2 columns case I’ll fill it to [x, y, 0, 0] and the 3 columns case with [x, y, z, 0]. The 3rd chunk is fixed (two, three or four letters and a number) like this: CCC 119.62 And the 4th chunk is the rest. Here is a representation of the messy output: The final result could be something like: ["s 91", "1.00", "OUT"] ["9", "3", "12", "7"] ["OCCC", "0.34"] ["f829", "27","f752","33"] So far, I’m stuck trying to figure out how to make the re module work like this: Any help is much appreciated, guys. Data sample s 27 1.00 STRE 30 16 OC 1.355049 f1291 50 s 28 -1.00 STRE 8 6 CC 1.494281 f1340 12 f1271 17 s 29 -1.00 STRE 14 15 NC 1.421282 f1358 49 s 30 1.00 STRE 14 15 NC 1.421282 f1337 10 f1290 33 s 31 1.00 STRE 8 6 CC 1.494281 f1171 15 f323 11 s 32 1.00 STRE 30 31 OC 1.419982 f1082 51 f1077 24 s 33 1.00 STRE 13 11 ClC 1.740581 f842 15 f323 19 s 34 -1.00 BEND 1 3 7 CCC 119.62 f1037 26 f485 10 s 35 -1.00 BEND 3 1 4 CCC 119.74 f1124 29 s 36 1.00 BEND 7 3 1 CCC 119.62 f733 25 f288 13 s 37 1.00 BEND 21 14 15 HNC 116.16 f1578 40 f1560 20 s 38 1.00 BEND 24 5 2 HCC 119.73 f1186 67 s 39 1.00 BEND 25 2 6 HCC 118.80 f1536 53 f1082 10 f1077 17 s 40 -1.00 BEND 24 5 2 HCC 119.73 f1508 44 f1171…
favorite count: 0
type: Question
tagged with: python-3.x
has title: Use re (regular expression) to parse only chunks of a line
has answer: http://stackoverflow.com/a/49201292
accepted answer: http://stackoverflow.com/a/49201292
tagged with: dataframe
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85406860
answer count: 3
has answer: http://stackoverflow.com/a/49201088
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49201088
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/85483150
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49239747
score: 0
has text: You should avoid reserved words such as `list` when naming variables.

http://stackoverflow.com/comment/85445839
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49211813
type: Comment
has text: I see, so decorator(arg1, arg2) becomes a function expression itself (I mean it's result), and the whole expression decorator(arg1, arg2) (my fun) becomes the final function call. Right?

http://stackoverflow.com/comment/85456449
has text: @abarnert Please look at my edits, this would probably make it more clear as to what I tried.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49226243

http://stackoverflow.com/q/49229234
has answer: http://stackoverflow.com/a/50720560
tagged with: python
has body: I have two tensors of shape (batch size,15,500) , (batch size,500,98) I want to Multiply them as matrix Multiplication for each batch size to obtain (batch size,15,98) How can I do that in tensorflow or keras backend can I use Batch dot
score: 2
answer count: 1
downvote count: 0
tagged with: keras
tagged with: tensorflow
favorite count: 0
has title: how to multiply by batches in keras backend or tf
type: Question
has comment: http://stackoverflow.com/comment/85487214
has comment: http://stackoverflow.com/comment/85464298
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/49187817
has title: read binary data using numpy
tagged with: numpy
type: AnsweredQuestion
score: 0
answer count: 1
has body: I have a binary file and I wonder how I can read it using numpy. The format of the data is 10 characters of string followed by 100 floats (stored using 4 characters each). I know the following snippet with struct module can solve this, but for large files the struct code is too time-consuming. f = open(file, 'rb') while True: tag = f.read(10) if tag== '': break b = [] for i in range(100): b.append(struct.unpack('f', f.read(4))) yield tag, b I'm a little confused with the numpy.fromfile, it seems this can meet my requirement.
type: Question
has answer: http://stackoverflow.com/a/49188871
accepted answer: http://stackoverflow.com/a/49188871
has comment: http://stackoverflow.com/comment/85380991
tagged with: python

http://stackoverflow.com/q/49207688
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49207772
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/21752989
tagged with: python
upvote count: 4
score: 4
type: Question
accepted answer: http://stackoverflow.com/a/49207772
has body: I want to take the log of each cell in a very sparse pandas DataFrame and must avoid the 0s. At first I was checking for 0s with a lambda function, then I thought it might be faster to replace the many 0s with NaNs. I got some inspiration from this closely related question, and tried using a "mask." Is there a better way? # first approach # 7.61 s ± 1.46 s per loop (mean ± std. dev. of 7 runs, 1 loop each) def get_log_1(df): return df.applymap( lambda x: math.log(x) if x != 0 else 0) # second approach (faster!) # 5.36 s ± 968 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) def get_log_2(df): return (df .replace(0, np.nan) .applymap(math.log) .replace(np.nan, 0)) # third apprach (even faster!!) # 4.76 s ± 941 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) def get_log_3(df): return (df .mask(df &lt;= 0) .applymap(math.log) .fillna(0))
has comment: http://stackoverflow.com/comment/85420453
has comment: http://stackoverflow.com/comment/85420871
tagged with: pandas
has title: pandas: Efficiently avoid 0s when taking log of cells in DataFrame

http://stackoverflow.com/q/49270937
has comment: http://stackoverflow.com/comment/85544817
has title: Python UnicodeEncodeError: 'ascii' codec can't encode characters
accepted answer: http://stackoverflow.com/a/49271130
favorite count: 0
type: Question
has body: There is a json data which contains some Chinese characters. { "font_size": "47", "sentences": [ "你好", "sample sentence1", "sample sentence2", "sample sentence3", "sample sentence4", "sample sentence5", "sample sentence6", "sample sentence7", "sample sentence8", "sample sentence9" ] } I create a Flask app and use it to receive above json data. I use below curl command to post data. curl -X POST \ http://0.0.0.0:5000/ \ -H 'Cache-Control: no-cache' \ -H 'Content-Type: application/json;charset=UTF-8' \ -H 'Postman-Token: af380f7a-42a8-cfbb-9177-74bb348ce5ed' \ -d '{ "font_size": "47", "sentences": [ "你好", "sample sentence1", "sample sentence2", "sample sentence3", "sample sentence4", "sample sentence5", "sample sentence6", "sample sentence7", "sample sentence8", "sample sentence9" ] }' After I receive json data from request.data, I convert it to json, in fact request.data is str. json_data = json.loads(request.data) Then I want to format a string with json_data. subtitles.format(**json_data) I got an error. UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) How to solve it? Thanks in advance. EDIT subtitles is read from file. subtitles_file = "{path}/templates/sorry/subtitles.ass".format(path=root_path) with open(subtitles_file, 'r') as file: subtitles = file.read() EDIT Python 2 or Python 3 I'm using python 2 and this error occurs. However Python 3 can automatically handle this. So enjoy Python 3.
has answer: http://stackoverflow.com/a/49271130
has comment: http://stackoverflow.com/comment/85545735
has comment: http://stackoverflow.com/comment/85545734
linked to: http://stackoverflow.com/q/9942594
has comment: http://stackoverflow.com/comment/85544959
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85545169
tagged with: python
has comment: http://stackoverflow.com/comment/85545767
has comment: http://stackoverflow.com/comment/85545903
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/85545387
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85544913
upvote count: 3

http://stackoverflow.com/a/49226126
type: Answer
upvote count: 2
has body: You can just need to add value="{{ ... }}" to your inputs: &lt;input type="name" value="{{ data[0] }}" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus&gt; &lt;input type="text" value="{{ data[1] }}" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus&gt; But it's recommended to name the values: name, text = cursor.fetchone() return render_template("edit_article.html", name=name, text=text) and then &lt;input type="name" value="{{ name }}" name="inputTitle" id="inputTitle" class="form-control" placeholder="Title" required autofocus&gt; &lt;input type="text" value="{{ text }}" name="inputBody" id="inputBody" class="form-control" placeholder="Body" required autofocus&gt; But I'd personally recommend WTForms module instead of rendering forms manually - it can for example help to validate your inputs properly.
score: 2
answers question: http://stackoverflow.com/q/49225564
downvote count: 0

http://stackoverflow.com/comment/85306059
comment on: http://stackoverflow.com/q/49150902
score: 0
type: QuestionComment
has text: ['data'][0] means the first element (index zero)
type: Comment

http://stackoverflow.com/q/49179274
has answer: http://stackoverflow.com/a/49179446
tagged with: win32com
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/85365501
score: 2
has title: win32com Powerpoint Cannot Handle Spaces In Name
answer count: 2
upvote count: 2
has body: A project of mine requires opening a variety of Microsoft Office documents as read-only through python. While the Excel and Word features of win32com have never had issues with documents containing spaces, win32com PowerPoint is not allowing it. from win32com.client import Dispatch Application = Dispatch("PowerPoint.Application") Application.Visible = True Test = Application.Presentations.Open("C:/Users/MYUSERNAME/Desktop/The Test.pptx", ReadOnly=True) Produces error: com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024894), None) My current solution for this is to rename the file, replacing spaces with underscores, then to rename it back after the file is opened. However, this requires the document to be opened untitled. from win32com.client import Dispatch import os Application = Dispatch("PowerPoint.Application") Application.Visible = True Filename = 'The Test.pptx' os.rename("C:/Users/MYUSERNAME/Desktop/" + Filename, "C:/Users/MYUSERNAME/Desktop/" + Filename.replace(" ","_")) Test = Application.Presentations.Open("C:/Users/MYUSERNAME/Desktop/" + Filename.replace(" ","_"), ReadOnly=True, Untitled=True) os.rename("C:/Users/MYUSERNAME/Desktop/" + Filename.replace(" ","_"), "C:/Users/MYUSERNAME/Desktop/" + Filename) Is there a better way to do this?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49179472
downvote count: 0
type: Question

http://stackoverflow.com/comment/85557164
comment on: http://stackoverflow.com/a/49276412
type: Comment
has text: I got it to work, the 5th answer [here](https://stackoverflow.com/questions/1346209/unknown-column-in-field-list-error-on-mysql-update-query) explained what I was doing wrong.
score: 0
type: AnswerComment

http://stackoverflow.com/a/49183265
type: AcceptedAnswer
has body: Have you tried using a reset_device() on the device you are using? It should make all tasks associated with the device able to be started again. edit: though it cleared the tasks, but it only aborts them.
has comment: http://stackoverflow.com/comment/85409752
score: 1
accepted answer of: http://stackoverflow.com/q/49154979
type: Answer
answers question: http://stackoverflow.com/q/49154979
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85527705
has text: @JonClements I am not looking for exact answer, but more looking for any alternative way to reindex the dataset to merge with anotherone. or if anyone know that `reindex(MeasureAgg.index, method='nearest')` can behave in this unexpected manner.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49261915

google-places-api
tags question: http://stackoverflow.com/q/49163417
tag name: google-places-api
type: Tag

http://stackoverflow.com/comment/85528458
comment on: http://stackoverflow.com/q/49262065
type: Comment
type: QuestionComment
score: 0
has text: Do you actually need the margin in the text, or do you just visually want a little whitespace so that the text isn't right next to the border? You could ignore the margin, and place the white text widget inside a white frame with some padding.

http://stackoverflow.com/comment/85433916
type: QuestionComment
comment on: http://stackoverflow.com/q/49214585
type: Comment
score: 0
has text: Thanks for pointing out - I've just edited.

monkeypatching
tag name: monkeypatching
tags question: http://stackoverflow.com/q/49198034
type: Tag

http://stackoverflow.com/a/49150233
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49149955
has body: You can also do it by merging a and b in a temp list, sorting it, and getting the previous elemenents of the elements originally in b. a = [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 59, 61, 63, 65, 68, 70, 72, 75] b = [5, 29, 78] temp = sorted(a + b) res = [temp[temp.index(x)-1] for x in b] print(res) # -&gt; [4, 28, 75] This does have some limitations, but you do not seem to consider them either.

http://stackoverflow.com/comment/85408731
type: Comment
comment on: http://stackoverflow.com/a/49201574
has text: Thank you for the help! Sorry if my question seemed so vague hahaha. I'm gonna go take a shot at implementing this and I'll let you know if I get it!
type: AnswerComment
score: 0

http://stackoverflow.com/q/49150613
answer count: 1
has body: The goal is to have a dashboard show a list of users in your area. The list of users works and it shows the Username. The only issue is I can't get the users images (ideally just have 1st image) to show. There are no error messages currently. Just nothing appearing. models.py class Images(models.Model): image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png') user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True, null=True) birth_date = models.DateField(null=True, blank=True) ... views.py class DashboardView(TemplateView): template_name = 've/cp/dashboard.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(DashboardView, self).dispatch(*args, **kwargs) def get(self, request, pk=None): users = User.objects.exclude(id=request.user.id) try: favorite = Favorite.objects.get(current_user=request.user) favorites = favorite.users.all() except Favorite.DoesNotExist: favorites = None args = { # 'users': users, 'favorites':favorites, 'images': images, } return render(request, self.template_name, args) dashboard.html People near you {% for user in users %} {{ user.username }} {{ user.profile.bio }} {{ user.images.image.url }} ''' Or this.. However it does work on view_profile page where there is a pk. Seem like it's not finding images for users, as this results in a "No images message on localhost ''' {% if images %} {% for img in images %} {% endfor %} {% else %} No images {% endif %} {% if not user in favorites %} Add Favorite {% endif %} {% endfor %}
tagged with: django
type: Question
score: 0
tagged with: foreign-keys
tagged with: python
has answer: http://stackoverflow.com/a/49150707
has title: Django Foreign Key class not showing
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49150707

http://stackoverflow.com/comment/85304045
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49147413
has text: Try to use a pygame.time.Clock and its [`get_fps`](http://www.pygame.org/docs/ref/time.html#pygame.time.Clock.get_fps) method.

http://stackoverflow.com/q/49210971
has answer: http://stackoverflow.com/a/49212095
downvote count: 0
linked to: http://stackoverflow.com/q/1602934
score: 7
upvote count: 7
answer count: 1
has title: Equivalent of php isset in python
favorite count: 0
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: isset
has body: Here is my python code: if onerow[0]['result'] is None or not result['GetOdds'][0]['result']is None: When result was empty, it returns this error: if onerow[0]['result'] is None or not result['GetOdds'][0]['result']is None: KeyError: 0 I want a something like php isset in python to check a dictionary item Is there any equivalent function or class in python?
has comment: http://stackoverflow.com/comment/85427457

http://stackoverflow.com/q/49151161
tagged with: if-statement
tagged with: python
has comment: http://stackoverflow.com/comment/85352814
has answer: http://stackoverflow.com/a/49151295
score: 0
tagged with: list
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49151283
has title: Use next item in the list within a condition in a for loop
has body: I have the following loop which is parsing the outputs of a difflib comparison of 2 configuration files and, so far showing me the differences in file 2 (indicated with +) and the heading in the file that the difference falls under e.g. [server] code: #!/usr/bin/env python import difflib from difflib import Differ conf = open('C:/Users/fitzs/Documents/Scripts/example_ISAM_conf_file.txt', 'r') upconf = open('C:/Users/fitzs/Documents/Scripts/Updated_ISAM_conf_file.txt', 'r') d = difflib.Differ() diff = list(d.compare(conf.readlines(), upconf.readlines()))# creates a 'generator' list of diffs delta = ''.join(diff).strip('# ') #converts the list to string for x in diff: x = str(x).strip() if x.startswith('+'): print(x) elif x.startswith('['): print(x) Example Output:- The above code is giving me the following example output so far. [server] + # web-host-name = www.myhost.com + https-port = 1080 + network-interface = 0.0.0.0 [process-root-filter] [validate-headers] [interfaces] [header-names] [oauth] [tfim-cluster:oauth-cluster] [session] + preserve-inactivity-timeout = 330 [session-http-headers] what I'm trying to do is only print a heading (e.g [server] ) if the next element in the list begins with + thereby excluding the headers that have no deltas under them' on other words for the line with the header to print 2 conditions must be met: 1. the line must begin with [ 2. the next line must begin with + for example: [server] + # web-host-name = www.myhost.com + https-port = 1080 + network-interface = 0.0.0.0 [session] + preserve-inactivity-timeout = 330 To achieve this I've tried changing the above for loop to the following: for x in range(0, len(diff)): stanza = diff[x+1] x = str(x).strip() if x.startswith('+'): print(x) elif x.startswith('[') and stanza.startswith('+'): print(x) However, this results in the following error: Traceback (most recent call last): File "C:/Users/fitzs/PycharmProjects/Pydiffer/Pydiffer.py", line 35, in &lt;module&gt; stanza = diff[x+1] Index…
type: Question
has comment: http://stackoverflow.com/comment/85306583

http://stackoverflow.com/a/49133428
type: Answer
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49126777
has body: You can look at the reference for firestore python client. It explains what result an operation returns, what errors it may raise etc. For example, below is a snippet from the reference for Documents- create(document_data) Create the current document in the Firestore database. Parameters: document_data (dict) – Property names and values to use for creating a document. Returns: The write result corresponding to the committed document. A write result contains an update_time field. Return type: google.cloud.firestore_v1beta1.types.WriteResult Raises: Conflict – If the document already exists. You can have try except blocks to capture and handle errors in relevant cases. And here is an SO post explaining what is a python equivalent of swift completion blocks.
score: 1
answers question: http://stackoverflow.com/q/49126777

matplotlib
tags question: http://stackoverflow.com/q/49206951
tags question: http://stackoverflow.com/q/49156484
tags question: http://stackoverflow.com/q/49271204
tags question: http://stackoverflow.com/q/49261229
tags question: http://stackoverflow.com/q/49187768
tags question: http://stackoverflow.com/q/49143513
tags question: http://stackoverflow.com/q/49158130
tags question: http://stackoverflow.com/q/49122352
tags question: http://stackoverflow.com/q/49269080
tags question: http://stackoverflow.com/q/49142448
tags question: http://stackoverflow.com/q/49149312
tags question: http://stackoverflow.com/q/49201174
tags question: http://stackoverflow.com/q/49216299
tags question: http://stackoverflow.com/q/49141479
tags question: http://stackoverflow.com/q/49218349
tags question: http://stackoverflow.com/q/49204861
tags question: http://stackoverflow.com/q/49267011
tags question: http://stackoverflow.com/q/49250925
tags question: http://stackoverflow.com/q/49199987
tags question: http://stackoverflow.com/q/49223702
tags question: http://stackoverflow.com/q/49155110
tags question: http://stackoverflow.com/q/49162494
tags question: http://stackoverflow.com/q/49239075
tags question: http://stackoverflow.com/q/49179181
tags question: http://stackoverflow.com/q/49210025
tags question: http://stackoverflow.com/q/49141083
tags question: http://stackoverflow.com/q/49268558
tags question: http://stackoverflow.com/q/49138888
tags question: http://stackoverflow.com/q/49237522
tags question: http://stackoverflow.com/q/49185428
tags question: http://stackoverflow.com/q/49203408
tags question: http://stackoverflow.com/q/49239647
tags question: http://stackoverflow.com/q/49218457
tags question: http://stackoverflow.com/q/49188811
tags question: http://stackoverflow.com/q/49264559
tags question: http://stackoverflow.com/q/49174302
tags question: http://stackoverflow.com/q/49178622
tags question: http://stackoverflow.com/q/49266592
tags question: http://stackoverflow.com/q/49183536
tags question: http://stackoverflow.com/q/49208444
tags question: http://stackoverflow.com/q/49259569
tags question: http://stackoverflow.com/q/49211334
tags question: http://stackoverflow.com/q/49183656
tags question: http://stackoverflow.com/q/49277182
tags question: http://stackoverflow.com/q/49130860
tags question: http://stackoverflow.com/q/49182468
tags question: http://stackoverflow.com/q/49129129
tags question: http://stackoverflow.com/q/49256820
tags question: http://stackoverflow.com/q/49153509
tags question: http://stackoverflow.com/q/49237002
tags question: http://stackoverflow.com/q/49267085
tags question: http://stackoverflow.com/q/49165589
tags question: http://stackoverflow.com/q/49135269
tags question: http://stackoverflow.com/q/49155654
tags question: http://stackoverflow.com/q/49161570
tags question: http://stackoverflow.com/q/49233855
tags question: http://stackoverflow.com/q/49238593
tags question: http://stackoverflow.com/q/49187131
tags question: http://stackoverflow.com/q/49255753
tags question: http://stackoverflow.com/q/49230967
tag name: matplotlib
tags question: http://stackoverflow.com/q/49174126
tags question: http://stackoverflow.com/q/49215929
tags question: http://stackoverflow.com/q/49134886
tags question: http://stackoverflow.com/q/49180822
tags question: http://stackoverflow.com/q/49241476
tags question: http://stackoverflow.com/q/49197997
tags question: http://stackoverflow.com/q/49135854
tags question: http://stackoverflow.com/q/49173468
tags question: http://stackoverflow.com/q/49224287
tags question: http://stackoverflow.com/q/49218366
tags question: http://stackoverflow.com/q/49215675
tags question: http://stackoverflow.com/q/49213686
tags question: http://stackoverflow.com/q/49187042
tags question: http://stackoverflow.com/q/49136668
tags question: http://stackoverflow.com/q/49147612
tags question: http://stackoverflow.com/q/49265951
tags question: http://stackoverflow.com/q/49203266
tags question: http://stackoverflow.com/q/49178618
tags question: http://stackoverflow.com/q/49165233

http://stackoverflow.com/comment/91481620
type: QuestionComment
type: Comment
has text: my suggestion is to include ALL of your code...it will prevent us from guessing what is there and what is not.
score: 0
comment on: http://stackoverflow.com/q/49182189

http://stackoverflow.com/comment/85444337
has text: what number do you want for say 1k.. 1000?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49220237

http://stackoverflow.com/q/49239751
has comment: http://stackoverflow.com/comment/85508495
has comment: http://stackoverflow.com/comment/85483467
tagged with: python
has comment: http://stackoverflow.com/comment/85483198
has comment: http://stackoverflow.com/comment/85483517
has body: (env) user@name:~/$ pip install -r requirements.txt Collecting Shapely==1.5.13 (from -r requirements.txt (line 1)) Using cached Shapely-1.5.13.tar.gz Complete output from command python setup.py egg_info: Failed `CDLL(libgeos_c.so.1)` Failed `CDLL(libgeos_c.so)` Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/tmp/pip-build-p0Fy8v/Shapely/setup.py", line 38, in &lt;module&gt; from shapely._buildcfg import geos_version_string, geos_version, \ File "/tmp/pip-build-p0Fy8v/Shapely/shapely/_buildcfg.py", line 167, in &lt;module&gt; fallbacks=['libgeos_c.so.1', 'libgeos_c.so']) File "/tmp/pip-build-p0Fy8v/Shapely/shapely/_buildcfg.py", line 161, in load_dll libname, fallbacks or [])) OSError: Could not find library geos_c or load any of its variants ['libgeos_c.so.1', 'libgeos_c.so'] ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-p0Fy8v/Shapely/ requirements.txt content : Shapely==1.5.13 Flask==0.10.1 matplotlib==1.5.1 scipy==0.19.0 plumbum==1.6.2 numpy==1.12.1 ipython==5.5 Pillow==4.2.1 opencv-python==3.2.0.6 trying to run pip install -r requirements.txt but i keep on getting that error described above, i just installed python and pip and basically everything else after my format on linux 16.04 so not sure what's going wrong. Edit: I removed Shapely==1.5.13 from the requirements.txt to test if it;s the issue and i got that error again Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-oVKNjq/matplotlib/
linked to: http://stackoverflow.com/q/19742406
answer count: 0
type: UnansweredQuestion
tagged with: pip
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/85483170
has title: Why can't i install the requirements.txt content?
type: Question
score: 0

http://stackoverflow.com/a/49121509
has comment: http://stackoverflow.com/comment/85248660
type: Answer
has body: You are facing the syntax error because you are attempting to add an integer to a string. This is not possible. To do what you want you need to convert randomNumber in each print statement. import random randomNumber = random.randrange(0,50) print("I’m thinking of a number in the range 0-50. You have five tries to guess it.") guessed = False while guessed == False: userInput = int(input("Guess 1?")) if userInput == randomNumber: guessed = True print("You are right! I was thinking of" + str(randomNumber) + "!") elif userInput&gt;randomNumber: print(str(randomNumber) + "is too high.") elif userInput &lt; randomNumber: print(str(randomNumber) + "is too low.") elif userInput &gt; 5: print("Your guess is incorrect. The right answer is" + randomNumber) print("End of program")
answers question: http://stackoverflow.com/q/49121437
downvote count: 0
upvote count: 1
score: 1

buffer
tags question: http://stackoverflow.com/q/49181147
type: Tag
tags question: http://stackoverflow.com/q/49221986
tag name: buffer

http://stackoverflow.com/q/49276118
has comment: http://stackoverflow.com/comment/85978322
downvote count: 0
linked to: http://stackoverflow.com/q/43877692
tagged with: pandas
type: UnansweredQuestion
tagged with: machine-learning
tagged with: scikit-learn
linked to: http://stackoverflow.com/q/34749806
has comment: http://stackoverflow.com/comment/86059076
favorite count: 0
tagged with: aws-lambda
has answer: http://stackoverflow.com/a/53621640
has answer: http://stackoverflow.com/a/49562109
has answer: http://stackoverflow.com/a/49584250
answer count: 5
has body: I am a newbie on the AWS &amp; Python and trying to implement a simple ML recommendation system using AWS Lambda function for self-learning. I am stuck on the packaging the combination of sklearn, numpy and pandas. If combined any two lib means (Pandas and Numpy) or (Numpy and Skype) is working fine and deploy perfectly. Because I am using ML system then i need sklearn (scipy and pandas and numpy) which cannot work and getting this error on aws lambda test. What I have done so far : my deployment package from within a python3.6 virtualenv, rather than directly from the host machine. (have python3.6, virtualenv and awscli already installed/configured, and that your lambda function code is in the ~/lambda_code directory): cd ~ (We'll build the virtualenv in the home directory) virtualenv venv --python=python3.6 (Create the virtual environment) source venv/bin/activate (Activate the virtual environment) pip install sklearn, pandas, numpy cp -r ~/venv/lib/python3.6/site-packages/* ~/lambda_code (Copy all installed packages into root level of lambda_code directory. This will include a few unnecessary files, but you can remove those yourself if needed) cd ~/lambda_code zip -r9 ~/package.zip . (Zip up the lambda package) aws lambda update-function-code --function-name my_lambda_function --zip-file fileb://~/package.zip (Upload to AWS) after that getting this error: **"errorMessage": "Unable to import module 'index'"** and START RequestId: 0e9be841-2816-11e8-a8ab-636c0eb502bf Version: $LATEST Unable to import module 'index': **Missing required dependencies ['numpy']** END RequestId: 0e9be841-2816-11e8-a8ab-636c0eb502bf REPORT RequestId: 0e9be841-2816-11e8-a8ab-636c0eb502bf Duration: 0.90 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 33 MB I have tried this on EC2 instance as well but did not a success.I did the google and read multiple blogs and solution but not worked. Please help me out on this.
has answer: http://stackoverflow.com/a/49497946
tagged with: python
has answer: http://stackoverflow.com/a/55956186
has title: Python Deployment Package with SKLEARN, PANDAS and NUMPY issue?
type: Question
upvote count: 9
score: 9

http://stackoverflow.com/comment/90188085
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49206479
type: Comment
has text: What if someone needs to use USB camera did you found the solution to that @yeyou ?

http://stackoverflow.com/q/49165201
has comment: http://stackoverflow.com/comment/85335886
has comment: http://stackoverflow.com/comment/85335777
accepted answer: http://stackoverflow.com/a/49169395
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49169395
has comment: http://stackoverflow.com/comment/85336502
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/85336604
has title: Django Login Form Input Fields not showing up
tagged with: django-forms
favorite count: 0
type: Question
has body: working on a Django Web project for a class. Created an own template for the login page, that looks like this {% extends 'thirdauth/base.html' %} {% block content %} Login {{form.as_p}} {% csrf_token %} -- OR -- Login with GitHub {% endblock %} The only problem that I face is that the input fields for user and password + labels are not showing up when the sites initially loads. When I click on the Login button, the fields appear and I can enter everything and it works fine... Here is the urls.py from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth import views as auth_views from . import views urlpatterns = [ url(r'^login/$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, name='logout'), url(r'^auth/', include('social_django.urls', namespace='social')), url(r'^admin/', admin.site.urls), url(r'^accounts/login/$', views.authentication, name='authentication'), ] I'm thankful for help, I think it is just a small stupid mistake from me, but I'm not able to find it, most help on the internet focuses on self defined forms. EDIT views.py: from django.shortcuts import render_to_response from django.template.context import RequestContext from django.shortcuts import render, get_object_or_404 def authentication(request): return render(request, 'registration/login.html') EDIT 2 second views.py: from django.utils import timezone from .models import * from django.shortcuts import render, get_object_or_404 from django.shortcuts import redirect from django.contrib.auth.decorators import login_required import wikipediaapi def home(request): return render(request, 'worldmap/home.html', {'worldmap': home}) def denverText (request): wiki_wiki = wikipediaapi.Wikipedia('en') page_py = wiki_wiki.page('Denver') return page_py.summary[0:60]; @login_required def plannerGetStarted (request): return render(request, 'worldmap/planner.html') SOLVED: added this code to my views.py: def authentication(request): if request.method…
downvote count: 0
tagged with: django
tagged with: python

http://stackoverflow.com/a/49235253
type: Answer
has comment: http://stackoverflow.com/comment/85474066
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49234367
has body: Please, try something like the example below. First, install SWIG (I am using Debian): sudo apt update sudo apt install swig Second, compile and install the GEOS library: cd /opt wget http://download.osgeo.org/geos/geos-3.3.3.tar.bz2 tar xvjf geos-3.3.3.tar.bz2 cd geos-3.3.3 mkdir build ./configure --prefix=/opt/geos-3.3.3/build --enable-python make &amp;&amp; sudo make install ./build/bin/geos-config --version Finally, add GEOS in your PATH: # add lines below at the end of /etc/bash.bashrc file. export LD_LIBRARY_PATH="/opt/geos-3.3.3/build/lib:$LD_LIBRARY_PATH" export PATH="/opt/geos-3.3.3/build/bin:$PATH" Now, open a new terminal console to use.
score: 1

http://stackoverflow.com/q/49218483
has comment: http://stackoverflow.com/comment/85445048
has answer: http://stackoverflow.com/a/49446332
tagged with: python
has comment: http://stackoverflow.com/comment/85440990
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
has body: This code cause a blue screen on windows on my computer : import matplotlib.pyplot as plt plt.plot(range(10),range(10)) # This is the line that cause the crash WhoCrashed tells me this : This was probably caused by the following module: nt_wrong_symbols.sys (nt_wrong_symbols) Bugcheck code: 0x124 (0x0, 0xFFFFB60A6AF4D028, 0xB2000000, 0x70005) Error: WHEA_UNCORRECTABLE_ERROR Here is a link to the full Minidump What I have done: Fully tested the CPU with a CPU-Z stress test Fully tested the RAM with memtest86+ Tested the GPU with Assassin's creed origin in full ultra Tested the same code on Ubuntu (double boot) : works fine This lead me to believe this is a windows specific error. Hardware configuration : i9-7940X GTX 1080 Ti 64 Gb RAM @2400Mhz (CPU frequency) Software : Windows 10, fresh install (I've always had this issue) Python 2.7 installed through Anaconda ( I tested the code with Jupyter and IPython with the same results) Windows and graphic drivers up to date This is the only thing that causes blue screen on my computer, and I'm out of ideas on how to solve this, any advice would be greatly appreciated. NOTE : I asked this question here as it appears to be matplotlib related, I hope this is the right place EDIT : Correction : it does not happens all the time, but more like 95% of the time.
has comment: http://stackoverflow.com/comment/85442773
has title: plt.plot() cause blue screen on windows
score: 1
tagged with: windows
tagged with: matplotlib
downvote count: 0
upvote count: 1
possible better answer: http://stackoverflow.com/a/58867710
has comment: http://stackoverflow.com/comment/85442355
favorite count: 0
tagged with: bsod
type: Question
has answer: http://stackoverflow.com/a/58867710
accepted answer: http://stackoverflow.com/a/49446332
has comment: http://stackoverflow.com/comment/85440882

http://stackoverflow.com/a/49272381
type: Answer
has body: Use selenium. It has functions to find elements by x path, css selector. It can also click as instructed. The main benefit of using it: it waits till the page loads. Clicking a button automatically in a web browser with python
has comment: http://stackoverflow.com/comment/85548781
score: 0
answers question: http://stackoverflow.com/q/49272220
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49272220

http://stackoverflow.com/comment/85422535
score: 0
has text: okay so in 'dict(zp1)[x] for x in rawdata' would the the dictionary get created first? Then if has been created cant we use x in rawdata to get the items from the dictionary. I mean how can it be empty.. {} I went through the iterators and came to know how the zip objects gets exhausted after an iteration. But that doesn't explain how we cant use the dictionary that is created in the first instance.. sorry to keep bothering, i know it duplicate. But this query hasn't been answered before. Please advice.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49208794

http://stackoverflow.com/comment/85486466
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49241164
score: 0
has text: It's not referenced until `handle_keystroke` is called. Python is very dynamic.

http://stackoverflow.com/q/49263996
accepted answer: http://stackoverflow.com/a/49264750
tagged with: pandas
has body: I have a pandas DF of (at this point) about 4000 rows, which I have put into the order I need.. I need to divide the DF into an arbitrary 10 bins by rowcount. So I want to append the bin number to the row for future aggregate computations by bin..about 400 each, given that the last bin will not be filled out. I don't want to do this in one operation at the moment, I just need to get the bin numbers appended to the rows. That way I can do the group by aggregations in another step. I have tied both pd.qcut and pd.cut but don't seem to be having any luck. ccs_category sex race marital_status presence_of_child payer_type no_of_persons occupation education wealth_rate donate_charity zip age 48_prediction count cum_count cum_accurate cum_percent 263 218 M U S N PK 999 99 0 99 U 60657.0 0 0.000538 1 1 0 0.0 2452 250 M W U U NK 0 99 0 99 U 8730.0 29 0.000404 1 2 0 0.0 2814 127 F W U N MK 2 8 2 9 Y 53051.0 75 0.000369 1 3 0 0.0 So I'd like the last column to be bin_nu with sequential Labels of 1-10 (0-9) is fine. E.G the 1st 400 label =1 the second 400 label =2 etc.. results.3['bin_nu']=pd.cut(results3,10,labels=False) I have tried with retbins=True with no result either gives me: TypeError: '&lt;=' not supported between instances of 'str' and 'int' I've looked around a bit but everything seems to be mostly binning by value (and time series) rather than arbitrary item counts? Here is a conversion of the 1st ten rows of the DF to a dict: {'48_prediction': {263: 0.0005377883207984269, 578: 0.00030468139448203146, 1168: 0.0003036215784959495, 2021: 0.0003635243338067085, 2452: 0.0004036910831928253, 2518: 0.00029300281312316656, 2814: 0.00036939769051969046, 3687: 0.0003046905330847949, 3963: 0.00029347193776629865, 7132: 0.00035702803870663047}, 'age': {263: 0, 578: 68, 1168: 1, 2021: 42, 2452: 29, 2518: 92, 2814: 75, 3687: 40, 3963: 51, 7132: 34}, 'ccs_category': {263: '218', 578: '250', 1168: '166', 2021: '90', 2452: '250', 2518: '3', 2814: '127', 3687: '58', 3963: '160', 71…
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85531716
has comment: http://stackoverflow.com/comment/85532145
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49264750
score: 1
has title: Pandas Dataframe create arbitrary Bins by row count
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/49242856
has title: Matching 'Date' dataframes in Pandas to enable joins/merging
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: date
has body: I have two csv files with pandas dataframes with a 'Date' column, which is my desired target to join the two tables (my goal is to join my two csvs by dates and merge matching dataframes by summing them). The issue is that despite sharing the same month-year format, my first csv abbreviated the years, whereas my desired output would be mm-yyyy (for example, Aug-2012 as opposed to Aug-12). csv1: 0 Oct-12 1154293 1 Nov-12 885773 2 Dec-12 -448704 3 Jan-13 563679 4 Feb-13 555394 5 Mar-13 631974 6 Apr-13 957395 7 May-13 1104047 8 Jun-13 693464 ... has 41 rows; i.e. 41 months worth of data between Oct. 12 - Feb. 16 csv2: 0 Jan-2009 943690 1 Feb-2009 1062565 2 Mar-2009 210079 3 Apr-2009 -735286 4 May-2009 842933 5 Jun-2009 358691 6 Jul-2009 914953 7 Aug-2009 723427 8 Sep-2009 -837468 ... has 86 rows; i.e. 41 months worth of data between Jan. 2009 - Feb. 2016 I tried initially to do something akin to a 'find and replace' function as one would in Excel. I tried : findlist = ['12','13','14','15','16'] replacelist = ['2012','2013','2014','2015','2016'] def findReplace(find, replace): s = csv1_df.read() s = s.replace(Date, replacement) csv1_dfc.write(s) for item, replacement in zip(findlist, replacelist): s = s.replace(Date, replacement) But I am getting a NameError: name 's' is not defined
tagged with: type-conversion
has answer: http://stackoverflow.com/a/49258320
tagged with: pandas
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85489412
has comment: http://stackoverflow.com/comment/85489931
upvote count: 1
answer count: 1
downvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49258320

http://stackoverflow.com/comment/85462632
score: 0
comment on: http://stackoverflow.com/q/49228474
type: Comment
type: QuestionComment
has text: @DebanjanB I read that thread, but I'm still not sure how to reattach my elements to DOM. I'm a python novice. Can you help?

http://stackoverflow.com/comment/85265678
score: 0
has text: I was suppose to use it in a different way, but that dint seem to work, so changed it entirely and came to this
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49130520

http://stackoverflow.com/comment/85266634
has text: Can you post the plots?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49130327
score: 0

http://stackoverflow.com/comment/85450216
has text: What is a sequence here? `5, 4, 3`? `5, 4`? `5`? And what would be the output for `['5', '4', '3', '2'], ['1', '4', '3', '2'], ['5', '4', '3', '1']`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49223147

http://stackoverflow.com/q/49241799
tagged with: jupyter-notebook
has title: Take a table from a website using pd.read_html and turn into a pandas Dataframe
score: 0
has comment: http://stackoverflow.com/comment/85487402
has comment: http://stackoverflow.com/comment/85487282
tagged with: pandas
answer count: 0
upvote count: 1
has body: I am trying to take a table using pandas pd.read_html function from the website https://www.statbunker.com/competitions/FantasyFootballPlayersStats?comp_id=556 I have got as far as making the table into a list but when I try to change it to a Dataframe only the 5 outputs from the top line of the 620x20 table appears in the output.The code I have used is BPL1617 = pd.read_html("https://www.statbunker.com/competitions/FantasyFootballPlayersStats?comp_id=556") Then to convert to a dataframe I usedBPL20162017 = pd.DataFrame(BPL1617) but the output is wrong. I hope to later add new tables from this website and merge them. Any help would be greatly appreciated as I don't know where I am going wrong!
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html
tagged with: python

http://stackoverflow.com/comment/87551242
comment on: http://stackoverflow.com/a/49271337
has text: @Vicrobot Because otherwise, each word would print on its own separate line, with newlines between them. This way, they all print on the same line, with spaces between them (and then we print a single newline at the end).
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49187778
answers question: http://stackoverflow.com/q/49180941
downvote count: 0
upvote count: 1
score: 1
has body: Before you start coding, you have to decide whuch features are useful for this task: The easiest way out is trying the approach in @Jordan's answer and converting the entire image to a feature. This could work because the classes are simple patterns, and is interesting if you are using KNN. If this does not work well, the following steps show how you should approach the problem. The number of black pixels might not help, because the size of the star and pentagon can vary. The number of sharp corners is very likely to be useful. The number of straight line segments might be useful, but this could be unreliable because the shapes are hand-drawn. Supposing you want to have a go at using the number of corners as a feature, you can refer to this page to learn how to extract corners.
type: Answer

http://stackoverflow.com/q/49170868
has title: Quick Controls universal style in PyQt designer
answer count: 0
tagged with: pyqt
tagged with: stylesheet
has comment: http://stackoverflow.com/comment/85361843
type: Question
has body: I am completely new to PyQt. I want to ask, how I change the stylesheet of my GUI in PyQt Designer. I want to to make a nice looking GUI with Universal Microsoft style. This is the style I want to use: https://doc.qt.io/qt-5.10/qtquickcontrols2-universal.html. I am using Python 3.6 and PyQt5 (5.10).
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85355569
tagged with: python
has comment: http://stackoverflow.com/comment/85361995
score: 0
tagged with: qt-designer

http://stackoverflow.com/q/49249731
has comment: http://stackoverflow.com/comment/85503143
has title: How to call lambda inside the __init__?
has comment: http://stackoverflow.com/comment/85502997
has answer: http://stackoverflow.com/a/49250081
has comment: http://stackoverflow.com/comment/85503116
has comment: http://stackoverflow.com/comment/85502836
downvote count: 1
has comment: http://stackoverflow.com/comment/85503483
score: -1
has comment: http://stackoverflow.com/comment/85504046
favorite count: 0
has comment: http://stackoverflow.com/comment/85503298
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85503152
tagged with: tkinter
type: Question
has comment: http://stackoverflow.com/comment/85504559
upvote count: 0
answer count: 2
tagged with: python
type: UnansweredQuestion
tagged with: lambda
has comment: http://stackoverflow.com/comment/85502896
has comment: http://stackoverflow.com/comment/85503520
has answer: http://stackoverflow.com/a/49250021
has body: My big application involves few codes like this: def __init__(self,master): self.destroy= lambda num=num : self.destroywidgets(num) def destroywidgets(self,num): if num == 1: for widget in self.frame1.winfo_children(): widget.destroy() elif num == 2: for widget in self.frame2.winfo_children(): widget.destroy() elif num == 3: for widget in self.frame3.winfo_children(): widget.destroy() def func1(self): self.destroy(1) This is the small picture of my code. But when I run this code, I am getting below error: self.destroy= lambda num=num : self.destroywidgets(num) NameError: name 'num' is not defined I am really confused as this code was running successfully the previous day. This is throwing such error after restart today. Why is this behaviour? Please note that, I tried altering this lambda in multiple ways and referred to many SOF answers, still couldn't resolve it. Also, please tell me if this could be done using partial(functools). To make it understand better, below is the smaller snippet I made: num = "" def paint(num): if num == 1: return "1st paint - green" elif num == 2: return "1st paint - blue" elif num == 3: return "1st paint - red" else: return "no more options" op = lambda num = num : paint(num) print(op(2)) print(op(3)) print(op(4)) And I get the perfect output as below: 1st paint - blue 1st paint - red no more options But why isn't this working in above code?
has comment: http://stackoverflow.com/comment/85503245
has comment: http://stackoverflow.com/comment/85503117
has comment: http://stackoverflow.com/comment/85503363

http://stackoverflow.com/q/49257738
has answer: http://stackoverflow.com/a/49258139
type: UnansweredQuestion
upvote count: 0
answer count: 1
tagged with: keras
downvote count: 1
tagged with: tensorflow
favorite count: 0
has body: I'm appeding single color channel image to an array image = cv2.cvtColor(cv2.imread(path), cv2.COLOR_BGR2HSV) tmp = image[:,:,1].reshape(160, 320, 1) images.append(tmp) But, during start of the Sequential model, I'm getting ValueError: Input 0 is incompatible with layer cropping2d_1: expected ndim=4, found ndim=3 How does Cropping2D work for single color channel image?? Model starts like: model = Sequential() model.add(Lambda(lambda x: x/255.0 - 0.5, input_shape=(160, 320, 1))) model.add(Cropping2D(cropping=((50, 20), (0, 0))))
type: Question
tagged with: python-3.x
tagged with: opencv
tagged with: python
score: -1
has title: “ValueError: Input 0 is incompatible with layer cropping2d_1: expected ndim=4, found ndim=3”

http://stackoverflow.com/q/49190592
has body: sh route has 8000-10000 routes when I am trying to fetch it using channel.recv(99999) I am unable to get complete output, please suggest any way to read complete output.
answer count: 1
tagged with: python
has title: channel.recv() maximum return size
downvote count: 1
tagged with: paramiko
favorite count: 0
has answer: http://stackoverflow.com/a/49192701
has comment: http://stackoverflow.com/comment/85386227
score: -1
type: Question
has comment: http://stackoverflow.com/comment/85386199
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85528371
has text: That looks to solve most of the problem. There is one issue thought. At the start of the inserted text if I select before the first letter and hit the return key then the top line loses its margin.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49262387

http://stackoverflow.com/q/49202497
tagged with: tuples
has comment: http://stackoverflow.com/comment/85412350
tagged with: math
answer count: 1
has title: Comparing items of a tuple within a list of tuples
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 2
has body: I have designed a program to calculate some maximum tuples from a list, however I am stuck at the point where I have to compare the maximum item[1] from a tuple and compare it to another tuple item[1]. This is the list of tuples: fff = [] anslist = [(2, [1]), (3, [7]), (4, [2]), (5, [5]), (6, [8]), (7, [16]), (8, [3]), (9, [19]), (10, [6]), (11, [14]), (12, [9]), (13, [9]), (14, [17]), (15, [17]), (16, [4]), (17, [12]), (18, [20]), (19, [20]), (20, [7])] This is the code I have: print(max(anslist, key=lambda x: x[1])) fff.append(max(anslist, key=lambda x: x[1])) anslist.remove(max(anslist, key=lambda x: x[1])) while (max(fff[1], key=lambda x: x[1])) == (max(anslist[1], key=lambda x: x[1])): print(max(anslist, key=lambda x: x[1])) anslist.remove(max(anslist, key=lambda x: x[1])) I expect my program to print (18, [20]) and (19, [20]), and because the list of tuples always changes in response to the users input I needed some kind of loop which needed to go through all tuples until the second item of the tuple is not the largest anymore. This is the error I get : while (max(fff[1], key=lambda x: x[1])) == (max(anslist[1], key=lambda x: x[1])): IndexError: list index out of range
has comment: http://stackoverflow.com/comment/85410889
upvote count: 1
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49206755
tagged with: lambda
tagged with: list-comprehension

http://stackoverflow.com/comment/85829865
type: AnswerComment
has text: if I replaced predictions with a test case such as: `predictions = [0]*60 + [1]* 60` the program is returning `[0.0, 1.3931972789115648, 'not-music'] ` alone. it is not outputting the second half of the answers which should be `[1.39xxx , 2.78639455782, 'music]`
type: Comment
comment on: http://stackoverflow.com/a/49182450
score: 0

http://stackoverflow.com/q/49207552
tagged with: python
has comment: http://stackoverflow.com/comment/85420492
linked to: http://stackoverflow.com/q/2365411
linked to: http://stackoverflow.com/q/4299675
linked to: http://stackoverflow.com/q/2087370
has comment: http://stackoverflow.com/comment/85419916
has comment: http://stackoverflow.com/comment/85420287
has comment: http://stackoverflow.com/comment/85420387
has title: Decoding and Encoding in Python
has comment: http://stackoverflow.com/comment/85420495
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85421278
has comment: http://stackoverflow.com/comment/85420220
has comment: http://stackoverflow.com/comment/85420005
accepted answer: http://stackoverflow.com/a/49207917
has comment: http://stackoverflow.com/comment/85420070
answer count: 1
has comment: http://stackoverflow.com/comment/85420021
upvote count: 1
has answer: http://stackoverflow.com/a/49207917
downvote count: 1
has comment: http://stackoverflow.com/comment/85420059
has comment: http://stackoverflow.com/comment/85420036
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85420032
has comment: http://stackoverflow.com/comment/85420164
has comment: http://stackoverflow.com/comment/85419887
has comment: http://stackoverflow.com/comment/85420481
has body: I have some text that I am trying to decode and encode in Python import html.parser original_tweet = "I luv my &amp;lt;3 iphone &amp;amp; you’re awsm apple.DisplayIsAwesome, sooo happppppy http://www.apple.com" tweet = original_tweet.decode("utf8").encode('ascii', 'ignore') I have entered the original tweet on one line in Spyder (Python 3.6) I get the following message AttributeError: 'str' object has no attribute 'decode' Is there an alternative way to rewrite this code for Python 3.6?
has comment: http://stackoverflow.com/comment/85419975
linked to: http://stackoverflow.com/q/4808967
has comment: http://stackoverflow.com/comment/85419947

http://stackoverflow.com/a/49215257
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49215136
has body: If you are only interested in converting to categorical codes and being able to access the mapping via a dictionary, pd.factorize may be more convenient. Algorithm for getting unique values across columns via @AlexRiley. a = pd.DataFrame({'A':list('bbaba'), 'B':list('cccaa')}) fact = dict(zip(*pd.factorize(pd.unique(a'A', 'B'.values.ravel('K')))[::-1])) b = a.applymap(fact.get) Result: A B 0 0 2 1 0 2 2 1 2 3 0 1 4 1 1

http://stackoverflow.com/comment/85272982
has text: I know that will work, thanks.. but somebody really wants it as a csv
type: Comment
comment on: http://stackoverflow.com/a/49134098
score: 0
type: AnswerComment

fft
tags question: http://stackoverflow.com/q/49276041
tags question: http://stackoverflow.com/q/49268647
tags question: http://stackoverflow.com/q/49131534
tags question: http://stackoverflow.com/q/49256507
tags question: http://stackoverflow.com/q/49197366
type: Tag
tags question: http://stackoverflow.com/q/49199934
tags question: http://stackoverflow.com/q/49134926
tag name: fft
tags question: http://stackoverflow.com/q/49172828
tags question: http://stackoverflow.com/q/49130327

http://stackoverflow.com/comment/85284690
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49138091
has text: You mean from this anchor ` Text `?

http://stackoverflow.com/q/49235028
type: Question
type: AnsweredQuestion
score: 3
tagged with: apache-nifi
has comment: http://stackoverflow.com/comment/85479071
accepted answer: http://stackoverflow.com/a/49247653
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49295442
upvote count: 4
has title: Python ExecuteScript in NiFi: Transform flowfile attributes & content
has body: I am trying to create a Python script in NiFi that: Reads some attributes from an incoming flowfile Read the json content of the flowfile &amp; extract specific fields Write attributes to outgoing flowfile Overwrite incoming flowfile with new content that is created in the script (e.g. API call that returns new json) and send it to SUCCESS relationship OR remove the old flowfile and create new with desired content What i ve done so far: import json import java.io from org.apache.commons.io import IOUtils from java.nio.charset import StandardCharsets from org.apache.nifi.processor.io import StreamCallback,InputStreamCallback, OutputStreamCallback class OutputWrite(OutputStreamCallback, obj): def __init__(self): self.obj = obj def process(self, outputStream): outputStream.write(bytearray(json.dumps(self.obj).encode('utf'))) ###end class### flowfile = session.get() if flowfile != None: **#1) Get flowfile attributes** headers = { 'Accept-Encoding': 'gzip, deflate, br', 'Accept': 'application/json, text/plain, */*', 'Cache-Control': 'no-cache', 'Ocp-Apim-Trace': 'true', 'Authorization': flowfile.getAttribute('Authorization') } collection = flowfile.getAttribute('collection') dataset = flowfile.getAttribute('dataset') **#2)Get flowfile content** stream_content = session.read(flowfile) text_content = IOUtils.toString(stream_content, StandardCharsets.UTF_8) json_content = json.loads(text_content) records = json_content['result']['count'] pages = records/10000 **#3) Write flowfile attributes** flowfile = session.putAttribute(flowfile, 'collection', collection) flowfile = session.putAttribute(flowfile, 'dataset', dataset) **#API operations: output_json with desired data** output_json = {some data} **#4) Write final JSON data to output flowfile** flowfile = session.write(flowfile, OutputWrite(output_json)) session.transfer(flowfile, REL_SUCCESS) session.commit() My problem is that i can't find a way to pass a reference to the desired output_json object as an argument in the Ou…
has comment: http://stackoverflow.com/comment/85479429
linked to: http://stackoverflow.com/q/44630514
answer count: 2
tagged with: python
possible better answer: http://stackoverflow.com/a/49295442
has answer: http://stackoverflow.com/a/49247653

http://stackoverflow.com/comment/100696554
score: 0
type: Comment
comment on: http://stackoverflow.com/a/54694601
type: AnswerComment
has text: neat solution but I think @Ed Smiths answer is correct in using REFLECT instead of SYMMETRIC

http://stackoverflow.com/comment/85482573
comment on: http://stackoverflow.com/q/49239437
has text: The exercise doesn't really say the input list will be sorted.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85396217
type: QuestionComment
score: 0
has text: why you have `words` in such strange list of lists? Would be way easier if you just have a set of words.
comment on: http://stackoverflow.com/q/49195659
type: Comment

http://stackoverflow.com/comment/85451182
type: QuestionComment
comment on: http://stackoverflow.com/q/49223760
has text: You will have to create a RESTful webservice (eg. with flask, there are many tutorials online just google for flask restful)
score: 1
type: Comment

http://stackoverflow.com/a/49153723
type: AcceptedAnswer
has body: Here is the best use numpy.argsort because very fast. First filter columns by subset - [] and get indices by argsort for 2. and 3. top: cols = ['Calories','Fat','Carb','Fiber','Protein'] arr = data[cols].values.argsort(axis=1)[:, [-2, -3]] a = np.array(cols)[arr] print (a) [['Carb' 'Protein'] ['Carb' 'Protein'] ['Carb' 'Fat'] ['Carb' 'Fat'] ['Carb' 'Fat']] Also select values by indices: b = data[cols].values[np.arange(len(arr))[:,None], arr] print (b) [[50 12] [70 10] [45 22] [56 23] [52 22]] Last create DataFrames and add join by | for one column: data['Top Nutrient'] = data[cols].idxmax(axis=1) data['Amount']= data[cols].max(axis=1) data['NextTop2'] = pd.DataFrame(a).apply('|'.join, 1) data['NextTop2Amount'] = pd.DataFrame(b).astype(str).apply('|'.join, 1) print (data) Name Calories Fat Carb Fiber Protein Top Nutrient Amount \ 0 Chonga Bagel 300 5 50 3 12 Calories 300 1 8-Grain Roll 380 6 70 7 10 Calories 380 2 Almond Croissant 410 22 45 3 10 Calories 410 3 Apple Fritter 460 23 56 2 7 Calories 460 4 Banana Nut Bread 420 22 52 2 6 Calories 420 NextTop2 NextTop2Amount 0 Carb|Protein 50|12 1 Carb|Protein 70|10 2 Carb|Fat 45|22 3 Carb|Fat 56|23 4 Carb|Fat 52|22
type: Answer
has comment: http://stackoverflow.com/comment/85335280
accepted answer of: http://stackoverflow.com/q/49153471
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49153471

numpy-slicing
tags question: http://stackoverflow.com/q/49155699
type: Tag
tag name: numpy-slicing

http://stackoverflow.com/q/49242741
upvote count: 0
has title: How to create colums from one very large nested list?
has comment: http://stackoverflow.com/comment/85489556
answer count: 1
has body: All right, so I have a text file that I've imported into python and had some difficutlies doing so since the data in it was from an api that uses a wrapper and after reading about it online, I loaded it the following way: save_path = 'C:/path' name_of_file = "all_transactions" completename = os.path.join(save_path, name_of_file+ '.txt') raw_file = io.open(completename, 'r', encoding= "utf-8" ) It seemed to load now fine. This is how it looks like: 49021 &lt;class 'list'&gt; ["{'cursor':'longcode' 'currency': 'USD'},\n", " 'card_details': {'card': {'billing_address': None,\n", " The 'list' is mighty long with a lot of of headers in it. when I place it into pandas DataFrame this is what I get: 0 0 {'cursor': 'CAESzgEaGQoNOFJYS1lFMlg2WlBUUBABEA... 1 'errors': None,\n 2 'transactions': [{'client_id': None,\n 3 'created_at': '2018-03-12T1... Going down all the way to 49020 rows with one column. 'transactions' and 'cursor' are the two keys I believe. I need the other items like 'created at as column headers and their data in the rows like so: created_at customer_id alldates theidshere ... ... ... ... I really do no know how to do this, I've tried searching all over Please help! Thanks
tagged with: data-science
downvote count: 1
has comment: http://stackoverflow.com/comment/85489330
has comment: http://stackoverflow.com/comment/85489490
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49242833
type: UnansweredQuestion
tagged with: dataframe
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85489314
tagged with: pandas
has comment: http://stackoverflow.com/comment/85489547

http://stackoverflow.com/q/49166424
has answer: http://stackoverflow.com/a/49176631
tagged with: python
has body: I have a an api that is setup with import hug API = hug.API(__name__).http.base_url='/api' @hug.get('/hello-world', versions=1) def hello_world(response): return hug.HTTP_200 and I'm trying to test it with PyTest. I'm trying to test the route with import pytest import hug from myapi import api ... def test_hello_world_route(self): result = hug.test.get(myapp, 'v1/hello-world') assert result.status == hug.HTTP_200 How can I test hug routes that have http.base_url configured? I get a 404 errors regardless of the route path. I've tried /api/v1/hello-world api/v1/hello-world v1/hello-world /v1/hello-world If I remove the hug.API().http.base_url setting then v1/hello-world works fine but my requirement is to have a base_url setup. I've reviewed the documentation on the official hug github repo and various online sources such as ProgramTalk but I haven't had much success. any recommendations?
type: AnsweredQuestion
tagged with: hug
upvote count: 3
score: 3
answer count: 1
downvote count: 0
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49176631
tagged with: pytest
has title: Using PyTest with hug and base_url

http://stackoverflow.com/a/49198909
has body: Change the code bellow the boiler plate to this and use the timeit module instead. This code allows me to execute the functions a number of times and return the mean ans standard deviation execution time. if __name__ == "__main__": import timeit n = int(input("enter the range")) setup = """\ import numpy as np from __main__ import numpysum,pythonsum n = {iterations} """.format(iterations=n) npex = numpy.array(timeit.repeat('numpysum(n)',setup=setup,repeat=100,number=1000)) pyex = numpy.array(timeit.repeat('pythonsum(n)',setup=setup,repeat=100,number=1000)) print("Numpy Execution Time, mean={m},std={sd}".format(m=npex.mean(),sd=npex.std(0))) print("Python Execution Time, mean={m},std={sd}".format(m=pyex.mean(), sd=pyex.std(0))) By testing with n = 100, it is clear that numpy is much faster enter the range100 Numpy Execution Time, mean=0.00482892623162404,std=0.0005752600215192671 Python Execution Time, mean=0.1037349765653833,std=0.004933817536363718
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49195281
has comment: http://stackoverflow.com/comment/85435838
has comment: http://stackoverflow.com/comment/85424326
answers question: http://stackoverflow.com/q/49195281
type: Answer
has comment: http://stackoverflow.com/comment/85418117
score: 0

http://stackoverflow.com/comment/85412442
has text: Other things being equal you would always prefer the comprehension to the for loop. But if you have a million items in your dictionary and only two of them are strings, the comprehension would perform 999,998 unnecessary copies whereas the for loop would simply replace 2 values. So a rule like *comprehension=fast, for loop=slow* is too simple.
comment on: http://stackoverflow.com/q/49203269
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/60888547
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49269327
has body: use the following code width = height = 256 dim = (width, height) file_name = "your file address here" image = imageio.imread(file_name ) resized = cv2.resize(image, dim, interpolation = cv2.INTER_AREA) image2 = imageio.core.util.Array(resized) what you need to use is image2

http://stackoverflow.com/a/49131786
has comment: http://stackoverflow.com/comment/85269622
has comment: http://stackoverflow.com/comment/85269871
type: Answer
score: 0
has body: You can add an alternative for hardcoded no-response, would it help? (?P&lt;ports&gt;[\d]+)\/(?P&lt;protocol&gt;tcp|udp)\s+(?P&lt;state&gt;open|filtered|closed)\s+(?P&lt;service&gt;[\w\S]*)\s+(?P&lt;reason&gt;(:?\S*\s+\S+\s+\S*(?=\w)\w)|(:?no-response))(?:\n|(?P&lt;version&gt;.*)) Demo
answers question: http://stackoverflow.com/q/49131708

http://stackoverflow.com/a/49131410
type: Answer
downvote count: 1
has body: As far as I understood, you want to have a default value of 1 to the order integer field and increment it with each entry of Achievment (same functionality as the id), but also allow users change it. For this purpose you can use Django's AutoField: An IntegerField that automatically increments according to available IDs. You usually won’t need to use this directly; a primary key field will automatically be added to your model if you don’t specify otherwise. Like this: class Achievement(models.Model): ... order = models.AutoField(default=1, primary_key=False) # Also specify that this autofield is *not* a ^ primary key class Meta: ordering = ['order', 'id']
upvote count: 1
score: 0
answers question: http://stackoverflow.com/q/49131265
has comment: http://stackoverflow.com/comment/85285383

http://stackoverflow.com/a/49184221
type: AcceptedAnswer
has body: Fixed it using a gaussian filter to interpolate matrix before contouring: Image as a binary matrix of incident values (one incident in U.K., one in Argentina). Seen here as a color mesh: Color mesh before Guassian filter Apply a guassian filter to the mask matrix over the world: sigma_y = 3.0 sigma_x = 3.0 sigma = [sigma_y, sigma_x] y = sp.ndimage.filters.gaussian_filter(grid_new, sigma, mode='constant') Where grid_new is a 2D matrix of incident values. Color mesh after applying guassian filter: Matrix after guassian filter seen as a pcolormesh Apply .contourf function to the guassian filtered matrix: Contourf of gaussian filtered matrix
type: Answer
answers question: http://stackoverflow.com/q/49178459
score: 0
accepted answer of: http://stackoverflow.com/q/49178459

http://stackoverflow.com/a/49208143
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49208047
upvote count: 1
score: 1
type: AcceptedAnswer
has body: Evaluate your forms before the if-statement, to avoid missing evaluation due to and short-circuiting: detailvalid = user_detail_form.is_valid() locationvalid = user_location_form.is_valid() if not detailvalid and not locationvalid: return redirect('account:profile') More generally, in if 1 == 2 and 3 == 3: the second part is never evaluated, because the first part fails. With or, it's the other way around: if 1 == 1 or 2 == 3: now, the first part succeeds, and the second part is (again) never evaluated. More importantly, in both cases, if that second part involves a function call (e.g. is_valid()), that function is never called. More info at this SO question, in particular the second answer.
answers question: http://stackoverflow.com/q/49208047

http://stackoverflow.com/comment/85431578
comment on: http://stackoverflow.com/q/49213278
score: 0
type: Comment
type: QuestionComment
has text: Is all the info filled in for each person (i.e. does each person have a Name, Age, Gender, Job, and Location)? If not, how is missing data handled?

http://stackoverflow.com/comment/85544641
type: AnswerComment
has text: Why not just pass the function directly as an argument and check if it's this one in the loop?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49270201

shopify
tag name: shopify
type: Tag
tags question: http://stackoverflow.com/q/49244170

http://stackoverflow.com/comment/85328183
has text: @David probably an old version of pandas. I’m no longer in front of a computer to test.
comment on: http://stackoverflow.com/a/49160687
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/q/49155418
accepted answer: http://stackoverflow.com/a/49155659
has answer: http://stackoverflow.com/a/49156046
possible better answer: http://stackoverflow.com/a/49156046
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/85315449
upvote count: 1
downvote count: 1
favorite count: 0
has title: Python classes understanding
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85315761
has answer: http://stackoverflow.com/a/49156095
linked to: http://stackoverflow.com/q/10004850
has comment: http://stackoverflow.com/comment/85315545
tagged with: python
has body: I have type a code using classes and without using classes but i cant find why classes are useful.Both give the same output.Please help Here are the codes ; 1) class Hero: def __init__(self,name,health,p,s): self.name=name self.health=health self.p=int(p) self.a=int(s) food=vars() print(self.name,self.health) self.eat() print(self.health) def eat(self): print('choose a or b') food=input('&gt;') if food == 'a': self.health -= self.p elif food == 'b': self.health += self.a else: print('choose one among a and b') Hero('Bob',100,10,5) Hero('Ham',500,60,10) 2) def eat(health,p,a): print('choose a or b') food=input('&gt;') if food == 'a': health -= int(p) elif food == 'b': health += int(a) else: print('choose one among a and b') return health def Hero(name,health,p,a): print(name,health) health = eat(int(health),p,a) print(health) Hero('Bob',100,10,5) Hero('Ham',500,60,10) Someone please help.
has comment: http://stackoverflow.com/comment/85315838
tagged with: class
has answer: http://stackoverflow.com/a/49155659
type: AnsweredQuestion

http://stackoverflow.com/a/49191643
upvote count: 2
has comment: http://stackoverflow.com/comment/85388839
has comment: http://stackoverflow.com/comment/85388533
has comment: http://stackoverflow.com/comment/85388229
has comment: http://stackoverflow.com/comment/85388242
has comment: http://stackoverflow.com/comment/85389211
score: 2
has comment: http://stackoverflow.com/comment/85389081
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85389437
answers question: http://stackoverflow.com/q/49191577
has body: You may fix it by adding .*? before and .* after the pattern you have and replace with r'\1 : DATESTR' res = re.sub(r'.*?(\d{1,31}(?::? |[-/])\d{1,12}(?::? |[-/])\d{4}).*', r'\1 : DATESTR', s) See the regex demo. With .*? you match any 0+ chars other than line break chars, as few as possible, and with .* you match any 0+ chars other than line break chars, as many as possible, and that way you remove what you do not need by just matching and you keep what you capture. You may also use your regex to extract the date and then append : DATESTR to it: import re rx = r"\d{1,31}(?::? |[-/])\d{1,12}(?::? |[-/])\d{4}" s = "My name is ALi Date is 09/03/2018" m = re.search(rx, s) if m: print("{} : DATESTR".format(m.group())) # =&gt; 09/03/2018 : DATESTR See the Python demo.

http://stackoverflow.com/a/49204178
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49204156
has comment: http://stackoverflow.com/comment/85413835
type: Answer
accepted answer of: http://stackoverflow.com/q/49204156
has comment: http://stackoverflow.com/comment/85414415
has body: Exactly the same way you used regular weights.... def build(self, input_shape): self.kernel = self.add_weight(name='kernel', shape=(input_shape[1], self.output_dim), initializer='he_normal', trainable=True) self.bias = self.add_weight(name='bias', shape=(self.output_dim), initializer='zeros', trainable=True) super(MyLayer, self).build(input_shape) def call(self, x): ep = K.constant(value= 10e-5, shape=(1,513)) v = K.dot(x, self.kernel) #maybe add bias here? out = K.switch((v - ep)&gt;0, v, - (ep)/(v-1-ep)) return out + self.bias
downvote count: 0

http://stackoverflow.com/comment/85537612
comment on: http://stackoverflow.com/q/49267085
score: 0
has text: Did you look through the [Matplotlib gallery](https://matplotlib.org/gallery/index.html) for figures with multiple sub-plots and try to adapt the example code to your purpose?
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49215635
has answer: http://stackoverflow.com/a/49226168
tagged with: list
answer count: 3
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49215643
favorite count: 0
type: Question
has body: I want to group list digits by their value and calculate sum of each group. Basically, it looks this way: input: list = [0,1,1,0,0,0,1,0,1,1,1,1,0] OUT (which i want to get): newList = [0,2,0,1,0,4,0] Any ideas how to acheive this in Python? Thanks
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85435426
tagged with: python
has answer: http://stackoverflow.com/a/49215761
has title: Python: How to group elements in the list and get sum of groups

http://stackoverflow.com/comment/85412007
comment on: http://stackoverflow.com/q/49203300
has text: @Teemu I prefer javascript, but python would be good as well ;)
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/q/49274575
type: AnsweredQuestion
has body: here is my problem: I have tow csv files as follows: Book1.csv Id Product 0 aaaa 1 bbbb 2 cccc 3 dddd Book2.csv Id Attribute 0 aaad 0 sssd 1 fffd 1 gggd 1 cccd 2 bbbd 3 hhhd 3 bbbd I want merge above files and get an output file as this: Product Attributes aaaa aaad, sssd bbbb fffd, gggd, cccd cccc bbbd dddd hhhd, bbbd The code I am using right now is: import pandas as pd a = pd.read_csv("Book1.csv") b = pd.read_csv("Book2.csv") b = b.dropna(axis=0) merged = a.merge(b, how='left', left_on='Id', right_on='Id' ) merged.rename(columns={ 'Product': 'Product', 'Attribute': 'Attributes'}, inplace=True) merged = merged'Product','Attributes' merged.to_csv("output.csv", index=False) what I get from this is : Product Attributes aaaa aaad aaaa sssd bbbb fffd bbbb gggd bbbb cccd cccc bbbd dddd hhhd dddd bbbd All the Attributes and Products are merged correctly. But what I want is merge Attibutes into one string and separate by comma (not line by line). How do I do this? Thank you in advance!
tagged with: pandas
score: 1
accepted answer: http://stackoverflow.com/a/49274723
answer count: 1
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49274723
favorite count: 0
type: Question
has title: Merge 2 CSV files with mapped values in another file separated by comma
tagged with: http://stackoverflow.com/tag/csv
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/49129374
score: 1
has comment: http://stackoverflow.com/comment/85264181
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49129129
type: Answer
has comment: http://stackoverflow.com/comment/85264239
has body: As of date it's not possible to add compression for tiff format. There is an open issue and a worked solution but has not seen progress since May last year or so. In the worked solution there is a proposed workflow and quoting ... generate huge TIFF image files with MPL, then import them in PIL, save them in PIL using compression of the TIFF and then discarding the uncompressed TIFF files. The scikit-image project has some tiff image saving functionality with compression, it might help you depending on your use case. Most likely the journal accepts other formats besides tiff. Then you can go for png or jpeg which with a DPI of 600 would work fine for basically all purposes of a journal.

http://stackoverflow.com/comment/85253666
score: 0
has text: Speed and space are two different and in general unrelated dimensions.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49124214

http://stackoverflow.com/comment/85375720
has text: I'm not sure how to do what you are saying
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49184761
score: 0

http://stackoverflow.com/comment/124849610
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/70623613
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).

http://stackoverflow.com/comment/85381617
type: Comment
type: QuestionComment
has text: I don't think that the question is a duplicate of the proposed original question. This one applies to DRF and not the original one.
comment on: http://stackoverflow.com/q/49187774
score: 1

http://stackoverflow.com/comment/85544197
score: 0
type: QuestionComment
type: Comment
has text: Oganesson is kind of new.
comment on: http://stackoverflow.com/q/49270330

http://stackoverflow.com/q/49174794
has body: How to correctly output all links on this news website? (in list form) After output in list form, how can I return the result randomly (3~5 links a time) note: the code I need starts from line 739 (nearly it may change a bit cause it refresh everyday) div class="abdominis rlby clearmen" and I need every link inside this kind of thing &lt;a href="https://tw.news.appledaily.com/life/realtime/20180308/1310910/&gt; Thanks!! the code is below: from bs4 import BeautifulSoup from flask import Flask, request, abort import requests import re import random import types target_url = 'http://www.appledaily.com.tw/realtimenews/section/new/' print('Start parsing appleNews....') rs = requests.session() res = rs.get(target_url, verify=False) soup = BeautifulSoup(res.text, 'html.parser') #can output all links but with useless information contents = soup.select("div[class='abdominis rlby clearmen']")[0].find_all('a') print(contents) #can output single link but not in list form #contents = soup.select("div[class='abdominis rlby clearmen']")[0].find('a').get('href') #print(contents)
accepted answer: http://stackoverflow.com/a/49175032
tagged with: web-crawler
has answer: http://stackoverflow.com/a/49175032
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49175235
has comment: http://stackoverflow.com/comment/85356609
answer count: 2
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85355172
has comment: http://stackoverflow.com/comment/85355092
type: AnsweredQuestion
score: 3
tagged with: python-2.7
has title: Beautifulsoup - Problems for webcrawler
has answer: http://stackoverflow.com/a/49175235
has comment: http://stackoverflow.com/comment/85356577
upvote count: 3

http://stackoverflow.com/comment/85477682
has text: I tried this solution, but I am getting the following error. "Buffer has wrong number of dimensions (expected 1, got 2)"
comment on: http://stackoverflow.com/a/49235883
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/49157380
has body: list(data.items()) will give you a list version of all entries in the dictionary as tuples of the form (key, value) that you can iterate over or index as needed: &gt;&gt;&gt; d = { 'a': 1, 'b': 2, 'c': 3 } &gt;&gt;&gt; print(list(d.items())[0]) ('a', 1) So in your case, list(data['books'].items())
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49157285
type: Answer
score: 25
answers question: http://stackoverflow.com/q/49157285
upvote count: 25

http://stackoverflow.com/a/49226861
type: AcceptedAnswer
downvote count: 0
has body: The closing bracket ) is being included inside the square brackets because the square bracket before it isn't escaped properly. ^.+@([?)[a-zA-Z0-9-.]+. ^ v ^.+@(\[?)[a-zA-Z0-9-.]+. Example: In[2]: import re ...: ...: ...: def is_valid_email(email): ...: if len(email) &gt; 7: ...: return bool(re.match( ...: "^.+@(\[?)[a-zA-Z0-9-.]+.([a-zA-Z]{2,3}|[0-9]{1,3})(]?)$", email)) ...: In[3]: is_valid_email("my.email@gmail.com") Out[3]: True
answers question: http://stackoverflow.com/q/49226806
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/49226806
score: 5

http://stackoverflow.com/comment/85315623
type: QuestionComment
comment on: http://stackoverflow.com/q/49155319
has text: That's because your `list_of_df` is a list of strings? I would've assumed it was a list of variable names.
score: 1
type: Comment

http://stackoverflow.com/comment/85547411
type: QuestionComment
comment on: http://stackoverflow.com/q/49272266
score: 0
type: Comment
has text: Related: https://stackoverflow.com/questions/45308212/is-there-a-way-to-return-a-custom-value-for-min-and-max-in-python

http://stackoverflow.com/comment/85356698
score: 0
type: Comment
type: QuestionComment
has text: Why is this current solution too slow? Do you have benchmarks showing that python can achieve a higher IO rate, or is this a script that needs to write lots of data in realtime?
comment on: http://stackoverflow.com/q/49172608

http://stackoverflow.com/comment/85458111
score: 1
has text: You can just do `key=sum`.
type: Comment
comment on: http://stackoverflow.com/a/49227163
type: AnswerComment

http://stackoverflow.com/q/49219161
has title: How to declare global variables with Cython in a Jupyter Notebook?
favorite count: 0
tagged with: jupyter-notebook
type: Question
score: 5
upvote count: 5
downvote count: 0
tagged with: python
linked to: http://stackoverflow.com/q/43725273
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49220203
answer count: 1
has answer: http://stackoverflow.com/a/49220203
has body: I have a few variables that should be accessible globally in the program. Since they are used so often I'm thinking of giving them a type which from my understanding would speed things up. I'm not able to do this. In one block in the Jupyter Notebook I have this: %%cython cdef int magic_number = 42 In the next block I get the following error: print(magic_number) --------------------------------------------------------------------------- NameError Traceback (most recent call last) &lt;ipython-input-34-a40fcb730ac3&gt; in &lt;module&gt;() ----&gt; 1 print(magic_number) NameError: name 'magic_number' is not defined cpdef also doesn't work. How can I get global variables?
tagged with: cython
tagged with: global-variables

http://stackoverflow.com/comment/85452059
type: QuestionComment
has text: Possible duplicate of [np.concatenate a ND tensor/array with a 1D array](https://stackoverflow.com/questions/48066662/np-concatenate-a-nd-tensor-array-with-a-1d-array)
comment on: http://stackoverflow.com/q/49224228
score: 0
type: Comment

http://stackoverflow.com/a/49136049
downvote count: 0
answers question: http://stackoverflow.com/q/49135870
has comment: http://stackoverflow.com/comment/85277186
upvote count: 2
has comment: http://stackoverflow.com/comment/85349583
accepted answer of: http://stackoverflow.com/q/49135870
type: AcceptedAnswer
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85350777
has body: You can use Python's Counter to help determine if there are duplicates: import xlrd from collections import Counter def FindDuplicates(in_list): counts = Counter(in_list) two_or_more = [item for item, count in counts.items() if count &gt;= 2] print two_or_more return len(two_or_more) &gt; 0 workbook = xlrd.open_workbook(r"input.xls") sheet = workbook.sheet_by_index(0) col_a = [sheet.row(row)[0].value for row in range(sheet.nrows)] # Read in all rows print FindDuplicates(col_a) Python by default cannot read in an .xls file so you will need to install a package to help. I have used xlrd to read in the older format .xls file. This could be installed by using: pip install xlrd If you are able to save your Excel file in .csv format, then the following code could be used: import csv from collections import Counter def FindDuplicates(in_list): counts = Counter(in_list) two_or_more = [item for item, count in counts.items() if count &gt;= 2] print two_or_more return len(two_or_more) &gt; 0 with open('input.csv', 'rb') as f_input: col_a = [row[0] for row in csv.reader(f_input)] print FindDuplicates(col_a)

http://stackoverflow.com/a/49199216
type: AcceptedAnswer
has body: You can keep track of all instances that are still referenced using a WeakSet. from weakref import WeakSet class Spam: _instances = WeakSet() def __init__(self, *args, **kwargs): self._instances.add(self) Here is a working example. class SubSpam(Spam): pass x = SubSpam() # Create an instance len(Spam._instances) # 1 x = 0 # Drop reference to this instance len(Spam._instances) # 0 For the above to work you will need to make sure to always call the super __init__ method when overidding __init__. class AnotherSubSpam(Spam): def __init__(self): # Do some stuff super().__init__() Alternatively, you could also keep track of the instances in the __new__ method which is not as often overridden. class Spam: _instances = WeakSet() def __new__(cls, *args, **kwargs): # Create the instance instance = super().__new__(cls, *args, **kwargs) # Keep track of the instance cls._instances.add(instance) # Return the instance as __new__ would return instance
score: 1
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49184456
downvote count: 0
answers question: http://stackoverflow.com/q/49184456

rpy2
tags question: http://stackoverflow.com/q/49144110
type: Tag
tag name: rpy2

http://stackoverflow.com/a/49224352
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49224272
has body: What about: python setup.py install --user As stated in the doc, it should work as you expect: https://docs.python.org/2/install/#alternate-installation-the-user-scheme
has comment: http://stackoverflow.com/comment/85688768
score: 1
type: Answer

http://stackoverflow.com/comment/85326041
type: Comment
type: AnswerComment
has text: I think the OP needs the answer 5 seconds and 13 miliseconds, your answer, reading it carefully, is 5 seconds and 130 miliseconds, or 130000 microseconds
comment on: http://stackoverflow.com/a/49160284
score: 0

http://stackoverflow.com/comment/85353680
score: 1
type: Comment
type: QuestionComment
has text: In general matplotlib.dates locators and formatters are incompatible with pandas plots. I think I've written this comment below some 20 questions already, so I'm a bit tired of finding the corresponding answers again.
comment on: http://stackoverflow.com/q/49174302

http://stackoverflow.com/comment/85304077
comment on: http://stackoverflow.com/a/49133591
type: Comment
has text: Yes, that would be my goal. How would you do that?
score: 0
type: AnswerComment

http://stackoverflow.com/a/49265997
downvote count: 0
has body: You need to move print statement out of for loop: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] x = [] def less_than_five(): for item in a: if item &lt; 5: x.append(item) print(x) less_than_five() Result: [1, 1, 2, 3] Same result can be achieved with list comprehension: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] x = [] def less_than_five(): # if original x has to be changed extend is used x.extend([item for item in a if item &lt; 5]) print(x) less_than_five()
answers question: http://stackoverflow.com/q/49265975
type: Answer
has comment: http://stackoverflow.com/comment/85535530
has comment: http://stackoverflow.com/comment/85535552
score: 2
upvote count: 2

http://stackoverflow.com/comment/85447801
has text: @Aran-Fey, how can you tell that some combination is new? You'd have to keep a potentially huge database of such combinations, then. And if you'd want to use this code on other machines, you'd have to copy this DB to them. Sounds a bit like blockchain, which consumes tens of gigs of storage.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49221989
type: AnswerComment

http://stackoverflow.com/comment/85455245
type: Comment
comment on: http://stackoverflow.com/q/49225534
score: 0
has text: a general principle: fail early', logic tests 'shortcircuit' - so the cheapest tests that eliminate the most cases should be up front, also looks like the code repeats some `in` tests with same args - refactor logic to avoid or assign vars with single test result, use var's values in repeated tests
type: QuestionComment

http://stackoverflow.com/q/49255529
has body: I want to save the value for VolumeId, in a variable as a result of the following: #!/usr/bin/env python import boto3 import json import argparse import logging import pprint parser = argparse.ArgumentParser( description='get_ec2_inst_state' ) parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() if args.verbose: logging.basicConfig(level=logging.DEBUG) logging.debug('running debug mode') ec2client = boto3.client('ec2') instance_id_value = input("Please enter the ec2 instance id : ") volume = ec2client.describe_instance_attribute(InstanceId= instance_id_value,Attribute='blockDeviceMapping') #for key in volume: # print (key) #print (volume) #pprint.pprint(volume, width=1) for key,value in volume.items(): print(key,value) #for key,value in value.items(): # print(key, ":", value) result: ./get_ec2_inst_vol.py Please enter the ec2 instance id : i-09f9696ce9150eb1f BlockDeviceMappings [{'DeviceName': '/dev/sda1', 'Ebs': {'AttachTime': datetime.datetime(2018, 1, 29, 1, 0, 52, tzinfo=tzlocal()), 'DeleteOnTermination': True, 'Status': 'attached', 'VolumeId': 'vol-0b42c57c7ba0281d6'}}] InstanceId i-09f9696ce9150eb1f ResponseMetadata {'RequestId': '6c4bbe79-5583-4ee4-8131-1e3bde5e4fa9', 'HTTPStatusCode': 200, 'HTTPHeaders': {'content-type': 'text/xml;charset=UTF-8', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding', 'date': 'Tue, 13 Mar 2018 11:51:45 GMT', 'server': 'AmazonEC2'}, 'RetryAttempts': 0} Now, how can i get VolumeId from the key BlockDeviceMappings . Keeping in mind that volume object is of type dictionary -------------------- notes ---------------------------- using resource interface VS client, some links: When to use a boto3 client and when to use a boto3 resource? http://boto3.readthedocs.io/en/latest/guide/resources.html http://boto3.readthedocs.io/en/latest/guide/clients.html
score: 1
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/39272744
upvote count: 1
accepted answer: http://stackoverflow.com/a/49255673
favorite count: 0
type: Question
has title: How to get VolumeId from the key BlockDeviceMappings (boto3 get volume info for ec2)
has answer: http://stackoverflow.com/a/49255673
tagged with: python
tagged with: boto3
tagged with: dictionary
tagged with: amazon-web-services
type: AnsweredQuestion

http://stackoverflow.com/a/49253211
score: 0
has comment: http://stackoverflow.com/comment/85509703
answers question: http://stackoverflow.com/q/49253140
type: Answer
has comment: http://stackoverflow.com/comment/85510054
has comment: http://stackoverflow.com/comment/85510172
has body: Try this: dictionary = {'key': ['value']} print(dictionary.get('key'))[0] Output: value [Finished in 0.0s]

http://stackoverflow.com/q/49261490
has title: Pandas timestamps to timeranges
answer count: 1
has body: I have a dataframe consisting of 10 minute timestamps like this: import pandas as pd import numpy as np df = pd.DataFrame({'TIME_BIN': np.random.randint(1, 86400, size=10000)}) df['TIME_BIN'] = pd.to_datetime(df['TIME_BIN'], unit='s').dt.round('10min').dt.strftime('%H:%M:%S') print(df) TIME_BIN 0 07:40:00 1 01:40:00 2 12:00:00 3 06:30:00 4 00:00:00 5 04:30:00 How would I append the beginning of the range (subtract 10) and concatenate so that the column looks like this TIME_BIN 0 07:30:00-07:40:00 1 01:30:00-01:40:00 2 11:50:00-12:00:00 3 06:20:00-06:30:00 4 23:50:00-00:00:00 5 04:20:00-04:30:00
has comment: http://stackoverflow.com/comment/85527352
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49261879
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/85527409
has answer: http://stackoverflow.com/a/49261879
tagged with: python
has comment: http://stackoverflow.com/comment/85527484
type: Question

http://stackoverflow.com/q/49234274
type: Question
accepted answer: http://stackoverflow.com/a/49234320
upvote count: 1
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/49234320
tagged with: pandas
type: AnsweredQuestion
has body: I have one DataFrame generated from below code import pandas as pd import pandas_datareader.data as web from datetime import datetime start=datetime(2018, 3, 1) end=datetime(2018,3,12) symbol = ['AAPL' , 'IBM' , 'MSFT' , 'GOOG'] Morningstar=web.DataReader(symbol, data_source='morningstar',start=start, end=end) dfResetMorningstar=Morningstar.reset_index() pricemine=dfResetMorningstar'Symbol','Date','Close' pricemine.set_index(['Symbol','Date'], inplace=True) Result: enter image description here I would like to transform the dataframe into format similar as below (the data would be the ['Close'] data enter image description here I'm not sure how this can be achieved using "groupby" comment. Any feedback would be much appreciated. Also open to other ways not using "groupby". Thank you!
downvote count: 0
tagged with: dataframe
score: 1
favorite count: 0
has title: Python: DataFrame restructure

http://stackoverflow.com/comment/85265229
score: 0
comment on: http://stackoverflow.com/q/49128032
has text: There are so many problems here this is unlikely to work. If you deliver a tuple to your `solver`, you need to receive it as *args, otherwise you will get an error of missing positional arguments. Your `pool.map()` does not return three items. It returns a list, in this case [(x,u,t), (x,u,t) ... ] where tuples are results from each individual worker. Your args needs to be a list of tuples. Etc.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49128622
has comment: http://stackoverflow.com/comment/85261914
tagged with: python
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/85261921
score: 2
has comment: http://stackoverflow.com/comment/85261713
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49128741
tagged with: list
upvote count: 3
has answer: http://stackoverflow.com/a/49128741
has comment: http://stackoverflow.com/comment/85261799
has comment: http://stackoverflow.com/comment/85261702
has answer: http://stackoverflow.com/a/49129067
has answer: http://stackoverflow.com/a/49128886
downvote count: 1
has answer: http://stackoverflow.com/a/49128706
accepted answer: http://stackoverflow.com/a/49128699
has body: I have a list such as: a = [[1,'b',2],[3,':',4],[5,':',6]] I want to remove the 'b' and ':' characters so that I end up with: [[1,2],[3,4],[5,6]] (Note that the fact that these characters are in the second position of each sublist is just an accident of my choice of example - the real data set I am working on has the same characters in random positions). I have chosen to use a list comprehension to do this. Here is an example of the code to iterate over each item of the sublists: for list in a: for number in list: print number But when I implement my list comprehension instead of the print statement like this: b = [] for list in a: for number in list: b = [number for number in list if number != 'b' and number != ':'] print b I get the following output: [1, 2] [1, 2] [1, 2] [3, 4] [3, 4] [3, 4] [5, 6] [5, 6] [5, 6] My question is, why are there three copies of each sublist? I was expecting [1,2] [3,4] [5,6] Any help and/or guidance would be much appreciated. Cheers.
favorite count: 0
type: Question
has title: Remove an element at a specific position from every sublist
has answer: http://stackoverflow.com/a/49128699
has comment: http://stackoverflow.com/comment/85261969
answer count: 5

http://stackoverflow.com/a/49170340
downvote count: 1
score: 19
has comment: http://stackoverflow.com/comment/85346100
upvote count: 20
has body: Only install BeautifulSoup4 instead of bs4 and BeautifulSoup then, do this: from bs4 import BeautifulSoup
type: Answer
answers question: http://stackoverflow.com/q/49170271
has comment: http://stackoverflow.com/comment/85346173
has comment: http://stackoverflow.com/comment/85346143

http://stackoverflow.com/q/49179845
has comment: http://stackoverflow.com/comment/85365242
has title: Threaty safety vs performance in Java and Python
has comment: http://stackoverflow.com/comment/85366147
has comment: http://stackoverflow.com/comment/85365887
has comment: http://stackoverflow.com/comment/85365605
type: UnansweredQuestion
has body: Use case: a single data structure (hashtable, array, etc) whose members are accessed frequently by multiple threads and modified infrequently by those same threads. How do I maintain performance while guaranteeing thread safety (ie, preventing dirty reads). Java: Concurrent version of the data structure (concurrent hashmap, Vector, etc). Python: No need if only threads accessing it, because of GIL. If it's multiple processes that will be reading and updating the data structure, then use threading.Lock. Force the each process's code to acquire the lock before and release the lock after accessing the data structure. Does that sound reasonable? Will Java's concurrent data structure impose too much penalty to read speed? Is there higher level concurrency mechanism in python?
has comment: http://stackoverflow.com/comment/85365657
tagged with: multithreading
answer count: 1
has comment: http://stackoverflow.com/comment/85365424
has comment: http://stackoverflow.com/comment/85365648
has comment: http://stackoverflow.com/comment/85365148
has comment: http://stackoverflow.com/comment/85365492
type: Question
has comment: http://stackoverflow.com/comment/85365577
score: 0
has comment: http://stackoverflow.com/comment/85365567
has comment: http://stackoverflow.com/comment/85369449
tagged with: java
has comment: http://stackoverflow.com/comment/85365189
tagged with: python
tagged with: concurrency
has answer: http://stackoverflow.com/a/49180737

http://stackoverflow.com/a/49239777
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49237973
accepted answer of: http://stackoverflow.com/q/49237973
score: 1
type: AcceptedAnswer
downvote count: 0
has body: You could balance your lists as follows: from bs4 import BeautifulSoup import requests url = "https://www.realtor.com/realestateandhomes-search/48198" user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1' html = requests.get(url, headers={'User-Agent':user_agent}).text soup = BeautifulSoup(html, "html.parser") house = {"beds": [], "baths": [], "lotsize": []} for div in soup.select('div.srp-item-property-meta'): for label, tag in [('property-meta-beds', 'beds'), ('property-meta-baths', 'baths'), ('property-meta-lotsize', 'lotsize')]: li = div.ul.find('li', {'data-label':label}) house[tag].append(li.text if li else 'None') print(house) This would give you house containing: { 'beds': ['3 bd', '3 bd', '3 bd', '3 bd', '3 bd', '3 bd', '2 bd', '2 bd', '3 bd', 'None', 'None', '3 bd', '3 bd', '3 bd', '3 bd'], 'baths': ['1+ ba', '1 ba', '2 ba', '1 ba', '1 ba', '2 ba', '2 ba', '2 ba', '1 ba', 'None', 'None', '1 ba', '2 ba', '2 ba', '1+ ba'], 'lotsize': ['None', '7,405 sq ft lot', '5,663 sq ft lot', '6,098 sq ft lot', '8,712 sq ft lot', '7,405 sq ft lot', '2,178 sq ft lot', 'None', '7,841 sq ft lot', '2.1 acres lot', '2.24 acres lot', '5,663 sq ft lot', 'None', 'None', '7,405 sq ft lot'] } If a given data-label is not found, it appends None.

http://stackoverflow.com/a/49124400
has comment: http://stackoverflow.com/comment/85281613
has comment: http://stackoverflow.com/comment/85280578
has comment: http://stackoverflow.com/comment/85277967
has comment: http://stackoverflow.com/comment/85283260
has comment: http://stackoverflow.com/comment/85284668
has comment: http://stackoverflow.com/comment/85280778
has comment: http://stackoverflow.com/comment/85284762
has body: Considering provided image of HTML source (tip: do not provide it as image, but as text instead) I can assume that required element located in the bottom of page and you might need to scroll page down to be able to handle it. Try below code link = browser.find_element_by_id("btnSearch") browser.execute_script("arguments[0].scrollIntoView()", link) link.click() Note that link is not a pseudo-element (is not located inside ::before/::after pseudo-element), so it can not be the cause of your problem As for your code: ActionChains(browser).move_to_element_with_offset(el, 1827, 270) ActionChains(browser).click() ActionChains(browser).perform() Here you're trying to make scroll to link with huge offset and then you make click on current mouse position - not on link You can try to modify it as ActionChains(browser).move_to_element(el) ActionChains(browser).click(el) # Pass WebElement you want to click as argument to `click()` ActionChains(browser).perform()
has comment: http://stackoverflow.com/comment/85281366
has comment: http://stackoverflow.com/comment/85284317
has comment: http://stackoverflow.com/comment/85277755
has comment: http://stackoverflow.com/comment/85254827
type: Answer
has comment: http://stackoverflow.com/comment/85283639
answers question: http://stackoverflow.com/q/49122003
has comment: http://stackoverflow.com/comment/85284168
has comment: http://stackoverflow.com/comment/85284247
score: 0

series
tags question: http://stackoverflow.com/q/49223937
tags question: http://stackoverflow.com/q/49134264
tag name: series
tags question: http://stackoverflow.com/q/49140570
type: Tag
tags question: http://stackoverflow.com/q/49169705
tags question: http://stackoverflow.com/q/49259630

http://stackoverflow.com/a/49226542
upvote count: 1
has body: Here are two more methods to complement @hpaulj's answer. One of them, the frompyfunc methods seems to scale a bit better than the other methods, although hpaulj's preallocation method is also not bad if we get rid of the loop. See timings below: import numpy as np import itertools bi_grams = [[(1, 2), (2, 3)], [(4, 5), (5, 6)], [(7, 8), (8, 9)]] def f_pp_1(bi_grams): return np.frompyfunc(itertools.chain.from_iterable(bi_grams).__next__, 0, 1)(np.empty((len(bi_grams), len(bi_grams[0])), dtype=object)) def f_pp_2(bi_grams): res = np.empty((len(bi_grams), len(bi_grams[0])), dtype=object) res[...] = bi_grams return res def f_hpaulj(bi_grams): res = np.empty((len(bi_grams), len(bi_grams[0])), dtype=object) for i, j in np.ndindex(res.shape): res[i, j] = bi_grams[i][j] return res print(np.all(f_pp_1(bi_grams) == f_pp_2(bi_grams))) print(np.all(f_pp_1(bi_grams) == f_hpaulj(bi_grams))) from timeit import timeit kwds = dict(globals=globals(), number=1000) print(timeit('f_pp_1(bi_grams)', **kwds)) print(timeit('f_pp_2(bi_grams)', **kwds)) print(timeit('f_hpaulj(bi_grams)', **kwds)) big = 10000 * bi_grams print(timeit('f_pp_1(big)', **kwds)) print(timeit('f_pp_2(big)', **kwds)) print(timeit('f_hpaulj(big)', **kwds)) Sample output: True &lt;- same result for True &lt;- different methods 0.004281356999854324 &lt;- frompyfunc small input 0.002839841999957571 &lt;- prealloc ellipsis small input 0.02361366100012674 &lt;- prealloc loop small input 2.153144505 &lt;- frompyfunc large input 5.152567720999741 &lt;- prealloc ellipsis large input 33.13142323599959 &lt;- prealloc looop large input
answers question: http://stackoverflow.com/q/49225933
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/a/49199576
upvote count: 4
has body: Using tolist and sum sum(df.values.tolist(),[]) Out[65]: ['a', 'b', 'c', 'f', 'g', 'h', 'k', 'l', 'm']
downvote count: 0
answers question: http://stackoverflow.com/q/49199430
type: Answer
score: 4

http://stackoverflow.com/comment/85373768
type: QuestionComment
type: Comment
score: 2
comment on: http://stackoverflow.com/q/49181602
has text: if you want optimize your `ReportFilter` then you should show its code...

http://stackoverflow.com/q/49192921
has answer: http://stackoverflow.com/a/49194998
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85390608
linked to: http://stackoverflow.com/q/47661536
has body: Using the URLconf defined in WisdomPets.urls, Django tried these URL patterns, in this order: admin/ ^$ [name='home'] ^adoptions/(\d+)/ [name='pet_detail'] The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. when I run server there was a warning WARNINGS: ?: (2_0.W001) Your URL pattern '^$' [name='home'] has a route that contains '(?P&lt;', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). ?: (2_0.W001) Your URL pattern '^adoptions/(\d+)/' [name='pet_detail'] has a route that contains '(?P&lt;', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). Here is the code.. from django.contrib import admin from django.urls import path from adoptions import views urlpatterns = [ path('admin/', admin.site.urls), path(r'^$', views.home, name='home'), path(r'^adoptions/(\d+)/', views.pet_detail, name='pet_detail'), ]
type: Question
has comment: http://stackoverflow.com/comment/85390539
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: django-urls browser preview error

http://stackoverflow.com/comment/85452044
type: QuestionComment
type: Comment
score: 0
has text: Is there a reason that every tuple of your result has length 3? Why is 16 and 31 not in the answer of your first example?
comment on: http://stackoverflow.com/q/49224066

http://stackoverflow.com/q/49241026
has answer: http://stackoverflow.com/a/49241073
tagged with: dataframe
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/49241115
has title: Duplicate list values and add in new column to dataframe
type: Question
has answer: http://stackoverflow.com/a/49241159
upvote count: 2
downvote count: 0
tagged with: python
has body: Apologies if this is a duplicate, but I could not find a similar question. I have a toy dataframe: A B participant 0 1 3 1 1 2 4 1 2 5 8 2 3 4 9 2 I have a list that corresponds to a single measurement made for each participant. measurement_list = [2.5, 4.7] How can I assign each participant's measurement to a new column? Desired: A B participant measurement 0 1 3 1 2.5 1 2 4 1 2.5 2 5 8 2 4.7 3 4 9 2 4.7 (The real dataset is much, much larger.)
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49241072
tagged with: list
possible better answer: http://stackoverflow.com/a/49241073
tagged with: pandas
has answer: http://stackoverflow.com/a/49241072

http://stackoverflow.com/q/49216532
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49216561
linked to: http://stackoverflow.com/q/41585078
type: UnansweredQuestion
has body: If I use the following code: with open('examplefile.csv') as tst: for line in tst: x = line print(x) I see 5 columns and numerous rows. How do I take one row at a time and set variables to each item in a row?
has title: How to manipulate one line at a time?
tagged with: python
has answer: http://stackoverflow.com/a/49216554
score: 2
upvote count: 3
answer count: 2
downvote count: 1
duplicate of: http://stackoverflow.com/q/41585078
favorite count: 0

http://stackoverflow.com/q/49250074
has title: How to get a mask bit from two inputs with python?
score: 0
type: UnansweredQuestion
has body: The program takes an begin IP address and an End IP Address as input and gives the following information about the inputs: (Mask Bits ) Example : 5.23.112.0 5.23.119.255
answer count: 1
has answer: http://stackoverflow.com/a/49251810
type: Question
tagged with: python

http://stackoverflow.com/q/49140843
tagged with: python
type: AnsweredQuestion
score: 0
has body: I have a class that displays a QMessageBox each time an action is performed. I was trying to set the button colour in the QMessageBox to a silver background. At the moment the button is blue which is the same as the background of the QMessageBox. My question is, how, with this piece of code: QtWidgets.qApp.setStyleSheet("QMessageBox QPushButton{background-color: Silver;}") can i change the QPushButton colour in the QMessageBox to silver. This is a snippet of my code. I have tried to put the above snippet into the function so that when the button is clicked, the colour of the QPushButton in the message box will be silver. Is there a problem with this as it does not seem to make any change. Where should I place this styleSheet functionality in the code? self.canonicalAddressesButton.clicked.connect(self.canonical_data_parsed_notification) def canonical_data_parsed_notification(self): QtWidgets.QMessageBox.information(self.mainwindow, 'Notification', 'Canonical Address Data Has Been Parsed!', QtWidgets.QMessageBox.Ok) QtWidgets.qApp.setStyleSheet("QMessageBox QPushButton{background-color: Silver;}")
has comment: http://stackoverflow.com/comment/85299734
has answer: http://stackoverflow.com/a/49153194
accepted answer: http://stackoverflow.com/a/49153194
upvote count: 1
downvote count: 1
answer count: 1
tagged with: pyqt5
has title: Setting background of QPushButton in QMessageBox
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85287895

http://stackoverflow.com/comment/85321311
comment on: http://stackoverflow.com/q/49155728
type: QuestionComment
score: 0
has text: @Code-Apprentice In the cases I looked at, yes, the results are correct. (PS: now added numpy import). But it's quite verbose. And I guess more pythonic would also mean faster.
type: Comment

http://stackoverflow.com/q/49198719
type: Question
tagged with: latex
score: 1
has answer: http://stackoverflow.com/a/49205443
tagged with: python
downvote count: 0
upvote count: 1
type: UnansweredQuestion
has title: Django: output textfile to be proceeded
answer count: 1
tagged with: tex
tagged with: django
has body: i have a small django application that i use to manage my patients data ( i am a doctor with an intermediate level in python/django) I used LaTeX to output my reports via a view function like that def consultation_pdf(request, pk2, pk1): entry = Consultation.objects.get(pk=pk2) source = Patient.objects.get(pk=pk1) # context = Context({ 'consultation': entry, 'patient': source }) context = dict({'consultation': entry, 'patient': source}) template = get_template('clinic/consultation.tex') rendered_tpl = template.render(context, request).encode('utf-8') # Python3 only. For python2 check out the docs! with tempfile.TemporaryDirectory() as tempdir: # Create subprocess, supress output with PIPE and # run latex twice to generate the TOC properly. # Finally read the generated pdf. for i in range(2): process = Popen( ['xelatex', '-output-directory', tempdir], stdin=PIPE, stdout=PIPE, ) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r Now i need to switch to ConTeXT since it fills more my needs. The biggest problem so far is that ConTeXT needs both the source file and the pdf to be saved on the disk, and not simply piping stdin and stdout , respectively. How could i manage to complete this task? so far the only workaround i've found is to generate a tex file then run it manually. Thank you for your help
favorite count: 0

http://stackoverflow.com/q/49243131
linked to: http://stackoverflow.com/q/13704860
has comment: http://stackoverflow.com/comment/85490102
type: AnsweredQuestion
has title: why is my decreasing number count repeating?
has comment: http://stackoverflow.com/comment/85490168
has body: d=int(input("Decreasing number: ")) i=int(input("Increasing number: ")) def i_d (n,m): c=0 for f in range (100,0,-n): for c in range (0,100,m): print (f,c) print () i_d(d,i) This is my program, it should give me two number lists, one decreasing and the other increasing. For example: d=60 i=40 it should print: 100 0 40 40 40 80 instead it prints: 100 0 100 40 100 80 40 0 40 40 40 80
downvote count: 1
has answer: http://stackoverflow.com/a/49243180
accepted answer: http://stackoverflow.com/a/49243180
favorite count: 0
type: Question
upvote count: 0
answer count: 1
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85490139

http://stackoverflow.com/a/49127768
accepted answer of: http://stackoverflow.com/q/49127546
upvote count: 1
has comment: http://stackoverflow.com/comment/85260324
answers question: http://stackoverflow.com/q/49127546
score: 1
type: Answer
has body: For the easiest solution to your problem, @Chris_Rands already posted it in a comment to your question: .split() returns a list. You don't have to make a separate one for the result, just enumerate the value returned by the split function: inputwords = input('What keywords are you looking for?').split() result = list(enumerate(inputwords)) print(result) What keywords are you looking for? This is a list of words. [(0, 'This'), (1, 'is'), (2, 'a'), (3, 'list'), (4, 'of'), (5, 'words.')] As noted in the other answer, it is a good idea to put a space after your prompt, that way there is separation between it and what the user is typing in: inputwords = input('What keywords are you looking for? ').split() Your code will not work with python2 though, where the input() function is actually running the resulting string through eval(): &gt;&gt;&gt; input() 1 + 2 + 3 6 For more information, see this question. If you want your code to be compatible with both python2 and python3, use this little snippet: try: input = raw_input except NameError: pass This will make sure that input is pointing to the python3 version of the function.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85503117
type: QuestionComment
has text: shouldn't this just be `self.destroy= lambda num : self.destroywidgets(num)` ?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49249731

http://stackoverflow.com/q/49267808
tagged with: python
type: Question
score: 1
accepted answer: http://stackoverflow.com/a/49280741
answer count: 1
downvote count: 0
has title: Use value from previous edge
has answer: http://stackoverflow.com/a/49280741
upvote count: 1
tagged with: amazon-neptune
tagged with: gremlin
favorite count: 0
has body: I'm using Gremlin Python, latest available on pip, on OSX for a DB hosted on AWS Neptune. I would like to use a value from a previously traversed edge. Example is better than 10 lines of explanation. g.V(2).outE().values('stop_timestamp').store('stop_ts').inV().outE().where(has('start_ts', between('stop_ts', end_ts))) I would like to use the stop_ts value (just an Int) and use it inside the between statement. Currently I only have error like: gremlin_python.driver.protocol.GremlinServerError: 597: Exception processing a script on request I think it's not possible to use a value from a previously traversed edge, would be a shame but I would need a confirmation. EDIT: It seems that neq &amp; eq doesn't crash but not between, gte, lte (as between is just translated to gte and lte)
type: AnsweredQuestion

http://stackoverflow.com/a/49211548
answers question: http://stackoverflow.com/q/49211458
has body: You can use regex: import re s = ['Renewables\n', '17.9% (3,951 MW)\n'] s1 = ['Solar\n', '27.4% (1,081 MW)\n', 'LATEST SYSTEM\n', 'GENERATION\n', '4,738 MW\n', 'THERMAL GENERATION\n', '(COAL, GAS, OTHER)\n', '54 %\n', 'RENEWABLE\n', 'GENERATION\n', '47.61 %\n'] final_results = [float(re.findall('\d+\.\d+(?=\%)|\d+\.\d+(?=\s\%)', i[-1])[0]) for i in [s, s1]] Output: [17.9, 47.61]
accepted answer of: http://stackoverflow.com/q/49211458
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/q/49159130
type: UnansweredQuestion
tagged with: regression
tagged with: scikit-learn
tagged with: python
tagged with: matlab
score: 0
has answer: http://stackoverflow.com/a/49159455
answer count: 1
has title: MATLAB mapminmax function in Python?
has body: Summary: I normalized my data for a linear regression model and I would like to reverse the normalization back to original values: I have the following function to reverse back the normalized data in MATLAB: Y_Pred_denorm=(mapminmax('reverse','Y_pred',params.Y))'; How can I write this code in Python ? I did some reading and came up with the following which throws an error: from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler(feature_range=(60, 90)) Y_Pred_denorm = Y_Pred.reshape(-1, 1) new_Y = scaler.fit_transform(60, 90)
type: Question

http://stackoverflow.com/a/49129742
type: Answer
answers question: http://stackoverflow.com/q/49128260
has body: You don't return anything from Random Value. That is why ${ran} remains None. You have to return a value from Random Value: Random Value [Arguments] ${x_boundry} ${y_boundry} ${output} Evaluate random.randint(${x_boundry},${y_boundry}) random [Return] ${output}
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49128260
score: 1

http://stackoverflow.com/comment/85428675
score: 0
comment on: http://stackoverflow.com/q/49211611
has text: I meant to say that I am unfamiliar with Pandas and how I would go about to create the dummy dates and set they as the key for the dataframe. As I had attempted it yesterday and today and was not successful I decided to post the question on SO.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85442162
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. Can you also add sample of second Dataframe and expected output?
type: Comment
comment on: http://stackoverflow.com/q/49219233
score: 1
type: QuestionComment

http://stackoverflow.com/comment/85452822
type: QuestionComment
has text: @jordi, thank you so much, I am a new member to the stackoverflow community and greatly appreciate your help. I'll run the code soon and see how that fits in.
comment on: http://stackoverflow.com/q/49222798
score: 0
type: Comment

http://stackoverflow.com/comment/135230392
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/73395648
has text: Thanks for the tip about metastack. I wrote some example code (without dill) https://stackoverflow.com/a/76686521/360265
type: Comment

http://stackoverflow.com/comment/85487223
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49240698
type: Comment
has text: Added an example of batch script I use, it just runs a python file and passes it two variables

http://stackoverflow.com/q/49252160
upvote count: 1
has body: I've seen a number of questions asking how to check if a float is an integer. Majority of answers seem to recommend using is_integer(): (1.0).is_integer() (1.55).is_integer() I have also occasionally seen math.floor() being used: import math 1.0 == math.floor(1.0) 1.55 == math.floor(1.55) I'm wondering why % 1 is rarely used or recommended? 1.0 % 1 == 0 1.55 % 1 == 0 Is there a problem with using modulo for this purpose? Are there edge cases that this doesn't catch? Performance issues for really large numbers? If % 1 is a fine alternative, then I'm also wondering why is_integer() was introduced to the standard library? It seems that % is much more flexible. For example, its common to use % 2 to check if a number is odd/even, or % n to check if something is a multiple of n. Given this flexibility, why introduce a new method (is_integer) that does the same thing, or use math.floor, both of which require knowing/remembering that they exist and knowing how to use them? I know that math.floor has uses beyond just integer checking but still...
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85507843
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49252354
accepted answer: http://stackoverflow.com/a/49252407
has comment: http://stackoverflow.com/comment/85507661
has answer: http://stackoverflow.com/a/49252407
type: AnsweredQuestion
has title: Check if float is an integer: is_integer() vs. modulo 1
answer count: 2
possible better answer: http://stackoverflow.com/a/49252354
has comment: http://stackoverflow.com/comment/85507763
downvote count: 0

http://stackoverflow.com/q/49276039
has comment: http://stackoverflow.com/comment/85573717
has comment: http://stackoverflow.com/comment/85554918
linked to: http://stackoverflow.com/q/49290059
tagged with: apply
has comment: http://stackoverflow.com/comment/85647882
favorite count: 0
type: Question
has body: I have a question how to efficiently apply a function which takes an m-dimensional slice of a n-dimensional array as an input. For example, I have a n-dimensional array of shape (i,j,k,l). And on the dimensions (j,l), I want to apply the function, which gives me back a matrix of shape (j,l). The resulting numpy array should again have the shape (i,j,k,l). For example I want to apply the following, normalisation function def norm(arr2d): return arr2d - np.mean(arr2d) over the array arrnd = np.arange(2*3*4*5).reshape(2,3,4,5) # Shape is (2,3,4,5) on the slice (j,l). The result I want to achieve I would get via a (slow?) Python list comprehension and moving axes. result = np.asarray([ [ f(arrnd[:,j,:,l]) for l in range(5) ] for j in range(3)]) # Shape is (3,5,2,4) result = np.moveaxis(np.moveaxis(result,2,0),2,3).shape # Shape is (2,3,4,5) again Is there any better, more "numpyic" way to achieve this, without any involved loops? I alreay looked at np.apply_along_axis() and np.apply_over_axes() but the former only works for 1-d functions, and the latter might only work, if my function is implemented as a ufunc. The example I provided is just a toy example. The solution should work for any python function. ((If normalising a slice would be my specific problem, I could have circumenvented the python loop and moveaxis by using the ufunc's axes=(..).))
tagged with: numpy
tagged with: dimensions
linked to: http://stackoverflow.com/q/48996893
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85570765
has comment: http://stackoverflow.com/comment/85554512
tagged with: python
score: 4
upvote count: 4
has title: Applying a multi-dimensional function over multi-dimensional array (Python, Numpy)
answer count: 0
downvote count: 0

http://stackoverflow.com/comment/85375202
score: 0
comment on: http://stackoverflow.com/q/49184639
type: Comment
has text: You don't have to write the stdout of your program to a file, a much better way to do this would be to open a file and write the str representation of your random number to this. This is googleable, but I, unlike some, understand that you may have been thinking about this the wrong way and your googling came up with nothing.
type: QuestionComment

http://stackoverflow.com/comment/85505813
type: QuestionComment
comment on: http://stackoverflow.com/q/49251023
type: Comment
has text: But on my console on the xcode, I did not get anything but that error message I just sent in the post. @Malik
score: 0

http://stackoverflow.com/q/49178372
downvote count: 4
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/85362354
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49179219
has answer: http://stackoverflow.com/a/49178514
tagged with: bioinformatics
type: UnansweredQuestion
score: -3
has body: def translat_dna(sequence): gencode= { 'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M', 'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T', 'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K', 'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R', 'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L', 'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P', 'CAC':'H', 'CAT':'H', 'CAA':'Q', 'CAG':'Q', 'CGA':'R', 'CGC':'R', 'CGG':'R', 'CGT':'R', 'GTA':'V', 'GTC':'V', 'GTG':'V', 'GTT':'V', 'GCA':'A', 'GCC':'A', 'GCG':'A', 'GCT':'A', 'GAC':'D', 'GAT':'D', 'GAA':'E', 'GAG':'E', 'GGA':'G', 'GGC':'G', 'GGG':'G', 'GGT':'G', 'TCA':'S', 'TCC':'S', 'TCG':'S', 'TCT':'S', 'TTC':'F', 'TTT':'F', 'TTA':'L', 'TTG':'L', 'TAC':'Y', 'TAT':'Y', 'TAA':'_', 'TAG':'_', 'TGC':'C', 'TGT':'C', 'TGA':'_', 'TGG':'W', } proteinseq='' for n in range(0,len(gencode),3): if sequence[n:n+3] in gencode: proteinseq += gencode[sequence[n:n+3]: sequence='' return proteinseq in translat_dna()
tagged with: python
has title: I am writing a program for converting DNA to protein, I am not get idea to creat help me to get through it,

http://stackoverflow.com/comment/85509096
type: QuestionComment
has text: My bad, I should have seen it.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49251322

http://stackoverflow.com/q/49249356
has body: I've successfully pulled data from IB using the api. It comes in XML format and it looks like this... 239176000000.000000 229234000000.000000 223507000000.000000 0.630000 0.630000 2.400000 0.630000 0.630000 0.630000 3.920000 2.090000 9.270000 </FinancialSummary> I want to convert this information to CSV format in this format: total revenue report type period rev dividendpershare period div 2017-12-31 239176000000 ttm 12m 0.630000 3m 2017-09-30 229234000000 ttm 12m 0.630000 3m is there an easy way to do this?
has comment: http://stackoverflow.com/comment/85502098
has title: parsing interactive broker fundamental data
favorite count: 0
type: Question
type: UnansweredQuestion
score: -2
tagged with: python
has answer: http://stackoverflow.com/a/49259620
downvote count: 3
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85502153

http://stackoverflow.com/a/49250081
has body: So I have make it work like this: class Test(): def __init__(self, master): self.destroy= lambda num : self.destroywidgets(num) def destroywidgets(self,num): if num == 1: print 1 elif num == 2: print 2 elif num == 3: print 3 def func1(self): self.destroy(1) def func2(self): self.destroy(2) a = Test(1) a.func1() # 1 a.func2() # 2 The only issue here is that I don't get where the master attribute goes, but this solution allows for the self.destroy function to be created and reply to the input number
answers question: http://stackoverflow.com/q/49249731
has comment: http://stackoverflow.com/comment/85503591
has comment: http://stackoverflow.com/comment/85503622
has comment: http://stackoverflow.com/comment/85503824
has comment: http://stackoverflow.com/comment/85503771
score: 0
has comment: http://stackoverflow.com/comment/85503606
has comment: http://stackoverflow.com/comment/85503966
type: Answer

http://stackoverflow.com/q/49271555
has answer: http://stackoverflow.com/a/49271742
accepted answer: http://stackoverflow.com/a/49271865
tagged with: python
has answer: http://stackoverflow.com/a/49271865
type: AnsweredQuestion
score: 0
answer count: 2
has body: I tried to follow along Martin Gorner's lecture on using TensorFlow and also the tutorial at the official TensorFlow documentation. I'm confused why on Gorner's lecture, he used the negative sum of the dot product between the labels and the predictions. But in the TensorFlow tutorial, it uses the same method, but then divides it to get the mean for each minibatch. Basically both will work as long as you scale the learning rate, but I don't understand the reason for the difference in methods.
tagged with: tensorflow
possible better answer: http://stackoverflow.com/a/49271742
has title: Mean of minibatch cross-entropy to optimize in tensorflow
type: Question

http://stackoverflow.com/q/49160381
accepted answer: http://stackoverflow.com/a/49161552
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49161552
type: Question
has answer: http://stackoverflow.com/a/49160473
has title: Django model's clean() method not raising the expected ValidationErrors for individual fields
has body: I have a Django model called CheckIn with (among others) two fields, min_weeks and max_weeks. I would like to build in validation such that min_weeks is always less than or equal to max_weeks. Following https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddo#django.db.models.Model.clean (in particular, the last example in which the ValidationError is passed a dictionary which maps fields to errors), I tried the following clean() method: from django.db import models from django.core.exceptions import ValidationError class CheckIn(models.Model): min_weeks = models.IntegerField(blank=True, null=True) max_weeks = models.IntegerField(blank=True, null=True) def clean(self): if self.min_weeks > self.max_weeks: raise ValidationError({ 'min_weeks': ValidationError("'min_weeks' should be smaller than 'max_weeks'", code='invalid'), 'max_weeks': ValidationError("'max_weeks' should be greater than 'min_weeks'", code='invalid')}) The model is used in a ModelForm: class CheckInForm(forms.ModelForm): class Meta: model = CheckIn fields = [ 'min_weeks', 'max_weeks', ] The fields are displayed manually in the template. Here is an excerpt: {% if check_in_type and not form.min_weeks.value %} {{ check_in_type.min_weeks }} mode_edit Min Weeks {% endif %} {{ form.min_weeks.errors }} {% if check_in_type and not form.max_weeks.value %} {{ check_in_type.max_weeks }} mode_edit Max Weeks {% endif %} {{ form.max_weeks.errors }} Note that there is some additional logic in here to 'inherit' values from the CheckIn's CheckInType if they are not provided explicitly. By and large, though, the template is just displaying form.min_weeks and form.max_weeks and the corresponding errors. The problem is that if I enter invalid value for min_weeks and max_wee…
type: AnsweredQuestion
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/126093423
has comment: http://stackoverflow.com/comment/85331469
possible better answer: http://stackoverflow.com/a/49160473
answer count: 2
linked to: http://stackoverflow.com/q/16633813
tagged with: validation
downvote count: 0
tagged with: django

http://stackoverflow.com/a/49214655
accepted answer of: http://stackoverflow.com/q/49214474
score: 2
upvote count: 2
downvote count: 0
has body: First you need to have the bar positions and widths on the same scale. So you would probably want to create a twinx axes instead of twiny. (You can still use ax.set_ylim(ax2.get_ylim()) to get the y scale equal as well.) Then, in case there are as many bars in the primary axes as in the twin axes, we have a one-to-one correspondance and can calculate the black bars' positions depending on the colored bars' positions. for bbar, cbar in zip(ax.patches, ax2.patches): cpos = cbar.get_x()+cbar.get_width()/2. bpos = cpos-bbar.get_width()/2. bbar.set_x(bpos) The complete code, producing the above plot: from io import StringIO import pandas as pd import matplotlib.pyplot as plt txt = u'''Category COLUMN1 COLUMN2 COLUMN3 A 0.5 3 Cat1 B 0.3 5 Cat1 C 0.7 4 Cat1 A 0.4 3 Cat2 B 0.8 5 Cat2 C 0.3 4 Cat2 ''' df = pd.read_table(StringIO(txt), sep="\s+") order = ['Cat1', 'Cat2'] fig, ax = plt.subplots() ax2 = ax.twinx() col1 = pd.pivot_table(df,index='COLUMN3',columns='Category',values='COLUMN1').reindex(order) col1.plot(kind='bar', ax=ax, edgecolor='Black', lw=1, color='black', width=0.2) col2 = pd.pivot_table(df,index='COLUMN3',columns='Category',values='COLUMN2').reindex(order) col2.plot(kind='bar', ax=ax2, legend=False, alpha=0.7) ax2.xaxis.set_visible(False) ax.set_ylim(ax2.get_ylim()) for bbar, cbar in zip(ax.patches, ax2.patches): cpos = cbar.get_x()+cbar.get_width()/2. bpos = cpos-bbar.get_width()/2. bbar.set_x(bpos) plt.show()
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85434041
answers question: http://stackoverflow.com/q/49214474
type: Answer
has comment: http://stackoverflow.com/comment/85433804

http://stackoverflow.com/comment/85321114
type: AnswerComment
comment on: http://stackoverflow.com/a/49157510
has text: removed the qeryset as you seggested and added the base_name: router.register(r'results/(?P<nome_ficheiro>.+)/$', resultUploadView.as_view({'get': 'get_queryset'}), base_name='img_name') but i keep getting the same error..
score: 0
type: Comment

http://stackoverflow.com/q/49182189
tagged with: ogr
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/86827531
tagged with: python
has comment: http://stackoverflow.com/comment/85424527
has answer: http://stackoverflow.com/a/70818630
tagged with: gdal
has body: I'm running Python 2.7 on Ubuntu 17.10, with osgeo v2.2.1 installed via apt. My code loads osgeo and 1) tries to create a shapefile with 1 layer and 1 field, 2) create a polygon (4 points geometry), then 3) add the polygon to the shapefile's layer. Everything runs without trouble until the third function when I use layer.CreateFeature(feature) : driver = ogr.GetDriverByName('ESRI Shapefile') ds = driver.Open(shapefile_name,-1) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) layer = ds.GetLayer() print "layer",layer,", number of features :",layer.GetFeatureCount() This prints : layer &lt;osgeo.ogr.Layer; proxy of &lt;Swig Object of type 'OGRLayerShadow *' at 0x7f79aa499c90&gt; &gt; , number of features : 0 I then create a geometry from the polygon I already created and passed to the function beforehand : defn = layer.GetLayerDefn() geom = ogr.CreateGeometryFromWkb(poly) print "geom",geom This prints : geom POLYGON ((-106 24 0,-100 26 0,-103 20 0,-106 20 0)) Code then goes on to create the feature : feat = ogr.Feature(defn) feat.SetField('polygon_id', polygon_name) feat.SetGeometry(geom) print feat print "Created feature",feat.GetField('polygon_id') This feature is created : &lt;osgeo.ogr.Feature; proxy of &lt;Swig Object of type 'OGRFeatureShadow *' at 0x7f35cd988d50&gt; &gt; Created feature polygon_1 But when I add it to the layer, nothing happens : layer.CreateFeature(feat) print "number of features : ",layer.GetFeatureCount() Prints : number of features : 0 What did I miss ?
has comment: http://stackoverflow.com/comment/92783720
tagged with: osgeo
score: 1
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85389098
upvote count: 1
tagged with: gis
favorite count: 0
has title: GDAL CreateFeature doesn't add a Feature to the Layer
type: Question
has comment: http://stackoverflow.com/comment/91481620

http://stackoverflow.com/a/49269740
downvote count: 0
has body: In [435]: ref = np.array([[1,0],[0,1]]) In [436]: index = np.array([1.,1.,1.,0.,1.]) Indexing with floats gives an error in recent versions: In [437]: ref[index,:] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-437-d50c95668d6c&gt; in &lt;module&gt;() ----&gt; 1 ref[index,:] IndexError: arrays used as indices must be of integer (or boolean) type Index with integers, select rows from ref depending on the index value: In [438]: ref[index.astype(int),:] Out[438]: array([[0, 1], [0, 1], [0, 1], [1, 0], [0, 1]]) This is a case where choose could be used, but it's pickier about array shapes than the above indexing: In [440]: np.choose(index.astype(int)[:,None],[[1,0],[0,1]]) Out[440]: array([[0, 1], [0, 1], [0, 1], [1, 0], [0, 1]]) or with only 2 choices that convert to boolean, where: In [443]: np.where(index.astype(bool)[:,None],[0,1],[1,0]) Out[443]: array([[0, 1], [0, 1], [0, 1], [1, 0], [0, 1]])
score: 2
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/49269042

http://stackoverflow.com/a/49121519
score: 0
has body: If you are looking for the print statement to literally say 4sqrt(2) then no, its very complex write a function to convert your answer to root form, and 99.9% time not worth it. The float means you are ensuring the type of bulma(x, y, z, t). Floats are floating point decimals.
type: Answer
answers question: http://stackoverflow.com/q/49121458

http://stackoverflow.com/comment/85551357
type: QuestionComment
score: 0
has text: One option is HDF5, read up on [h5py docs](http://docs.h5py.org/en/latest/). There are freeware readers to open up & view data [not python dependent] and this is a much better option than csv since data types are maintained.
type: Comment
comment on: http://stackoverflow.com/q/49274426

http://stackoverflow.com/comment/138996342
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49153387
has text: As a newer option, there is also my https://pypi.org/project/tabxlsx - it is a single script that can be copy-n-pasted to any place. It can read the basic data types - it can also wirte xlsx when no extra cell formatting is required.

http://stackoverflow.com/q/49134493
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 0
has title: Excess '4' occurs in the end of number when summing negative floats
upvote count: 2
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/11950819
tagged with: python
linked to: http://stackoverflow.com/q/588004
downvote count: 1
duplicate of: http://stackoverflow.com/q/588004
has comment: http://stackoverflow.com/comment/85273590
score: 1
linked to: http://stackoverflow.com/q/11950819
has body: For example: In: -0.01 + (-0.02) + (-0.4) + (-0.05) Out: -0.48000000000000004 Instead of -0.48 Why does it happen so? And how to avoid such situations?

permissions
tag name: permissions
tags question: http://stackoverflow.com/q/49175172
type: Tag

http://stackoverflow.com/a/49200323
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49200245
upvote count: 2
downvote count: 0
type: Answer
has body: If you look at the Chebyshev docs, you'll find that the first argument is the coefficients, not the domain. The domain is the optional second argument. For example, np.polynomial.Chebyshev([0, 3]) is 0*T_0 + 3*T_1.
score: 2
accepted answer of: http://stackoverflow.com/q/49200245

pykafka
tag name: pykafka
type: Tag
tags question: http://stackoverflow.com/q/49268963

http://stackoverflow.com/a/49255686
has comment: http://stackoverflow.com/comment/85516723
has comment: http://stackoverflow.com/comment/85514532
type: Answer
has comment: http://stackoverflow.com/comment/85515285
has comment: http://stackoverflow.com/comment/85516492
has comment: http://stackoverflow.com/comment/85514771
has comment: http://stackoverflow.com/comment/85514629
downvote count: 0
has comment: http://stackoverflow.com/comment/85515770
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85515645
answers question: http://stackoverflow.com/q/49255609
has comment: http://stackoverflow.com/comment/85515497
has body: You need resample with first, but for exactly same values is necessary convert all values to strings by dtype=str in read_csv: df = pd.read_csv(file, dtype=str) df['Timestamp'] = pd.to_datetime(df['Timestamp'], unit='s') df = (df.set_index('Timestamp') .resample('15T').first() .reset_index() .reindex(columns=df.columns)) df['Timestamp'] = df['Timestamp'].astype(np.int64) // 10**9 print (df) Close Timestamp High Low Open \ 0 1006.54999992 1483304400 1006.54999997 1004.00000002 1005.84692623 1 1002.69522396 1483305300 1003.50000156 1002.03739724 1003.50000156 2 1004.9 1483306200 1004.9 1003.50000155 1003.50000155 3 1007.98333891 1483307100 1008.151 1006.54999328 1006.99999999 4 1007.18578657 1483308000 1007.4 1004.79999999 1005.99999939 5 1005.99669899 1483308900 1007.40360648 1001.84692611 1001.84692611 6 1004.99999989 1483309800 1005.99669893 1002.55436881 1003.80404142 7 1004.99999999 1483310700 1005.0 1002.55399997 1004.99999991 8 1004.44444427 1483311600 1005.99999991 1001.84362417 1004.99999999 Volume 0 2686.70823136 1 1066.56568909 2 4978.96836354 3 1357.21576969 4 11867.90775651 5 13223.84822808 6 1519.48804831 7 7791.517061 8 3803.79028496
has comment: http://stackoverflow.com/comment/85516865
has comment: http://stackoverflow.com/comment/85514826
has comment: http://stackoverflow.com/comment/85516731
has comment: http://stackoverflow.com/comment/85516823
score: 5
upvote count: 5
accepted answer of: http://stackoverflow.com/q/49255609
has comment: http://stackoverflow.com/comment/85515051
has comment: http://stackoverflow.com/comment/85514699

http://stackoverflow.com/comment/85374036
comment on: http://stackoverflow.com/a/49183911
has text: `list_1[1][1:1] = 5` is not true. Also you should use `==` and not `=`.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85497427
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49246775
has text: Yes it is. Good point, I didn't think to check it since when I tested it earlier it appeared to be working fine. Full code can be seen here: https://github.com/AdamVen/Capstone/blob/master/__main__

http://stackoverflow.com/q/49155698
tagged with: vectorization
favorite count: 0
score: 1
tagged with: python
has title: How can I vectorize this python function to take an array of points (as pairs of cartesian coordinates)?
type: Question
tagged with: python-3.x
has body: I have this function which checks if a point (passed as pair of cartesian coordinates) is inside the trapezoid (passed as list of tuples of vertices coordinates) def inside(point_coordinates, trapezoid_vertices): x,y = point_coordinates is_inside = False x_1, y_1 = trapezoid_vertices[0] for i in range(1, 4): x_2, y_2 = trapezoid_vertices[i] if y &gt; min(y_1, y_2): if y &lt;= max(y_1, y_2): if x &lt;= max(x_1, x_2): if y_1 != y_2: x_intersect = (y - y_1) * (x_2 - x_1) / (y_2 -y_1) + x_1 if x_1 == x_2 or x &lt;= x_intersect: is_inside = not is_inside x_1, y_1 = x_2, y_2 return is_inside I want to make it accept a numpy array where each element of the array is a pair of its indices. Then I want it to return an array of bools where the each element is True if the point corresponding to its indices is inside the trapezoid, or False otherwise. For example, a 3x3 array of what I want to pass to the function looks like this: a = [[[0 0] [0 1] [0 2]] [[1 0] [1 1] [1 2]] [[2 0] [2 1] [2 2]]] And what I want the function to return is something like this: [[ True True False] [ True True False] [False False False]] I tried to vectorize the function with inside_vectorized=np.vectorize(inside), but it doesn't seem to work. Running inside_vectorized( a, [(0, 0), (0, 1), (1, 1), (1, 0)] ) gives me a TypeError. --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-12-6d5966fb40d4&gt; in &lt;module&gt;() ----&gt; 1 inside_vectorized(a, [(0, 0), (0, 1), (1, 1), (1, 0)]) /usr/lib/python3/dist-packages/numpy/lib/function_base.py in __call__(self, *args, **kwargs) 2205 vargs.extend([kwargs[_n] for _n in names]) 2206 -&gt; 2207 return self._vectorize_call(func=func, args=vargs) 2208 2209 def _get_ufunc_and_otypes(self, func, args): /usr/lib/python3/dist-packages/numpy/lib/function_base.py in _vectorize_call(self, func, args) 2268 _res = func() 2269 else: -&gt; 2270 ufunc, otypes = self._get_ufunc_and_otype…
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85323395
downvote count: 0
has comment: http://stackoverflow.com/comment/85360058
upvote count: 1

http://stackoverflow.com/comment/85443037
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49216896
has text: Hi @H.Tibat, I have set up all of the required SMTP settings but `send_mail` method doesn't provide a way to attach a file.To attach a file I think we need to use EmailMessage which is not working anyhow.
type: Comment

http://stackoverflow.com/q/49270953
has answer: http://stackoverflow.com/a/49272734
score: 0
tagged with: selenium
has body: expand_more expand_more Intro Enrolment Disclaimer Admission Requirements Program Requirements Professional Outcomes Recognition of Achievement Program Fees I am kind of new to robot framework. I am trying to retrieve the value from the href anchor tag value that is Intro using the following xpath //*[@id="pageNavContainer"]/div/div/a[2]/@href But when I run the script to get the text with the above xpath I am getting the below error: InvalidSelectorException: Message: invalid selector: The result of the xpath express I tried using getattribute also but it didn't work. Can anyone please help me out what is the correct xpath for this? Thanks in advance
has title: Robot Framework anchor tag value is not retrieved
tagged with: xpath
has answer: http://stackoverflow.com/a/49272430
tagged with: robotframework
type: Question
has comment: http://stackoverflow.com/comment/85557482
answer count: 2
tagged with: python
type: UnansweredQuestion
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/85544925

http://stackoverflow.com/comment/85322071
type: Comment
has text: True and thank you again Mike hope you will see the new Question - How do i close this topic :( Can't see the option or i might be the 10 hours staring at code :)
comment on: http://stackoverflow.com/a/49156032
score: 0
type: AnswerComment

http://stackoverflow.com/q/49241306
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49241556
tagged with: python
has body: Looking into annotations (using Python 3.6.4), I tried from typing import * and noticed that NoReturn was not imported. issue28556 added NoReturn to the typing library, but it's missing from the __all__ list in the 3.6 and 3.7 cpython sources. Was this a deliberate omission? Is NoReturn harmful in some way that warrants this omission?
score: 0
answer count: 1
has title: Why is NoReturn missing from __all__ in Python 3
tagged with: python-typing
type: Question

http://stackoverflow.com/q/49258892
answer count: 2
has answer: http://stackoverflow.com/a/76406080
has body: I have a problem, I was working on a code with python 3. the code is about getting news of a website onto my canvas. however I keep getting this error which says: AttributeError: 'NewsFeed' object has no attribute 'canvas'. this is my code: from tkinter import * import feedparser root=Tk() class Achtergrond() : m_Width = 0 m_Height = 0 m_BgColor = 0 def CreateCanvas(self, master, width, height) : m_Width = width m_Height = height m_BgColor='#14B4E1' self.canvas = Canvas(master, width=m_Width, height=m_Height) self.canvas.configure(bg=m_BgColor) self.canvas.pack() return(self.canvas) def create_rectangle(x0, y0 ,x1,y1, color) : self.canvas.create_rectangle(x0, y0, x1, y1, fill=color) return def create_title (self, x, y, title, opmaak): self.canvas.create_text(x,y,text=title, font= opmaak) return def create_newsbox(master,x0,y0,x1,y1,color): canvas.create_rectangle(x0,y0,x1,y1, fill=color) return def SetBackgroundColor(self, kleurcode) : m_BgColor = kleurcode self.canvas.configure(bg=m_BgCode) self.canvas.pack() return class NewsFeed (): Hitem = 0 Nitem = 0 feed = 0 th = 0 rssURL = "" def UpdateNews(self,path): self.rssURL = path self.feed = feedparser.parse(self.rssURL) self.Nitem = len(self.feed["items"]) return def ToonEerste(self): str="" self.Hitem = 0 for i in range(self.Hitem,self.Hitem+2,1): if i &lt; self.Nitem: entry = self.feed["entries"][i] str += entry.title + "\n\n" + entry.summary + "\n__________________________________________________\n\n" self.canvas.delete(th) th = self.canvas.create_text(200,300, width=300, text = str) return def ToonVolgende(self): str="" self.Hitem += 3 if self.Hitem &gt;= self.Nitem: Hitem = 0 for i in range(self.Hitem,self.Hitem+2,1): if i &lt; self.Nitem: entry = feed["entries"][i] str += entry.title + "\n\n" + entry.summary + "\n__________________________________________________\n\n" self.canvas.delete(th) th = self.canvas.create_text(200,300, width=300, text = str) return hoofdscherm = Achtergrond() a = hoofdscherm.CreateCanv…
has comment: http://stackoverflow.com/comment/85521520
has comment: http://stackoverflow.com/comment/85521217
favorite count: 0
tagged with: attributes
type: Question
tagged with: tkinter
upvote count: 2
has comment: http://stackoverflow.com/comment/85521289
downvote count: 2
accepted answer: http://stackoverflow.com/a/49261686
has comment: http://stackoverflow.com/comment/85520859
has comment: http://stackoverflow.com/comment/85525535
has title: AttributeError: '' object has no attribute ''
tagged with: python
has answer: http://stackoverflow.com/a/49261686
tagged with: class
has comment: http://stackoverflow.com/comment/85521069
possible better answer: http://stackoverflow.com/a/76406080
type: AnsweredQuestion
tagged with: object
score: 0

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/49178331
tags question: http://stackoverflow.com/q/49228728
type: Tag

opencv
tags question: http://stackoverflow.com/q/49248824
type: Tag
tags question: http://stackoverflow.com/q/49225274
tags question: http://stackoverflow.com/q/49126929
tags question: http://stackoverflow.com/q/49140965
tags question: http://stackoverflow.com/q/49138457
tags question: http://stackoverflow.com/q/49191615
tags question: http://stackoverflow.com/q/49162364
tags question: http://stackoverflow.com/q/49264011
tags question: http://stackoverflow.com/q/49182881
tags question: http://stackoverflow.com/q/49199066
tags question: http://stackoverflow.com/q/49213553
tags question: http://stackoverflow.com/q/49188279
tags question: http://stackoverflow.com/q/49216551
tags question: http://stackoverflow.com/q/49219537
tags question: http://stackoverflow.com/q/49235611
tags question: http://stackoverflow.com/q/49221892
tags question: http://stackoverflow.com/q/49192936
tags question: http://stackoverflow.com/q/49274048
tags question: http://stackoverflow.com/q/49147937
tags question: http://stackoverflow.com/q/49168804
tags question: http://stackoverflow.com/q/49209918
tags question: http://stackoverflow.com/q/49217587
tags question: http://stackoverflow.com/q/49162657
tags question: http://stackoverflow.com/q/49180006
tags question: http://stackoverflow.com/q/49278087
tags question: http://stackoverflow.com/q/49225778
tags question: http://stackoverflow.com/q/49157680
tags question: http://stackoverflow.com/q/49170964
tags question: http://stackoverflow.com/q/49135755
tags question: http://stackoverflow.com/q/49126955
tags question: http://stackoverflow.com/q/49163935
tags question: http://stackoverflow.com/q/49257738
tags question: http://stackoverflow.com/q/49238724
tags question: http://stackoverflow.com/q/49143267
tags question: http://stackoverflow.com/q/49162915
tags question: http://stackoverflow.com/q/49160559
tags question: http://stackoverflow.com/q/49163975
tags question: http://stackoverflow.com/q/49147471
tags question: http://stackoverflow.com/q/49148166
tags question: http://stackoverflow.com/q/49191221
tags question: http://stackoverflow.com/q/49201570
tags question: http://stackoverflow.com/q/49269327
tags question: http://stackoverflow.com/q/49145154
tags question: http://stackoverflow.com/q/49157989
tags question: http://stackoverflow.com/q/49230981
tags question: http://stackoverflow.com/q/49272356
tags question: http://stackoverflow.com/q/49265735
tags question: http://stackoverflow.com/q/49184042
tags question: http://stackoverflow.com/q/49236146
tag name: opencv
tags question: http://stackoverflow.com/q/49267010
tags question: http://stackoverflow.com/q/49211307
tags question: http://stackoverflow.com/q/49237117
tags question: http://stackoverflow.com/q/49133484
tags question: http://stackoverflow.com/q/49147792
tags question: http://stackoverflow.com/q/49261615
tags question: http://stackoverflow.com/q/49205051
tags question: http://stackoverflow.com/q/49215611

http://stackoverflow.com/comment/85328716
type: QuestionComment
has text: I got this error: C:/Program : The term 'C:/Program' is not recognized as the name of a cmdlet, function,
comment on: http://stackoverflow.com/q/49160818
score: 0
type: Comment

http://stackoverflow.com/comment/85388249
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49191309
has text: If I put a print statement under the open line, it prints twice, although there are definitely many read-writes between the 2 opens and one close.

pytables
tags question: http://stackoverflow.com/q/49232724
type: Tag
tag name: pytables

http://stackoverflow.com/comment/85289533
comment on: http://stackoverflow.com/q/49142021
has text: Yes, you are missig the `requests` module, apparently... It's a popular one, but it isn't part of the standard library.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49255859
has comment: http://stackoverflow.com/comment/85514720
answers question: http://stackoverflow.com/q/49255775
score: 0
has comment: http://stackoverflow.com/comment/85514679
type: Answer
has body: This is one way. groupby.apply(list) will aggregate all the internalnotes per group into a list. group_cols = ['CaseNumber', 'ProcessInstanceDescription', 'ProdOpsCaseOwner', 'personname', 'SNLAnalystEntryDesc'] ans_new = ans_new.groupby(group_cols)['internalnotes'].apply(list).reset_index() If you really want to join strings, as @jezrael suggests, and remove all knowledge of the fact the values came from different rows: ans_new = ans_new.groupby(group_cols)['internalnotes'].apply(' '.join).reset_index()

http://stackoverflow.com/a/49254651
answers question: http://stackoverflow.com/q/49254588
has comment: http://stackoverflow.com/comment/93524871
type: Answer
has body: Put single quote around %s Because username is a String result = cur.execute("SELECT * FROM users WHERE username = '%s'"%str(username)) if result.rowcount &gt;0 Corretion cur = conn.cursor() result = cur.execute("SELECT * FROM users WHERE username = %s", [username]) data = cur.fetchone() if result.rowcount &gt; 0: password = data['password'] if sha256_crypt.verify(password_given, password): app.logger.info('PASSWORD MATCHED') else: app.logger.info('PASSWORD Not MATCHED')
has comment: http://stackoverflow.com/comment/85512861
has comment: http://stackoverflow.com/comment/85546295
score: 0
has comment: http://stackoverflow.com/comment/85513525
has comment: http://stackoverflow.com/comment/85513759
has comment: http://stackoverflow.com/comment/85512890
has comment: http://stackoverflow.com/comment/85512616
has comment: http://stackoverflow.com/comment/85513135
has comment: http://stackoverflow.com/comment/85514469

http://stackoverflow.com/comment/85549808
has text: Nailed! Thank you
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49272654
type: AnswerComment

http://stackoverflow.com/comment/85608692
type: Comment
score: 0
has text: it just belongs to one cluster, it is just repeated.
type: QuestionComment
comment on: http://stackoverflow.com/q/49272209

http://stackoverflow.com/comment/85276705
comment on: http://stackoverflow.com/a/49132635
score: 0
type: Comment
has text: "Knowing that, your final statements are clearly outside the loop body." Yes, but where are they, then? If the last lines are indented with 4 spaces, and the rest with tabs (i.e. 8 spaces) then those two lines should not be on any valid (previous) level of indentation and hence yield an error.
type: AnswerComment

http://stackoverflow.com/q/49205467
favorite count: 0
has answer: http://stackoverflow.com/a/49205484
type: Question
upvote count: 4
answer count: 2
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/49216930
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85419021
has comment: http://stackoverflow.com/comment/85422194
tagged with: python
score: 4
tagged with: ubuntu
has title: How to install Visual Studio Code IDE using Anaconda?
tagged with: anaconda
has body: I have a Ubuntu machine. How can I install Visual Studio Code IDE? This is the announcement but couldn't figure out how to install in Ubuntu. https://blogs.msdn.microsoft.com/pythonengineering/2018/02/15/visual-studio-code-is-now-shipping-with-anaconda/ Can I do a conda install?

deep-learning
tags question: http://stackoverflow.com/q/49206869
tags question: http://stackoverflow.com/q/49212526
tags question: http://stackoverflow.com/q/49126007
tags question: http://stackoverflow.com/q/49179549
tags question: http://stackoverflow.com/q/49258492
tags question: http://stackoverflow.com/q/49190288
tags question: http://stackoverflow.com/q/49271691
tags question: http://stackoverflow.com/q/49215615
tags question: http://stackoverflow.com/q/49197016
tags question: http://stackoverflow.com/q/49177169
tags question: http://stackoverflow.com/q/49162202
tags question: http://stackoverflow.com/q/49244066
type: Tag
tags question: http://stackoverflow.com/q/49126004
tags question: http://stackoverflow.com/q/49161652
tags question: http://stackoverflow.com/q/49219958
tags question: http://stackoverflow.com/q/49252970
tags question: http://stackoverflow.com/q/49148098
tags question: http://stackoverflow.com/q/49206650
tags question: http://stackoverflow.com/q/49188148
tags question: http://stackoverflow.com/q/49124814
tags question: http://stackoverflow.com/q/49200276
tags question: http://stackoverflow.com/q/49184241
tags question: http://stackoverflow.com/q/49212257
tags question: http://stackoverflow.com/q/49240338
tags question: http://stackoverflow.com/q/49278571
tags question: http://stackoverflow.com/q/49251642
tags question: http://stackoverflow.com/q/49278504
tags question: http://stackoverflow.com/q/49163097
tags question: http://stackoverflow.com/q/49160481
tags question: http://stackoverflow.com/q/49183229
tags question: http://stackoverflow.com/q/49124622
tags question: http://stackoverflow.com/q/49227015
tags question: http://stackoverflow.com/q/49209957
tags question: http://stackoverflow.com/q/49124900
tag name: deep-learning
tags question: http://stackoverflow.com/q/49208326
tags question: http://stackoverflow.com/q/49262623
tags question: http://stackoverflow.com/q/49263487
tags question: http://stackoverflow.com/q/49192536
tags question: http://stackoverflow.com/q/49225326
tags question: http://stackoverflow.com/q/49122339
tags question: http://stackoverflow.com/q/49149699

http://stackoverflow.com/a/49278140
accepted answer of: http://stackoverflow.com/q/49277758
has body: I modified your code to get string values for your data variable. Now you type in the numbers in the entry field separated by space and when you click on the Analyze Data button it saves the entry into your global data variable. The command method of the button is taking care of putting the entry data into that variable. This way there is no need to use the input line anymore. I defined data='' in the beginning to have a global variable. Just as a side note I remark it is not the best practice to rely on global variables. data = '' class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.init_window() def init_window(self): self.master.title("Data Analyzer To Go") self.pack(fill=BOTH, expand=1) analyzeButton = Button(self, text="Analyze Data", command=self.getData) dataPrompt = Label(self, text="Please enter your data") global data self.var=StringVar(self) e = Entry(self, textvariable=self.var) analyzeButton.place(x=150, y=150) e.place(x=125, y=125) dataPrompt.place(x=125, y=100) def getData(self): global data data = self.var.get() root = Tk() root.geometry("400x300") app = Window(root) root.mainloop() # variables #data = input("please enter your data set: ") data = [int(n) for n in data.split(' ')] data.sort() dataLength = len(data) dataInt = list(map(int, data)) dataTotal = sum(dataInt) dataMean = dataTotal / dataLength highNumber = max(data) lowNumber = min(data) dataRange = highNumber - lowNumber
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85559626
answers question: http://stackoverflow.com/q/49277758
type: Answer

foreign-keys
tags question: http://stackoverflow.com/q/49150613
tags question: http://stackoverflow.com/q/49137152
tags question: http://stackoverflow.com/q/49223319
type: Tag
tag name: foreign-keys
tags question: http://stackoverflow.com/q/49214241
tags question: http://stackoverflow.com/q/49131866

http://stackoverflow.com/a/49144157
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85293563
has body: This will achieve what you need , cumsum 1350*2-df.Price.cumsum() Out[304]: 0 1350.00 1 1348.25 2 1344.75 3 1339.25 Name: Price, dtype: float64 After assign it back df.Current=1350*2-df.Price.cumsum() df Out[308]: Price Current 0 1350.00 1350.00 1 1.75 1348.25 2 3.50 1344.75 3 5.50 1339.25
has comment: http://stackoverflow.com/comment/85293613
answers question: http://stackoverflow.com/q/49144138
type: Answer
accepted answer of: http://stackoverflow.com/q/49144138
score: 2
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/49200045
has title: For loop in python to check elements in list
has comment: http://stackoverflow.com/comment/85408762
upvote count: 2
has body: I have this code: keys = ['well done','come on','going to','c','D','m','l','o'] values = ['well','going','come','D'] category = [] for index, i in enumerate(keys): for j in values: if j in i: category.append(j) break if index == len(category): category.append("other") print(category) I am getting this output ['well', 'other', 'come', 'going', 'other', 'D', 'other', 'other'] The expected output is ['well', 'come', 'going', 'other', 'D', 'other','other' 'other'] I'm not sure what's wrong with the code. Any help would be appreciated.
has comment: http://stackoverflow.com/comment/85405823
possible better answer: http://stackoverflow.com/a/49204086
has comment: http://stackoverflow.com/comment/85405181
tagged with: python
accepted answer: http://stackoverflow.com/a/49218197
has comment: http://stackoverflow.com/comment/85405525
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49218197
answer count: 2
has comment: http://stackoverflow.com/comment/85413473
score: 1
has comment: http://stackoverflow.com/comment/85405481
has answer: http://stackoverflow.com/a/49204086
has comment: http://stackoverflow.com/comment/85405663
has comment: http://stackoverflow.com/comment/85405634
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85630964
has comment: http://stackoverflow.com/comment/85405710

http://stackoverflow.com/q/49279202
type: Question
has body: Good morning, everyone, I tried to import image logo.gif but got an error message saying the image does not exit. Appreciate your help. Dennis from PIL import Image, ImageChops from PIL.GifImagePlugin import getheader, getdata img = Image.open("logo.gif") img.show() from tkinter import * window = Tk() imgLbl = Label( window, image = img ) TclError: image "&lt;PIL.GifImagePlugin.GifImageFile image mode=P size=92x95 at 0x8C92B38&gt;" doesn't exist
type: UnansweredQuestion
has title: Python import image gif
tagged with: python
tagged with: image
favorite count: 0
has answer: http://stackoverflow.com/a/79472892
linked to: http://stackoverflow.com/q/28518072
score: 0
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/49280239
downvote count: 1

http://stackoverflow.com/q/49181855
type: Question
tagged with: python-3.x
answer count: 0
has body: I have a nested dict my_dict in python: {'version': '1.1', 'time': '1520541234', 'car': [{'id': '123', 'locationX': '-0.673606', 'locationY': '23.5310399', '@id': 'http://URL', 'standardname': 'value1', 'name': 'value_1'}, {'id': '124', 'locationX': '0.O683', 'locationY': '48.42', '@id': 'htt://URL2', 'standardname': 'value2', 'name': 'value_2'}, {'id': '125', 'locationX': '42.532', 'locationY': '12.424', '@id': 'http://URL3', 'standardname': 'value3', 'name': 'value_3'}, .... I want to check if one specific value is in the dic. I saw it seems easier in a list so I try to convert my my_dict to a list: my_list=(list(my_dict.items())) Now I'm searching for my value any('value' in sl for sl in my_list) But this does not work. What am I missing here?
has comment: http://stackoverflow.com/comment/85369372
type: UnansweredQuestion
has title: How to convert nested dict to nested list to find value
upvote count: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85372514
has comment: http://stackoverflow.com/comment/85369966
has comment: http://stackoverflow.com/comment/85369417
has comment: http://stackoverflow.com/comment/85369824
score: 0
has comment: http://stackoverflow.com/comment/85372589
has comment: http://stackoverflow.com/comment/85369975
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/49126195
type: Question
tagged with: c#
has body: This question is similar to this one Including a service reference from a class library. In my case I work with python and C#. In my C# ClassLibrary Project I use a service reference and a dll which provides a specific client as a class, used for calling the webservice. This code works fine if I try it in my console application: class ws_class { [DllExport("webservice", CallingConvention = CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.LPWStr)] public static string TestExport() { //Calling request return response; } } Now I want to use the .dll in python using this code: api = ctypes.cdll.LoadLibrary(path) api.webservice.retsype = ctypes.c_wchar_p print(api.webservice()) In other cases this code also works fine for receiving string returned by a C# Class Library. But as soon as I use the .dll reference for the client in my C# code, it doesn't work anymore. It seems like python cannot handle this issue. Regarding the question I mentioned above, the config files must be identical but still it won't work.
tagged with: dll
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/529550
downvote count: 0
answer count: 0
score: 1
upvote count: 1
has title: calling c# dll with (service) references from python
favorite count: 0

http://stackoverflow.com/a/49226491
has body: ddd.txt: 3.1948343452787551598e-08 8.2713170790435268456e-08 9.2997407466072783263e-08 2.2201974063356576525e-08 4.7184351703512537954e-08 6.4869237006439418830e-08 5.6105657006093290136e-08 2.5869788723656166592e-08 3.2336150408719792489e-08 1.3711755095387755690e-08 0.8466139114156927980e-08 8.6552265489125695952e-08 1.6410391288046437544e-08 6.4151550079023113112e-08 9.9077814220256712144e-08 4.8228459783414887112e-08 1.6503915571969716123e-08 5.0759765831642425139e-08 1.4163943549368568877e-08 0.9171874262950143401e-08 2.2924892903408382299e-08 8.0910403085272639979e-08 0.1150909967310807486e-08 1.7800414806457459589e-08 9.9156327409347916878e-08 0.7474308272820071357e-08 4.8164050539957729897e-08 7.2570119501482690351e-08 5.5760621634989852061e-08 3.3409017307778332564e-08 4.7565190913441753115e-08 5.1557086343029653458e-08 6.3693801211606923532e-08 7.8897108738118126312e-08 9.4510334836961360301e-08 7.4880836459074272283e-08 4.9268327788150989424e-08 1.8466453757372403026e-08 6.2011855819003971679e-08 2.0783930984602632852e-08 0.9917554541229221025e-08 7.5224425124573985562e-08 2.6181377446191134266e-08 8.9009270149441469026e-08 7.7175189573912221707e-08 2.2170581996655944683e-08 3.2639560946849215485e-08 7.0901354279344938844e-08 5.5997044308008179085e-08 9.8907609461314007943e-08 3.1948343452787551598e-08 8.2713170790435268456e-08 9.2997407466072783263e-08 2.2201974063356576525e-08 4.7184351703512537954e-08 6.4869237006439418830e-08 5.6105657006093290136e-08 2.5869788723656166592e-08 3.2336150408719792489e-08 1.3711755095387755690e-08 0.8466139114156927980e-08 8.6552265489125695952e-08 Solution: with open('ddd.txt', 'r') as f: nums = [] for line in f: nums.extend(line.split()) with open('eee.txt', 'w') as f: for i in range(0, len(nums), 5): five_nums = ' '.join(nums[i:i + 5]) f.write('{}\n'.format(five_nums)) eee.txt 3.1948343452787551598e-08 8.2713170790435268456e-08 9.2997407466072783263e-08 2.2201974063356576525e-08 4.7184351703512537954e-08 6.48692370064…
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49226391
has comment: http://stackoverflow.com/comment/85458897
has comment: http://stackoverflow.com/comment/85456926
has comment: http://stackoverflow.com/comment/85457814
has comment: http://stackoverflow.com/comment/85456941

http://stackoverflow.com/q/49267939
type: UnansweredQuestion
has title: Python list strange behaviour
has body: I have in my code: my_list= [] def start() my_list = [1, 2, 3] for item in my_list: print item And it works OK. But if I call to a second function. The 'for' stament only iterates once, only for the first element of the list. my_list= [] def print_list() for item in my_list: print item def start(): my_list = [1, 2, 3] print_list() Why? Any help/tip?
has comment: http://stackoverflow.com/comment/85539291
tagged with: python
has answer: http://stackoverflow.com/a/49268022
score: -1
tagged with: list
has comment: http://stackoverflow.com/comment/85539515
has comment: http://stackoverflow.com/comment/85539408
upvote count: 0
answer count: 1
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49221743
has comment: http://stackoverflow.com/comment/85447161
upvote count: 2
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49222091
accepted answer: http://stackoverflow.com/a/49222091
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49222589
has comment: http://stackoverflow.com/comment/85447604
tagged with: file
has body: Okay so I'm having some troubles. I have a file with a few keywords in there. I have another file for the output. I am trying to read each line from the first file, add a string at the end and the output to the last file. Here's what I currently have: def add(x, extend, file): extend = Extl file = open(file, "a") for i in extend: out = x + i + " + roy" file.write(out + "\n") file.close() print("Starting...") Extl = ['c', 's', 'aa', 'aqe','tdd', 'lap', 'tre', 'bgh', 'r' ] Keys = [] Reader = open("Keywords.txt", "r") for line in Reader: Keys.append(line) S = 0 while S &lt; len(Keys): xc = Keys[S] files = "File.txt" add(xc, Extl, files) S += 1 However when I receive the output, I get something like this: Keypeo c + roy Keypeo s + roy Keypeo aa + roy Keypeo aqe + roy Keypeo tdd + roy Keypeo lap + roy Keypeo tre + roy Keypeo bgh + roy Keypeo r + roy Aewqc + roy Aewqs + roy Aewqaa + roy Aewqaqe + roy Aewqtdd + roy Aewqlap + roy Aewqtre + roy Aewqbgh + roy Aewqr + roy It's not adding the keywords correctly, only the last few are fine. Help would be much appreciated.
has title: How to read each line from a file and output the line to another file with an extension
linked to: http://stackoverflow.com/q/3277503
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49221888
possible better answer: http://stackoverflow.com/a/49221888
has comment: http://stackoverflow.com/comment/85447222
tagged with: python
has comment: http://stackoverflow.com/comment/85447560
has comment: http://stackoverflow.com/comment/85447757

http://stackoverflow.com/comment/85319713
comment on: http://stackoverflow.com/q/49155132
type: QuestionComment
has text: Possible duplicate of [How do I read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-do-i-read-a-file-line-by-line-into-a-list)
type: Comment
score: 0

http://stackoverflow.com/comment/85558216
type: QuestionComment
has text: Look at my anwer
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49276042

http://stackoverflow.com/a/49244258
has comment: http://stackoverflow.com/comment/85519543
score: 0
has body: First, Make sure the file is present at this location. It could be possible that it is renamed. Second, check whether Python has successfully changed the directory. You can do this using the os.getcwd() method. I am not sure why you used type(wb). Maybe you wanted to check the type of the variable wb. Your code section is not edited properly. Here's what you can do: import os import openpyxl os.chdir('C:\Users\Simon\Desktop') os.getcwd() # to check the current working directory wb = openpyxl.load_workbook('wellbeing.xlsx') wb.sheetnames # to get all sheet names in the Excel spreadsheet type(wb) # openpyxl.workbook.workbook.Workbook The best way to get the correct path of a file(and be sure that it's present): 1) Go to the file and press Shift+right-click on the file and select Copy as path: 2) Next, paste the copied path in os.chdir() in the code below, excluding the filename 'wellbeing.xlsx'. 3) Run the following code to check if Python can open and read the contents in the file. The readlines() function reads the contents line-by-line. We will print this to see if we can get the contents displayed. import os import openpyxl os.chdir('C:\\Users\\Simon\\Desktop') with open("wellbeing.xlsx" ,'r') as f: print(f.readlines())
accepted answer of: http://stackoverflow.com/q/49243507
has comment: http://stackoverflow.com/comment/85519400
has comment: http://stackoverflow.com/comment/85519553
has comment: http://stackoverflow.com/comment/85520207
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49243507
has comment: http://stackoverflow.com/comment/85520279

http://stackoverflow.com/comment/85571290
has text: Thanks for the info. Is this scheduled for development at some point?
score: 2
comment on: http://stackoverflow.com/a/49255259
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85503137
type: Comment
has text: I think using deepcopy is one solution.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49249605

http://stackoverflow.com/q/49216418
tagged with: selenium-webdriver
answer count: 2
upvote count: 2
score: 2
has title: How to switch between different chrome browser window opened by different WebDriver using selenium in Python?
possible better answer: http://stackoverflow.com/a/49219037
downvote count: 0
tagged with: selenium
has body: I searched for this question,and I found an idea using driver.switch_to.window(),but it didn't work as expect: from selenium import webdriver driver1=webdriver.Chrome("D:\Python\Files\chromedriver.exe") driver1.get('https://www.google.com') driver2=webdriver.Chrome("D:\Python\Files\chromedriver.exe") driver2.get('https://www.bing.com/') driver1.switch_to.window(driver1.current_window_handle) above code will first open a chrome window and go to google,then will open another chrome window and go to bing,then driver1.switch_to.window(driver1.current_window_handle) seems didn't work,the window showing bing still shows on top of the window showing google. Anyone have any idea?I think driver1.switch_to.window(driver1.current_window_handle) may have some BUG.
has answer: http://stackoverflow.com/a/49219037
tagged with: webdriver
favorite count: 0
accepted answer: http://stackoverflow.com/a/49220645
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49220645
tagged with: python

http://stackoverflow.com/q/49138888
has title: Matplotlib subplots: equal axis with axis sharing
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/13784201
downvote count: 0
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85283661
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49139150
accepted answer: http://stackoverflow.com/a/49139150
has comment: http://stackoverflow.com/comment/85283329
score: 1
tagged with: matplotlib
has body: I know that this topic has been addressed already in several matplotlib blogs, but I still could not find a solution to this. I want to create a plot like this: (plot from the answer of @ImportanceOfBeingErnest) So these are two subplots which share the same y-axis with y-limits that I define. The x-axis should be in equal units as the y-axis, meaning if I would draw a circle, it would really be a circle. Now I would like to also specify x-limits and like the subplot size to adjust to this limits, but I cannot make it work. The general problem seems to be that matplotlib always keeps the fig-size of the different subplots. Here is a minimal working example: import matplotlib.pyplot as plt import numpy as np fig=plt.figure() ax1=fig.add_subplot(1,2,1,aspect='equal') ax2=fig.add_subplot(1,2,2,aspect='equal',sharey=ax1) def create_data(xmin,xmax): delta = 0.025 ---- x = np.arange(xmin, xmax, delta) y = np.arange(-3,3,delta) X, Y = np.meshgrid(x, y) Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 10 * (Z1 - Z2) ---- nr, nc = Z.shape ---- # put NaNs in one corner: Z[-nr//6:, -nc//6:] = np.nan # contourf will convert these to masked ---- ---- Z = np.ma.array(Z) # mask another corner: Z[:nr//6, :nc//6] = np.ma.masked ---- # mask a circle in the middle: interior = np.sqrt((X**2) + (Y**2)) &lt; 0.5 Z[interior] = np.ma.masked return X,Y,Z X,Y,Z=create_data(-2,4) ax1.contourf(X,Y,Z) ax1.set_ylim(-1,1) ax1.set_xlim(-2,4) X,Y,Z=create_data(-1,0) ax2.contourf(X,Y,Z) ax2.set_ylim(-1,1) ax2.set_xlim(-1,0) plt.show() In this example the y-axis is shared but the x-limits are not applied correctly: Further, how can I add a colorbar to the right of the subplots aligned to the y-axis? fig.colorbar(CS, ax=ax,shrink=xx) seems to work but requires to manually edit the shrink parameter.
tagged with: python

http://stackoverflow.com/q/49223183
answer count: 2
has title: Shifting Elements in a Numpy Array
has comment: http://stackoverflow.com/comment/85485509
has comment: http://stackoverflow.com/comment/85450076
has body: I am trying to implement a function that will shift a particular element in a numpy 2d array a desired number of spaces in a given direction. Empty spaces should be filled with 0's. This function will take as input a numpy array, the x and y coordinates, a desired direction, and the number of spaces to shift. For example, where shift is the hypothetical function: arr = np.array([1, 1, 1], [1, 1, 1], [1, 1, 1]) arr out: [[1, 1, 1], [1, 1, 1], [1, 1, 0]] shift(arr, 0, 0, 'right', 2) arr out: [[0, 0, 1], [1, 1, 1], [1, 1, 0]] shift(arr, 0, 2, 'down', 1) arr out: [[0, 0, 0], [1, 1, 1], [1, 1, 1]] I have found that I can achieve the desired shifting of all elements of either a row or column along that row or column with numpy's roll function. However, this approach simply cycles elements back to the beginning of the same row or column and does not fill empty spaces with 0's. For example: arr[:, 0] = np.roll(arr[:, 0], 1) arr out: [[1, 0, 0], [0, 1, 1], [1, 1, 1]] Any assistance is very much appreciated. edit: The x and y coordinates are the coordinates of the element to be shifted within the 2d array. The the rest of the elements within the same row or column are then shifted with respect to that element in the desired direction. For example shift(arr, 2, 2, 'down', 1) shifts the elements in the column with respect to the element at (2, 2) down by 1. All input values may be assumed to be valid at all times. edit: This problem differs from the one linked in that elements are shifted with respect to the element at the coordinates provided, and this shifting occurs in a nested array. Furthermore, this solution does not allow for shifting of elements either up or down within the same column.
score: 1
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49241050
tagged with: numpy
upvote count: 2
accepted answer: http://stackoverflow.com/a/49241432
has comment: http://stackoverflow.com/comment/85449815
has comment: http://stackoverflow.com/comment/85526095
has answer: http://stackoverflow.com/a/49241432
tagged with: python
has comment: http://stackoverflow.com/comment/85450762
has comment: http://stackoverflow.com/comment/85485802
possible better answer: http://stackoverflow.com/a/49241050
has comment: http://stackoverflow.com/comment/85450061
has comment: http://stackoverflow.com/comment/85450837
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/30399534

http://stackoverflow.com/comment/85455058
score: 2
has text: Notably, this replaces all "falsey" values, so it will work as intended on empty strings, but if some of the dictionary values are actually `None` or `0` or `False` or some other such value, it might not have the desired effect.
type: Comment
comment on: http://stackoverflow.com/a/49225425
type: AnswerComment

http://stackoverflow.com/comment/85563776
comment on: http://stackoverflow.com/q/49227183
score: 0
type: Comment
type: QuestionComment
has text: You say "returns `'JpegImageFile' object has no attribute '_committed'` error on the last line (`instance.save()`)" but the traceback shows `'JpegImageFile' object has no attribute 'read'` at `if uploaded_file_type(instance) is True:` which is not included in your code sample. You will also need to show your `uploaded_file_type` helper function.

http://stackoverflow.com/comment/85490804
type: Comment
comment on: http://stackoverflow.com/q/49242820
has text: I am pretty sure I did not do python2 thing. After activating the virtual env, I could do `python --version` and get python 3.6
type: QuestionComment
score: 0

http://stackoverflow.com/a/49159264
has comment: http://stackoverflow.com/comment/85327592
has comment: http://stackoverflow.com/comment/85327701
answers question: http://stackoverflow.com/q/49159217
has comment: http://stackoverflow.com/comment/85328021
has comment: http://stackoverflow.com/comment/85346211
has comment: http://stackoverflow.com/comment/85348275
has comment: http://stackoverflow.com/comment/85328042
has comment: http://stackoverflow.com/comment/85348018
downvote count: 0
has comment: http://stackoverflow.com/comment/85346331
has comment: http://stackoverflow.com/comment/85327867
upvote count: 4
has body: Use Python's string .format() to give each of your elements a fixed width: def text(): rows = (("PETER PAUL", "MALE", "100000"), ("MARGARET ", "FEMALE", "1000"), ("MICHAEL JORDAN", "MALE", "1"),("AGNES", "FEMALE", "200")) for row in rows: print('{:20} {:8} {}'.format(*row)) text() Giving you: PETER PAUL MALE 100000 MARGARET FEMALE 1000 MICHAEL JORDAN MALE 1 AGNES FEMALE 200 The format() command works by replacing each {} seen in the string by an argument passed to it, in this case *row. The * has the effect of expanding the three values inside row to be the three arguments required to be expanded. To return the formatted text, you would need to first create a list of formatted rows, and then use '\n'.join() to join them all together will newlines at the end: def text(): rows = (("PETER PAUL", "MALE", "100000"), ("MARGARET ", "FEMALE", "1000"), ("MICHAEL JORDAN", "MALE", "1"),("AGNES", "FEMALE", "200")) data = [] for row in rows: data.append('{:20} {:8} {}'.format(*row)) return '\n'.join(data) print(text()) This could also be done very neatly using a Python "list comprehension" as follows: def text(): rows = (("PETER PAUL", "MALE", "100000"), ("MARGARET ", "FEMALE", "1000"), ("MICHAEL JORDAN", "MALE", "1"),("AGNES", "FEMALE", "200")) return '\n'.join('{:20} {:8} {}'.format(*row) for row in rows) print(text())
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/85327901

http://stackoverflow.com/a/49200666
downvote count: 0
has body: Because the absolute value of a complex number is the distance from origin to the number on the complex plane (where the two components of the complex number form the coordinates). The imaginary i and real r components of a complex number can be seen as coordinates on a plane, and you can calculate the distance from the origin ((0, 0)) by using Pythagorean distance formula, sqrt(i**2 + r**2). The distance can be expressed as a floating point (real) number, there is no imaginary component. It also can’t be an integer, because the Pythagorean distance is not always a convenient whole number (unlike the absolute value of an integer, which can only ever be another integer).
has comment: http://stackoverflow.com/comment/85413391
has comment: http://stackoverflow.com/comment/85413116
score: 3
answers question: http://stackoverflow.com/q/49200609
type: Answer
has comment: http://stackoverflow.com/comment/85414137
upvote count: 3

http://stackoverflow.com/comment/85472191
has text: i am totally confused i dont understand how this works can you paste the code you tired which works :/ need serious help
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49233970

http://stackoverflow.com/comment/85304721
comment on: http://stackoverflow.com/q/49150120
score: 0
type: Comment
type: QuestionComment
has text: Welcome to SO! Please provide some reproducible data and code, in other words a **[mcve]**.

http://stackoverflow.com/q/49251946
tagged with: http://stackoverflow.com/tag/pdf
tagged with: regex
accepted answer: http://stackoverflow.com/a/49253750
has answer: http://stackoverflow.com/a/49253750
type: Question
has body: I've done a lot of searching and experiments already with this one! I am sure its probably very simple. I use Python to scan the contents of PDFs to read the serial numbers of machines I buy in. All machines are wiped with specialized software and the serial number (used to be) the final 'word' in the first line of the document. Easy to extract without a regex. Now the software that does the wiping sometimes puts the serial on the second line of the PDFs. I guess I could use a bunch of chained 'if' clauses to get around the problem but I would rather use Regexes. The machines I deal with are Dells, Macs and iPhones. Dells have 7 upper-case alphanumeric 'service tags'/serials. Macs and iPhones can be either 11 or 12 upper-case alphanumeric characters, depending on when they were manufactured. This is what i have so far... I a little concerned about 'false positives' creeping in. The verification of the serial number is based on lenght. The date and time and software version of the software are also in the list of the serial results. output = convert_pdf_to_txt(file_name) # getting the serial by joining first two lines together, using a regex, adding to list, sorting list by len #assigning the longest result to the serial variable. this limits the scope of the search. fewer results to annoy me lines = output.splitlines() firstLine = lines[0] secondLine = lines[1] docHeader = str(firstLine) + str(secondLine) docHeader = str(docHeader) #regex to find alphanumeric words serialRegex = "(\w*\d[\w\d]+)" serialResults = re.findall(serialRegex, docHeader) sorted(serialResults, key=len) serial = serialResults[-1] The tests I have done so far have been in order, but its only a matter of time before Dell come up with some laptop whose (alphanumeric) model number is 8 characters long and thus supplants the serial... just thinking out loud. An example of how the top of the PDF document reads... the serial (obscured) is on the second line here. My version of Python (2.7) doest seem…
answer count: 1
tagged with: python
has title: Regex for computer serial numbers. Python 2.7
type: AnsweredQuestion
score: 0

http://stackoverflow.com/a/49265152
type: Answer
has body: try to run wih sudo if you want to know why you get this problem check this stackoverflow answer
score: 0
answers question: http://stackoverflow.com/q/49265054

http://stackoverflow.com/a/49191052
has body: If you set shuffle = false in tf.estimator.inputs.numpy_input_fn as follows, input_function = tf.estimator.inputs.numpy_input_fn({"X": X}, Y, batch_size=4, shuffle=False, num_epochs=None) the output seems reasonable to me. However, I think the reason is with your data it's hard to learn a linear model. When shuffle=False model try to overfit and shuffle=True model learns nothing. EDITED You can also try the Gradientdescent optimizer as follows. estimator = tf.estimator.LinearRegressor(feature_columns=feat_cols,optimizer=tf.train.GradientDescentOptimizer(learning_rate=1)) Or you can continue to use the same FtrlOptimizer, which is the default optimizer of tf.estimator.LinearRegressor with increased learning rate. estimator = tf.estimator.LinearRegressor(feature_columns=feat_cols,optimizer=tf.train.FtrlOptimizer(learning_rate=1)) I think both should converge when shuffle = True. However, I'm not sure exact reason for not converging when shuffle = True with default settings. Hope this helps.
has comment: http://stackoverflow.com/comment/85387333
answers question: http://stackoverflow.com/q/49188239
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/85400864

http://stackoverflow.com/comment/85459185
comment on: http://stackoverflow.com/a/49226859
type: Comment
type: AnswerComment
score: 0
has text: I see. I've experimented with manually bringing the network interface down for 30-60s, and the program gives a Resource Temporarily Unavailable message, but then recovers. So I am not sure what is happening with the longer sessions that is unrecoverable. The main reason I went with PAIR/PAIR was that at the time we were prototyping this software a few months ago, RADIO/DISH and CLIENT/SERVER were still in early draft for pyzmq. Now that those drafts are more stable, do you think it is worth trying to switch to that paradigm? Would it help with the Resource Temporarily Unavailable messages?

http://stackoverflow.com/a/49219028
has comment: http://stackoverflow.com/comment/85441814
score: 1
has comment: http://stackoverflow.com/comment/85449685
accepted answer of: http://stackoverflow.com/q/49218967
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85442085
has comment: http://stackoverflow.com/comment/85441824
upvote count: 1
has body: I think better is avoid loops (apply under the hood) and use numpy.where: #sample Dataframe with sample datetimes rng = pd.date_range('2017-04-03', periods=10, freq='8m') df = pd.DataFrame({'Date': rng, 'a': range(10)}) date1 = df.Date.shift(1).dt.year date2 = df.Date.dt.year df['all_data_in_year'] = np.where(date1 == date2, date1 * date2, np.nan) print (df) Date a all_data_in_year 0 2017-04-30 0 NaN 1 2017-12-31 1 4068289.0 2 2018-08-31 2 NaN 3 2019-04-30 3 NaN 4 2019-12-31 4 4076361.0 5 2020-08-31 5 NaN 6 2021-04-30 6 NaN 7 2021-12-31 7 4084441.0 8 2022-08-31 8 NaN 9 2023-04-30 9 NaN EDIT1: df['new'] = df.groupby( pd.to_datetime(df['Date']).dt.year)['Close'].transform('prod')
answers question: http://stackoverflow.com/q/49218967
type: Answer
has comment: http://stackoverflow.com/comment/85441967
has comment: http://stackoverflow.com/comment/85441823

http://stackoverflow.com/a/49181769
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49181258
downvote count: 0
has body: Following the comment in issue 308 that says py::cast(self), I try py::cast(*this). That works. I feel a bit uneasy about invalidation of views, but numpy does that the same way. Python test: import _cpp import numpy as np a = _cpp.A() print(a) a.view()[:] = 100 # should make it all 100. print(a) Test result: 1480305816 32581 19420784 0 // original data of `a` 100 100 100 100 // It works: changing `a.view()` changes data of `a`. main.cpp: #include &lt;iostream&gt; #include "pybind11/pybind11.h" #include "pybind11/numpy.h" namespace py = pybind11; class A { public: A() {} std::string str() { std::stringstream o; for (int i = 0; i &lt; 4; ++i) o &lt;&lt; _data[i] &lt;&lt; " "; return o.str(); } py::array view() { return py::array(4, _data, py::cast(*this)); // &lt;--- } int _data[4]; }; PYBIND11_MODULE(_cpp, m) { py::class_&lt;A&gt;(m, "A") .def(py::init&lt;&gt;()) .def("__str__", &amp;A::str) .def("view", &amp;A::view, py::return_value_policy::reference_internal); } I use reference_internal to make the life time of a.view() tie to life time of a. View is invalidate upon deleting the parent object. After deleting a in the python test, python will garbage collect the data of a at an indefinite time. This means if I previously store the view by b = a.view(), b is invalidated after a is deleted. I try to make a._data a numpy array at the C++ side but that doesn't help the invalidation. main.cpp: class A { public: A() : _data(4, new int[4]) {} std::string str() { std::stringstream o; for (int i = 0; i &lt; 4; ++i) o &lt;&lt; _data.data()[i] &lt;&lt; " "; return o.str(); } py::array view() { return py::array(4, _data.data(), py::cast(*this)); } py::array_t&lt;int&gt; _data; }; Python Test: import _cpp import numpy as np a = _cpp.A() print(a) a.view()[:] = 100 # should make it all 100. b = a.view() print('b is base?', b.base is None) del a print('b is base after deleting a?', b.base is None) c = np.zeros(4) print('c is base?', c.base is None) d = c.view() print('d is base?'…
upvote count: 1
has comment: http://stackoverflow.com/comment/85426828
has comment: http://stackoverflow.com/comment/85425208
type: Answer
accepted answer of: http://stackoverflow.com/q/49181258
score: 1

http://stackoverflow.com/q/49267148
duplicate of: http://stackoverflow.com/q/3206344
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49267858
tagged with: pandas
has answer: http://stackoverflow.com/a/49267858
downvote count: 2
answer count: 1
tagged with: jinja2
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/3206344
has body: I am using Flask ,Jinja2 template(html file) to post the panda dataframe tables which are stored in results in ABC.py. Table looks like :Image I am using dictionary to print it but it is not coming in right format {% if results is not none %} Compare Specifications part1 part2 {% for key,value in results.iterrows() %} <option value = {{value[0]}} {{value[1]}} # {{value['1'] }} {% endfor %} {% endif %} Have to do other things using jinja2 templates but stuck at very ground level. Any suggestions please. Thanks
tagged with: python
score: 4
tagged with: flask
has title: jinja2 to post dataframe tables on web
upvote count: 6

http://stackoverflow.com/q/49260442
accepted answer: http://stackoverflow.com/a/49276056
has title: Celery - Flower service in Cent/7 doesn't show data after a restart
has answer: http://stackoverflow.com/a/49276056
has body: My service is as below : [Service] User=vagrant Group=vagrant WorkingDirectory=/home/vagrant/ ExecStart=/usr/bin/celery -A tasks /usr/bin/flower --port=5000 --basic_auth=sun:flower --persistent=true --/var/log/supervisord.log Restart=on-failure Type=simple I have created a simple tasks for testing purposes after creating a REDIS master-slave replication and pointing Celery and flower to Master... celery.ini for Supervisord [program:SPSimpleTasks] directory = /home/vagrant/ command = celery -A tasks worker --loglevel=DEBUG -n SimpleTasks user=vagrant autostart=true autorestart=true stdout_logfile=/var/log/supervisord.log stderr_logfile=/var/log/supervisord.log celery_app.py from celery import Celery app = Celery('tasks', backend='redis://:&lt;PASSWORD&gt;@192.168.100.20:6379/0') #app.config_from_object('celeryconfig') app.conf.update( enable_utc = True, broker_url = 'redis://:&lt;PASSWORD&gt;@192.168.100.20:6379/0', result_backend = 'redis://:&lt;PASSWORD&gt;@192.168.100.20:6379/1', result_persistent = True, task_serializer = 'json', result_serializer = 'json', accept_content = ['json'] ) Again, the workers are working fine and flower shows the tasks result. But once I restart the service using sudo service flower restart Flower loads as its brand new install without any data... Am I doing something wrong with the broker / backend urls?
tagged with: python
type: AnsweredQuestion
tagged with: flower
score: 1
tagged with: supervisord
answer count: 1
tagged with: centos7
downvote count: 0
upvote count: 1
type: Question
tagged with: celery
favorite count: 0

http://stackoverflow.com/q/49250239
has answer: http://stackoverflow.com/a/49250511
upvote count: 1
has comment: http://stackoverflow.com/comment/85504529
has body: Consider I have an array containing the string of datetime: new_time[index] Out[9]: array(['2012-09-01_00:00:00', '2012-09-01_01:00:00', '2012-09-01_02:00:00', '2012-09-01_03:00:00', '2012-09-01_04:00:00', '2012-09-01_05:00:00', '2012-09-01_06:00:00', '2012-09-01_07:00:00', '2012-09-01_08:00:00', '2012-09-01_09:00:00', '2012-09-01_10:00:00', '2012-09-01_11:00:00', '2012-09-01_12:00:00', '2012-09-01_13:00:00', '2012-09-01_14:00:00', '2012-09-01_15:00:00', '2012-09-01_16:00:00', '2012-09-01_17:00:00', '2012-09-01_18:00:00', '2012-09-01_19:00:00', '2012-09-01_20:00:00', '2012-09-01_21:00:00', '2012-09-01_22:00:00', '2012-09-01_23:00:00'], dtype='&lt;U19') Its shape is (24,).The question is how can I assign it to a (24,19)array,and the rows of new array could look like following: ## one row of new array Out[10]: array(b'2', b'0', b'1', b'2', b'-', b'0', b'9', b'-', b'0', b'1', b'_', b'0', b'0', b':', b'0', b'0', b':', b'0', b'0', dtype='|S1') Thanks for your help.
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85504432
tagged with: datetime
has answer: http://stackoverflow.com/a/49251855
has title: How to transform an 1D string array to a 2D array about the datetime
possible better answer: http://stackoverflow.com/a/49250752
tagged with: python
has comment: http://stackoverflow.com/comment/85504237
answer count: 4
has answer: http://stackoverflow.com/a/49250752
has comment: http://stackoverflow.com/comment/85503937
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/49250511
has comment: http://stackoverflow.com/comment/85503868
has answer: http://stackoverflow.com/a/49250415
downvote count: 0

concurrent.futures
tags question: http://stackoverflow.com/q/49167721
type: Tag
tags question: http://stackoverflow.com/q/49266458
tags question: http://stackoverflow.com/q/49273773
tags question: http://stackoverflow.com/q/49272622
tags question: http://stackoverflow.com/q/49255477
tag name: concurrent.futures

http://stackoverflow.com/a/49143795
upvote count: 0
has comment: http://stackoverflow.com/comment/85337574
downvote count: 1
has comment: http://stackoverflow.com/comment/85369277
has comment: http://stackoverflow.com/comment/85339920
has comment: http://stackoverflow.com/comment/85369384
type: Answer
score: -1
has body: This works - Please note the Upper and Lower values are reset in the function definition. def take_guess(lower, higher): return int(lower + (higher - lower) / 2) def calc_guesses(i): lower = 0 higher = 100 t = 1 while True: guess = take_guess(lower, higher) #print("i is {} guess is {}".format(i,guess)) if guess == i: l.append(t) t = 1 break elif guess &gt; i: higher = guess t += 1 continue elif guess &lt; i: lower = guess t += 1 continue return t l = [] for i in range(1,100): l.append(calc_guesses(i)) l.sort() print ("Last value is {}".format(l[-1])) Output 7 Regards
answers question: http://stackoverflow.com/q/49143628

mne-python
type: Tag
tag name: mne-python
tags question: http://stackoverflow.com/q/49172863

http://stackoverflow.com/comment/85521113
comment on: http://stackoverflow.com/q/49258986
has text: I'm sure this is a duplicate but I can't find a prior. It's a good question regardless.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85327542
has text: perhaps you could remove the old version and install the newer version?
type: QuestionComment
comment on: http://stackoverflow.com/q/49160972
type: Comment
score: 0

http://stackoverflow.com/comment/85494017
comment on: http://stackoverflow.com/q/49244982
score: 1
has text: Also, the convention in Python is to use `self` to refer to the current instance, using `r1` instead is just confusing.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85373051
type: Comment
score: 0
type: AnswerComment
has text: @bclayman What about `df.iloc[1, lag_cols] = df.iloc[0, lag_cols].values`?
comment on: http://stackoverflow.com/a/49183479

http://stackoverflow.com/q/49179128
score: 1
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/49182342
tagged with: signal-processing
has body: I am working on a project to predict the gender of a user by taking live audio input from the user. While researching for this project I came across a dataset by kaggle https://www.kaggle.com/primaryobjects/voicegender, a CART logic was proposed where if meanfun&lt;0.14: if IQR&gt;=0.07: return male else return female else return female I have tried to search for mean fundamental frequency but could not find any useful resources. Please explain this concept and what is the difference between mean frequency and mean fundamental frequency? and also how to calculate it's value.
favorite count: 0
type: Question
tagged with: frequency
type: UnansweredQuestion
has title: Calculation of mean fundamental frequency of audio sample
tagged with: python
tagged with: frequency-analysis
tagged with: audio
downvote count: 0

http://stackoverflow.com/comment/85454183
score: 0
has text: Hi thanks to all for the great replies. I know it wasn't the best code as I am just a beginner at this and it is for a school coursework project. I entered in the code above but it seems to create a new record in the table every time a new exercise and weight is added, this means that multiple MemberID's are being used by one user and so could not be referenced if the frame was closed and reopened. Is there a way to prevent this so that the ID is the same?
comment on: http://stackoverflow.com/a/49224831
type: Comment
type: AnswerComment

http://stackoverflow.com/a/63066633
downvote count: 0
has body: The easiest way I've found is just list(df.columns) Personally I wouldn't want to change the globals, it's not that often I want to see all the columns names.
answers question: http://stackoverflow.com/q/49188960
score: 9
upvote count: 9
type: Answer
has comment: http://stackoverflow.com/comment/127282560
has comment: http://stackoverflow.com/comment/120817539

http://stackoverflow.com/a/49215074
type: Answer
answers question: http://stackoverflow.com/q/49214989
has body: External drives can be found under /Volumes on macOS. If you provide the full path and have read access you should be able to read in your csv.
downvote count: 0
upvote count: 8
score: 8

http://stackoverflow.com/a/49180204
accepted answer of: http://stackoverflow.com/q/49178618
type: Answer
answers question: http://stackoverflow.com/q/49178618
score: 1
type: AcceptedAnswer
has body: This generates 17 individual histograms and 1 final figure with the red squares. import matplotlib.pyplot as plt import numpy as np def generateData(goal): x=[_ for _ in range(20)] y=[10+np.random.exponential()*5 for _ in range(100)] return x,y def drawHistogram(data,nBins): plt.figure() plt.hist(diffs,nBins) sweep=np.linspace(10,20,4) for goal in sweep: for gw2 in sweep: diffs=[] for i in range(10): data=generateData(goal) diffs.append(goal-np.mean(data[1])) #generate plot plt.figure(1) clr=(abs(np.mean(diffs))/goal,0,0) plt.plot([goal], [gw2], marker="s", mew='1', ms='35', color=clr) drawHistogram(diffs,5) ##Comment this line out to see what the final graph should look like plt.draw() plt.show()
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85534919
type: Comment
has text: something in your `RegisterView` and `LocationView` is different
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49265666

http://stackoverflow.com/q/49138587
has answer: http://stackoverflow.com/a/49138641
has comment: http://stackoverflow.com/comment/85282437
has body: I'm trying to get a list of tuples with the indices of all sets of parentheses in a string. I can find the left and right parens independently easily with list comprehensions: s = "12(34)567" left_parens = [i for i,j in enumerate(s) if j == "("] right_parens = left_parens = [i for i,j in enumerate(s) if j == ")"] The most logical way to turn these separate lists into a list of tuples with (left paren, right paren) pairs is with the zip function. parens = zip(right_parens,left_parens) print(list(parens)) From this I would expect to yield: [(2,5)] But instead, I get: [(5,5)] Even if I switch the order like this: parens = zip(left_parens,right_parens) The result is still [(5,5)]. What am I missing? Try it online!
downvote count: 0
tagged with: python
tagged with: tuples
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/49138641
upvote count: 3
has comment: http://stackoverflow.com/comment/85282274
has comment: http://stackoverflow.com/comment/85282309
answer count: 1
has comment: http://stackoverflow.com/comment/85282434
has title: Find all parentheses in a string by pairs - Python 3
favorite count: 0
type: Question

http://stackoverflow.com/comment/85505634
comment on: http://stackoverflow.com/a/49220514
type: Comment
type: AnswerComment
has text: Thanks for very informative answer. That's a good answer, and it is something that I am using right now. The problem with search is that you can't do conditions (like is greater/less then date etc.). You can do those conditions with filter button. The problem is my table has tons of fields, but I only want to see let's say 15 fields. The solution that I gave with fields get is good. But problem is that when you switch between menuitems (Other Route, Route(Accounting) in image) The filter are not being renewed. Anyways thank you for your answer :).
score: 0

http://stackoverflow.com/q/49255916
has comment: http://stackoverflow.com/comment/85516032
has comment: http://stackoverflow.com/comment/85514874
has comment: http://stackoverflow.com/comment/85514829
type: Question
tagged with: python-multithreading
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/15362372
has comment: http://stackoverflow.com/comment/85514755
has comment: http://stackoverflow.com/comment/85514920
tagged with: python-multiprocessing
tagged with: tkinter
score: 0
answer count: 0
has title: Show output on Tkinter gui, in real time(dynamically)
has comment: http://stackoverflow.com/comment/85517806
tagged with: tk-toolkit
has body: I am working on a python program that generates output continuosly, Depending upon the user input. I am unable to show this output on Tkinter gui. Without tkinter it just works perfectly on terminal. Could you please suggest some code that will show the output on thr gui. Here is my python code: Program 1:- print "Enter a file name:", filename = raw_input() print filename This program is executed with gui using second program. Program 2:- import os from Tkinter import * root = Tk() t = Text(root) t.pack() def go(): p = os.popen("python hello.py") for l in p.xreadlines(): t.insert(END, '%s\n' % l.rstrip()) t.see(END) t.update_idletasks() Button(root, text='Go', command=go).pack() root.mainloop() Now I want the output to be shown inside tkinter GUI.

http://stackoverflow.com/comment/85539805
type: Comment
type: QuestionComment
score: 0
has text: The way that open() is being used is referring to a relative path. If you execute p3.py from anywhere outside of that directory, you're going to run into an error.
comment on: http://stackoverflow.com/q/49268188

http://stackoverflow.com/q/49142819
tagged with: python
has title: model in django,how to change two value when I edit one in admin?
type: AnsweredQuestion
tagged with: python-2.7
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49143060
type: Question
has body: in models.py: class Projects(models.Model): # 项目名称 pro_name = models.CharField('项目名称',max_length=50) # 项目内容 # content = models.CharField('项目内容',max_length=200) content = models.TextField('项目内容', max_length=200) # 外键 person = models.ForeignKey(Person, on_delete=models.CASCADE) # 金额 sum_money = models.IntegerField('项目金额',default=0) # 付款 payed_money = models.IntegerField('已付金额',default=0) # 欠钱 owe_money = models.IntegerField('未付金额',default=0) # 是否欠钱 is_debt = models.BooleanField('是否欠账',default=True) # 发布日期 pub_date = models.DateTimeField('保存日期',default=timezone.now,) def was_published_recently(self): return self.pub_date &gt;= timezone.now() - datetime.timedelta(days=1) def __str__(self): return self.pro_name class Meta: verbose_name = '项目' verbose_name_plural = '项目' admin screen capture: when I changed the 'payed_money(已付金额:)' the 'owe_money(未付金额:)' = sum_money - payed_money, and if sum_money == payed_money the is_debt = False what should I do? rewrite save() mehtod?
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49143060
tagged with: django

http://stackoverflow.com/q/49268387
type: UnansweredQuestion
type: Question
has title: I want to get json data from an url using python 2.7 version. I tried to import urllib request module but its not working for me
tagged with: python
has comment: http://stackoverflow.com/comment/85628364
has body: import urllib.request import json from pprint import pprint def main(): url="https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&amp;format=json&amp;env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys" data=urllib.request.urlopen(url).read() jsonData=json.loads(data.decode("utf-8")) pprint(jsonData) if __name__ == '__main__': main() Can someone help me with this? Thanks
score: 0
answer count: 2
favorite count: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85540145
has answer: http://stackoverflow.com/a/49268436
has answer: http://stackoverflow.com/a/49268451
has comment: http://stackoverflow.com/comment/85629555
tagged with: api

http://stackoverflow.com/comment/85278896
comment on: http://stackoverflow.com/q/49136407
type: Comment
type: QuestionComment
score: 2
has text: Fetch the records to a list first, using `fetchall()`.

http://stackoverflow.com/comment/85607867
comment on: http://stackoverflow.com/a/49159889
type: AnswerComment
score: 1
has text: the method save() will be actually called for each of the form instance when calling `formset.save()` there is iteration over all forms done and save() is executed. See https://github.com/django/django/blob/master/django/forms/models.py#L655
type: Comment

http://stackoverflow.com/a/57779392
has comment: http://stackoverflow.com/comment/105075369
score: 3
has comment: http://stackoverflow.com/comment/134531572
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49140911
has body: you can try this : Project Structure -> SDKs -> "+" -> Python SDK Project -> Project SDK -> Python 2.7.10 #Choose the python version that you want
has comment: http://stackoverflow.com/comment/105254386
type: Answer
has comment: http://stackoverflow.com/comment/105004802

http://stackoverflow.com/comment/85540612
type: QuestionComment
score: 0
has text: was a typo, num specifies the number of line on which it is and lines specify the text.
comment on: http://stackoverflow.com/q/49268469
type: Comment

http://stackoverflow.com/comment/85482656
has text: @MadPhysicist I already heard this, and I fully agree on it. Except, sometimes in cases like this, I don't have all day to look for a special function that would make my work easier. :'( -- This being said, I was looking for `np.where()` at first, but couldn't figure how to use it. Now I also know that I should have used it in association with `np.diff()`. :p
type: AnswerComment
comment on: http://stackoverflow.com/a/49239253
score: 0
type: Comment

http://stackoverflow.com/a/49271337
answers question: http://stackoverflow.com/q/49271187
score: 3
has comment: http://stackoverflow.com/comment/87551021
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/87551214
accepted answer of: http://stackoverflow.com/q/49271187
has comment: http://stackoverflow.com/comment/87551242
has comment: http://stackoverflow.com/comment/87551064
type: Answer
has body: As a guess: You wanted string() to return a value the caller can use, instead of just printing something to the screen. So you need a return statement instead of a print call. You want to loop over all of the words in that returned string, not all the characters, so you need to call split() on the string. You want to replace stuff in each word, not in the literal "cat". So, you need to call replace on word, not on the str class. Also, replace doesn't actually change the word, it returns a new one, which you have to remember. You want to print out each of those words. If so: def string(): return "This cat was scared." def main(): for word in string().split(): word = word.replace("cat", "dog") print(word, end=' ') print() main() That fixes all of your problems. However, it can be simplified, because you don't really need word.replace here. You're swapping out the entire word, so you can just do this: def main(): for word in string().split(): if word == "cat": word = "dog" print(word, end=' ') print() But, even more simply, you can just call replace on the entire string, and you don't need a loop at all: def main(): print(string().replace("cat", "dog"))

http://stackoverflow.com/q/49228214
tagged with: python
has answer: http://stackoverflow.com/a/49228268
has comment: http://stackoverflow.com/comment/85459984
possible better answer: http://stackoverflow.com/a/49228490
has body: I'm starting with Python 3, using Raspbian (from Debian), and using virtualenv. I understand how to create/use a virtualenv to "sandbox" different Python project, HOWEVER I'm a bit unclear on whether one should be setting up a different linux user for each project (assuming that the project/virtualenv will be used to create &amp; then run a daemon process on the linux box). So when creating separate python environments the question I think is should I be: creating a new linux user account for each deamon/acript I'm working on, so that both the python virtual environment, and the python project code area can live under directories owned by this user? perhaps just create one new non-administrator account at the beginning, and then just use this account for each project/virtual environmnet create everything under the initial admin user I first log with for raspbian (e.g. "pi" user) - Assume NO for this option, but putting it in for completeness.
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49228490
has answer: http://stackoverflow.com/a/49228732
answer count: 3
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85459968
tagged with: virtualenv
tagged with: virtualenvwrapper
has title: should new python virtualenv's be created with new linux user accounts?
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85459964
tagged with: linux
accepted answer: http://stackoverflow.com/a/49228268

http://stackoverflow.com/comment/85482232
has text: I fixed the migrations, but still the same error. `*** NameError: name 'tags_data'` is not defined.
type: AnswerComment
comment on: http://stackoverflow.com/a/49224874
score: 0
type: Comment

http://stackoverflow.com/q/49206173
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85417364
has body: enter code here class Movie() : def __init__(self, movie_title, move_storyline , trailer_youtube): self.title = movie_title self.storyline = move_storyline self.poster_image_url = poster_image_url self.trailer_youtube_url = trailer_youtube whats the erorr here !
has comment: http://stackoverflow.com/comment/85417407
tagged with: python
has title: TypeError: __init__() takes exactly 4 arguments (5 given)udacity
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49206202
downvote count: 4
upvote count: 0
has answer: http://stackoverflow.com/a/49206202
score: -4
answer count: 1

http://stackoverflow.com/comment/85434244
type: QuestionComment
has text: I added the versions.
score: 0
comment on: http://stackoverflow.com/q/49214915
type: Comment

http://stackoverflow.com/a/49222865
type: Answer
score: 0
accepted answer of: http://stackoverflow.com/q/49222813
has body: You need to change v = sum(value) to v = sum(hours) #sum the list of sleep hrs
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49222813

http://stackoverflow.com/comment/85377576
type: Comment
score: 0
type: QuestionComment
has text: Thank you larsks and hoyland. Larsks I tried your solution but that does not work. There are multiple Url values and I want to get all of them for the related Id.
comment on: http://stackoverflow.com/q/49185974

http://stackoverflow.com/comment/85625538
type: AnswerComment
has text: But, if the value in the column 'code' contains indentation, it doesn't work. The regex doesn't keep the indentation at the beginning of the code.
comment on: http://stackoverflow.com/a/49275167
type: Comment
score: 0

http://stackoverflow.com/comment/85331795
comment on: http://stackoverflow.com/q/49163031
type: Comment
score: 1
has text: Included my actual code, I just wanted a general idea of how to encode two branches in a while statement. Thanks in advance for the help.
type: QuestionComment

http://stackoverflow.com/q/49277168
has comment: http://stackoverflow.com/comment/85556945
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85557344
has answer: http://stackoverflow.com/a/49277377
favorite count: 0
type: Question
tagged with: object
tagged with: priority-queue
tagged with: heap
tagged with: python
has answer: http://stackoverflow.com/a/49277371
has title: Issue using heapq in python for a priority list
possible better answer: http://stackoverflow.com/a/49277371
accepted answer: http://stackoverflow.com/a/49277377
has body: I can't understand why my below code raise an error. I'm trying to build a priority list based on heapq module of Python. The only difference with a basic example of the module is that want to use it with custom objects in it it, instead of simple (int,int) or (int,str) tuples. import heapq class MyObject(): def __init__(self,a=0,name='toto'): self.a = a self.name = name if __name__ == '__main__': priority_list = [] heapq.heappush(priority_list,(1,MyObject())) heapq.heappush(priority_list,(1,MyObject())) This is the error I have: heapq.heappush(priority_list,(1,MyObject())) TypeError: '&lt;' not supported between instances of 'MyObject' and 'MyObject' The error is not raised if I use a different key to insert in the heap, but isn't heapq supposed to deal with same keys? I don't understand very well this behaviour. Thanks a lot
type: AnsweredQuestion
tagged with: list
answer count: 2

http://stackoverflow.com/q/49180329
tagged with: python
linked to: http://stackoverflow.com/q/12385179
has title: Python - Requests - will not upload files
has comment: http://stackoverflow.com/comment/85367065
has comment: http://stackoverflow.com/comment/85366493
has comment: http://stackoverflow.com/comment/85367354
score: 0
has comment: http://stackoverflow.com/comment/85368528
answer count: 0
has body: I am developing a workflow for a class I am taking. I am trying to leverage a tool which requires I upload two files and supply an email and a job name. I have tried many suggestions from this site and read the documentation for requests but nothing seems to work. This is my (messy) code: import requests, sys, urllib3, json, os START_URL = 'https://bmm.crick.ac.uk/~svc-bmm-swarmdock/submit.cgi' EMAIL = 'someAddress@domain.com' if len(sys.argv) != 3: print('Usage: -a receptor -a ligand') sys.exit(1) ''' with open('./Swarm Dock/pdb/1asu.pdb') as rec_file: rec_contents = rec_file.read() with open('./Swarm Dock/pdb/2msi.pdb') as lig_file: lig_contents = lig_file.read() ''' print('cwd: {}'.format(os.getcwd())) form_data = { 'formSubmitBut': 'Submit New Job', 'jobname': 'test1', 'email': EMAIL } #, 'receptorfile': rec_contents, 'ligandfile': lig_contents} files = { 'receptorfile': (open('./Swarm Dock/pdb/1ASU.pdb', 'rb'), 'fakepath/1asu.pdb'), #'receptorfile': ('1ASU',open('./Swarm Dock/pdb/1ASU.pdb', 'rb'), 'plain/text'), 'ligandfile': (open('./Swarm Dock/pdb/2MSI.pdb', 'rb'), 'fakepath/2msi.pdb') } response = requests.post(START_URL, files=files, data=form_data) print(response.content) Here is the output: b'&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;meta name="robots" content="noarchive"&gt;\n &lt;meta name="description" content="SwarmDock Server"&gt;\n &lt;meta name="keywords" content ="SwarmDock, The Francis Crick Institute, Mieczyslaw Torchala, Iain Moal, Raphael Chaleil, Juan Fernandez-Recio, Paul Bates"&gt;\n &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;&lt;link href=\'https://fonts.googleapis.com/css?family=Crafty+Girls\' rel=\'stylesheet\' type=\'text/css\'&gt;&lt;link rel="stylesheet" type="text/css" href="https://bmm.crick.ac.uk/~svc-bmm-swarmdock/sds.css" /&gt;&lt;title&gt;SwarmDock Server&lt;/title&gt;\n &lt;script type="text/javascript"&gt;\n function validateForm() {\n var ea = document.forms["sdsForm"]["email"].va…
has comment: http://stackoverflow.com/comment/85367031
has comment: http://stackoverflow.com/comment/85366356
has comment: http://stackoverflow.com/comment/85367738
tagged with: multipartform-data
tagged with: python-requests
has comment: http://stackoverflow.com/comment/85367961
type: Question
has comment: http://stackoverflow.com/comment/85367463
type: UnansweredQuestion

http://stackoverflow.com/a/49183882
type: Answer
answers question: http://stackoverflow.com/q/49183806
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49183806
has comment: http://stackoverflow.com/comment/85373842
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85374596
has body: You have two options: explicitly test for a list or dictionary, with isinstance() put your access in a try:...except and catch the TypeError, then proceed to treat it as a single element. It won't matter all that much which one you pick (but there can be a performance difference), pick the style you feel works best for your code. For example, if you used an isistance() test, you could add a list around the single element so the rest of your code doesn't have to change: for train_rt in trains_data['ctatt']['route']: line_name = train_rt['@name'] train_runs = train_rt.get('train', []) if not isinstance(train_runs, list): # single entry, wrap train_runs = [train_runs] for train_run in train_runs: # ... Note that if the 'train' key is missing, the above code again normalises by using an empty list. That allows you to avoid another if test, because now the for loop will not iterate at all. If you have a support contact for that API, I'd at least report the issue and point out that their data structure is inconsistent.
has comment: http://stackoverflow.com/comment/85373927

http://stackoverflow.com/q/49217121
has title: Time complexity of min, max on sets
tagged with: python
has answer: http://stackoverflow.com/a/49217271
has comment: http://stackoverflow.com/comment/85438304
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85438423
linked to: http://stackoverflow.com/q/1653970
answer count: 1
has comment: http://stackoverflow.com/comment/85438269
favorite count: 0
type: Question
score: 8
upvote count: 8
accepted answer: http://stackoverflow.com/a/49217271
downvote count: 0
has body: min, max have O(N) time complexity because they have to loop over the given list/string and check every index to find min/max. But I am wondering what would be the time complexity of min,max if used on a set? For example: s = {1,2,3,4} # s is a set using min/max we get: min(s) = 1 max(s) = 4 Since sets do not use indices like lists and strings, but instead operate using buckets that can be accessed directly, does the time complexity of min/max differ than the general case? Thank you!

http://stackoverflow.com/comment/85325150
comment on: http://stackoverflow.com/q/49159596
score: 0
has text: I think you are misconstruing the question: the problem is that I expect the subprocess to fail and I don't know how to get pytest to ignore that error.
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49205614
downvote count: 0
upvote count: 1
has body: It looks like you want to update money, so just reassign the result of the subtraction back to money. money = money - total Python has a shortcut operator you could use instead. money -= total
type: Answer
accepted answer of: http://stackoverflow.com/q/49205577
answers question: http://stackoverflow.com/q/49205577
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49215610
linked to: http://stackoverflow.com/q/6260089
has comment: http://stackoverflow.com/comment/85435756
tagged with: python
has title: Python - Issue using list pop() method in loop
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/85435702
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49215633
has body: The following code: list = ['A', 'B', 'C', 'D', 'E', 'F'] for item in list: removed_item = list.pop() print(removed_item + ' has been removed from the list') print(list) Gives the result: F has been removed from the list E has been removed from the list D has been removed from the list ['A', 'B', 'C'] When I was expecting it to loop through the whole list and return and empty list. Why is it stopping half way through the list and leaving the A, B and C values in the list?
accepted answer: http://stackoverflow.com/a/49215633
has comment: http://stackoverflow.com/comment/85435378

http://stackoverflow.com/q/49129451
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/52701751
type: UnansweredQuestion
downvote count: 0
tagged with: websocket
has title: how to use ws(websocket) via ngrok
tagged with: python
tagged with: localhost
score: 3
has body: I want to share my local WebSocket on the internet but ngrok only support HTTP but my ws.py address is ws://localhost:8000/ it is good working on localhost buy is not know how to use this on the internet?
answer count: 2
has answer: http://stackoverflow.com/a/75994510
upvote count: 3
tagged with: ngrok
tagged with: serve

mfcc
type: Tag
tag name: mfcc
tags question: http://stackoverflow.com/q/49196184

http://stackoverflow.com/q/49207867
accepted answer: http://stackoverflow.com/a/49395134
has comment: http://stackoverflow.com/comment/85431228
has comment: http://stackoverflow.com/comment/85426717
has comment: http://stackoverflow.com/comment/85422279
type: AnsweredQuestion
score: 0
has body: When i use Entry Widget in line "inputs = Entry(row)" the output form can only take single string, as soon i update the code to use Text Wiget "inputs = Text(row)" the output form accepts multi line string inputs but the buttons disappear, Please help not sure why the buttons disappear from tkinter import * fields = 'Section1','Section2' def fetch(entries): for entry in entries: field = entry[0] text = entry[1].get() print('%s \n%s\n' % ("\n====================================\n" + field + "\n====================================\n", text)) def makeform(root, fields): entries = [] for field in fields: row = Frame(root) labels = Label(row, width=35, text=field, anchor='w') inputs = Entry(row) # This is the line where i tried Text Widget row.pack(side=TOP, fill=X, padx=15, pady=15) labels.pack(side=LEFT) inputs.pack(side=RIGHT, expand=YES, fill=X) entries.append((field, inputs)) return entries if __name__ == '__main__': root = Tk() root.title('Form') entries = makeform(root, fields) root.bind('&lt;Return&gt;', (lambda event, e=entries: fetch(e))) b1 = Button(root, text='Generate', command=(lambda e=entries: fetch(e))) b1.pack(side=LEFT, padx=5, pady=5) b2 = Button(root, text='Quit', command=root.quit) b2.pack(side=LEFT, padx=5, pady=5) root.mainloop()
has comment: http://stackoverflow.com/comment/85422383
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49395134
has comment: http://stackoverflow.com/comment/85424630
type: Question
tagged with: python-3.x
has title: Buttons disappear form the GUI Form when i use Text Widget in Tkinter
tagged with: tkinter

http://stackoverflow.com/a/49263431
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49240332
upvote count: 5
answers question: http://stackoverflow.com/q/49240332
type: Answer
has body: The error is clear: you are trying to apply a style to a column. openpyxl provides rows and columns as a convenience but these are always a collection of cells over which you need to loop. for cell in ws['A']: cell.fill = whiteFill
score: 5
type: AcceptedAnswer

http://stackoverflow.com/q/49268647
tagged with: fft
tagged with: transform
accepted answer: http://stackoverflow.com/a/49289903
has answer: http://stackoverflow.com/a/49268717
has answer: http://stackoverflow.com/a/49289903
tagged with: spectrogram
tagged with: python
has comment: http://stackoverflow.com/comment/85541111
type: AnsweredQuestion
tagged with: audio
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85541043
upvote count: 1
has body: I am trying to create an amplitude vs frequency spectrogram of an audio file in Python. what is the procedure to do so? Some sample code would be of great help.
has comment: http://stackoverflow.com/comment/85541473
has title: Creating an amplitude vs frequency spectrogram of an audio file in Python
downvote count: 1
possible better answer: http://stackoverflow.com/a/49268717
favorite count: 0
has comment: http://stackoverflow.com/comment/85540923
type: Question

http://stackoverflow.com/a/49274373
has body: Use Numpy's broadcasting features: In [23]: arr1d[:, None, None] + arr3d Out[23]: array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]], [[20, 21, 22], [23, 24, 25], [26, 27, 28]]]) This basically copies the content of arr1d across the other two dimensions (without actually copying, it just provides a view of the memory which looks like it). Instead of None, you can also use numpy.newaxis. Alternatively, you can also use reshape: In [32]: arr1d.reshape(3, 1, 1) + arr3d Out[32]: array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]], [[20, 21, 22], [23, 24, 25], [26, 27, 28]]])
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49274345
downvote count: 0
answers question: http://stackoverflow.com/q/49274345
score: 1
upvote count: 1

http://stackoverflow.com/comment/85418177
has text: @cdarke I want to append all the Values to a single list - mylist
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49206561
score: 0

http://stackoverflow.com/q/49137698
tagged with: iteration
has answer: http://stackoverflow.com/a/49138092
type: AnsweredQuestion
tagged with: python
type: Question
score: 0
has title: Python iterating over array with different sizes
has body: I am trying to perform a simple calculation and place the outputs into an array. I begin by setting values and arrays and then iterating through the arrays and performing the calculation. Finally, I try to place the calculated output into an array filled with zeroes. However, I get the following error message: "for i in range(b[0]): TypeError: only integer scalar arrays can be converted to a scalar index." Could someone please help me understand how to properly iterate through an array and perform calculations? Thank you for your time. import numpy as np S = np.linspace(0,37,100) T = np.array([5.,25.,30.]) delta = 25. - T f = 1575e6 tt = T.reshape(3,1) beta = S*tt b = np.zeros(np.shape(beta)).reshape(100,3) #Calculate and put into a 3x100 or 100x3 array for i in range(b[0]): for j in range(T[0]): b[i,j]= 1.00 + 2.282e-5*S[i]*[j] - 7.638e-4*S[i] - 7.76e-6*S[i]**2 + 1.105e-8*S[i]**3
answer count: 1
tagged with: arrays
accepted answer: http://stackoverflow.com/a/49138092
tagged with: calculation

http://stackoverflow.com/comment/85347287
has text: @Yu-Yang Right, agree. Now I've realized that real memory consumption is increasing during training process, and not initialization.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49152291
type: QuestionComment

http://stackoverflow.com/comment/85326258
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49160369
score: 0
has text: Ahhhhh...I was using it completely wrong then! Thanks for the helpful comments. @mods: Please close this question.

http://stackoverflow.com/a/49162073
answers question: http://stackoverflow.com/q/49162010
type: AcceptedAnswer
score: 4
has comment: http://stackoverflow.com/comment/85330081
has comment: http://stackoverflow.com/comment/85330149
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49162010
downvote count: 0
has body: This is one way. First create a dictionary mapping, then apply it in a list comprehension. a = ["a", "b"] b = ["a (x)"] b_dict = {v.split(' ')[0]: v for v in b} a = [b_dict.get(i, i) for i in a] # ['a (x)', 'b']

http://stackoverflow.com/q/49210172
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49210229
possible better answer: http://stackoverflow.com/a/49210241
has answer: http://stackoverflow.com/a/49210226
has comment: http://stackoverflow.com/comment/85425015
has answer: http://stackoverflow.com/a/49210241
has answer: http://stackoverflow.com/a/49210227
tagged with: python
has answer: http://stackoverflow.com/a/49210192
answer count: 6
score: 2
upvote count: 2
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/27083445
has body: ths is probably a dumb question... I'm working with some data that is generated, line by line, after an iteration and I'd like to store the result for further processing in a multiline string. As an example, let me show you this: is_string = """""""" for i in range(1, 101): is_string += str(i) print(is_string) The result is: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 But I'd like it to be a multiline string: 1 2 3 4 5 ... 99 100 What is te correct way to achieve this?
has answer: http://stackoverflow.com/a/49210225
has title: Generate a multiline string from an iteration
favorite count: 0
has answer: http://stackoverflow.com/a/49210229

http://stackoverflow.com/comment/85470240
has text: This looks like a straight forward CSV, without any JSON
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49233156

http://stackoverflow.com/comment/85533444
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49258320
has text: Thank you! I was halfway there, missing the "dt.strftime('%b-%Y')" argument.
score: 0

http://stackoverflow.com/q/49251344
has answer: http://stackoverflow.com/a/49274548
accepted answer: http://stackoverflow.com/a/49274548
has comment: http://stackoverflow.com/comment/85508485
answer count: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/85506891
tagged with: python-requests
favorite count: 0
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/85508884
has comment: http://stackoverflow.com/comment/85508943
has comment: http://stackoverflow.com/comment/85507253
has comment: http://stackoverflow.com/comment/85509132
score: -2
has body: I'm trying to scrape the contents of tags from a web page. My code is: from bs4 import BeautifulSoup import requests import sys reload(sys) sys.setdefaultencoding('utf-8') url = 'https://www.safaribooksonline.com/library/view/linux-performance-optimization/9780134985961' req = requests.get(url) soup = BeautifulSoup(req.text, 'html.parser') lessons = soup.find_all('li', class_='toc-level-1') lesson = lessons[0] print(lesson) My page has an element: (Obtained directly from the output of my DOM inspector in firefox)... Introduction Linux Performance Optimization: Introduction However, when I use requests and the bs4 modules to scrape the data, with the above code, the output I get is: Introduction Linux Performance Optimization: Introduction Notice the href values of the tags? They're supposed to be relative URLs like: /library/view/linux-performance-optimization/9780134985961/LPOC_00_00_00.html but I get absolute ones - and that too wrong sometimes: https://www.safaribooksonline.comhttps://www.safaribooksonline.com/library/view/linux-performance-optimization/9780134985961/LPOC_00_00_00.html. I have no clue how the domain name gets prefixed to the link url, since only the href value is given in the original HTML, unless requests or bs4 is doing this. All my previous scripts that used this same method are also producing a similar error. Did something change on the side of the modules, or am I doing something wrong?
tagged with: python
has title: Python requests and BeautifulSoup4 .get('href') returning absolute address when scraping from Safaribooksonline
has comment: http://stackoverflow.com/comment/85508778
type: AnsweredQuestion
upvote count: 0
downvote count: 2

http://stackoverflow.com/comment/85335611
type: Comment
comment on: http://stackoverflow.com/q/49165004
type: QuestionComment
score: 0
has text: I tried py -3 -m django --version and with django-admin, neither worked.

http://stackoverflow.com/comment/85311749
type: QuestionComment
has text: do you have a question?
comment on: http://stackoverflow.com/q/49153682
type: Comment
score: 4

http://stackoverflow.com/q/49203550
type: Question
score: 3
answer count: 5
has answer: http://stackoverflow.com/a/49203565
tagged with: python
linked to: http://stackoverflow.com/q/1271320
tagged with: generator
has body: I am practising with generators and I wonder why the following code does not print 16 pairs but only 4. def range_generator_function(my_range): for i in my_range: yield i gen1=range_generator_function(range(1,5)) gen2=range_generator_function(range(1,5)) def pairs_generator_function(gen1,gen2): for it1 in gen1: for it2 in gen2: yield [it1,it2] my_gen = pairs_generator_function(gen1,gen2) for it in my_gen: print(it) The output is [1, 1] [1, 2] [1, 3] [1, 4] While the output I expect is [1, 1] [1, 2] [1, 3] [1, 4] [2, 1] [2, 2] [2, 3] [2, 4] [3, 1] [3, 2] [3, 3] [3, 4] [4, 1] [4, 2] [4, 3] [4, 4]
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/49203620
downvote count: 0
possible better answer: http://stackoverflow.com/a/49203574
has comment: http://stackoverflow.com/comment/85412619
accepted answer: http://stackoverflow.com/a/49203565
has answer: http://stackoverflow.com/a/49203671
has answer: http://stackoverflow.com/a/49203574
has answer: http://stackoverflow.com/a/49203611
has title: Python nested generators not working
favorite count: 0

http://stackoverflow.com/a/49201950
answers question: http://stackoverflow.com/q/49201897
upvote count: 0
downvote count: 2
has body: sum(map(lambda schoolAmount: schoolAmount.amount, school))
score: -2
type: Answer

http://stackoverflow.com/q/49213440
has comment: http://stackoverflow.com/comment/85443458
has body: While trying to use GTK 3 frame clock in a Python 3 script, I discovered that I don't understand how to invoke the equivalent of gdk_frame_clock_get_refresh_info(). I have first tried the obvious, to call the get_refresh_info() method on the object returned by get_frame_clock(): from gi.repository import Gtk as gtk, GLib as glib w = gtk.Window() w.show() glib.idle_add(lambda: print(w.get_frame_clock().get_refresh_info())) gtk.main() That fails with: TypeError: Gdk.FrameClock.get_refresh_info() takes exactly 4 arguments (1 given) The C function indeed takes four arguments, but the last two are pointers to gint64. In the Python version the function raises type errors when called with anything except three numbers. When invoked with three numbers, the whole process crashes with a segmentation fault. Is this a bug in GDK's introspection specs for gdk_frame_clock_get_refresh_info? Is there a workaround, or a different way to obtain the refresh interval?
tagged with: gobject-introspection
tagged with: gtk
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85435362
score: 3
upvote count: 3
accepted answer: http://stackoverflow.com/a/49225951
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49225951
has comment: http://stackoverflow.com/comment/85435178
has comment: http://stackoverflow.com/comment/85435228
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85438710
has comment: http://stackoverflow.com/comment/85449331
has comment: http://stackoverflow.com/comment/85435103
has comment: http://stackoverflow.com/comment/85452131
tagged with: python
has title: How does one call `gdk_frame_clock_get_refresh_info` from Python

http://stackoverflow.com/a/49165473
type: Answer
accepted answer of: http://stackoverflow.com/q/49163994
has body: I have a complex solution. def get_vacation_info(x): vacations = sorted(x["DATE"][x["VACATION"]=="True"].tolist()) df_x = pd.DataFrame(vacations, columns=["DATE"]).apply(pd.to_datetime) df_x["year"] = df_x.DATE.dt.year df_x["week"] = df_x.DATE.dt.weekofyear df_x["quarter"] = df_x.DATE.dt.quarter def get_subtotals(y): total = len(y) perweek = y["week"].value_counts().reset_index() weekindex = pd.DataFrame([i for i in range(1, 53)], columns=["index"]) merged_week = pd.merge(weekindex, perweek, on=["index"], how="left").fillna(0).astype(int) perweek = merged_week["week"].tolist() perquarter = y["quarter"].value_counts().reset_index() quarterindex = pd.DataFrame([i for i in range(1, 5)], columns=["index"]) merged_quater = pd.merge(quarterindex, perquarter, on=["index"], how="left").fillna(0).astype(int) perquarter = merged_quater["quarter"].tolist() return {"total": total, "perweek": perweek, "perquarter": perquarter} subtotals = df_x.groupby("year").apply(lambda y: get_subtotals(y)).to_json() return {"vacations": vacations, "subtotals": subtotals} result = df.groupby("NAME").apply(lambda x: get_vacation_info(x))
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49163994
has comment: http://stackoverflow.com/comment/85366698

http://stackoverflow.com/a/49237289
score: 4
has comment: http://stackoverflow.com/comment/135697009
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/49235486
has body: This solution works without extra arguments, and without having to replace/delete files across environments. Make settings.py decide which file to load Let's assume your Django project is named MyDjangoApp. Create the config/ dir in your Django project's root dir, and one .py file per environment, e.g. like this: config/ local.py dev.py prod.py MyDjangoApp/ settings.py There is no logical limit to the number of environments, I just added the three I usually have. Then, inside MyDjangoApp/settings.py we can add the logic to choose which settings file to load. """ Django settings for MyDjangoApp project. """ import os # Begin: Custom per-env settings import socket # Use the appropriate logic to understand "where" we're running HOST = socket.gethostname() configs = { 'localhost': 'local', # replace 'localhost' with whatever your machine name is 'dev.mysite.com': 'dev', 'www.mysite.com': 'production', } config = 'config.{}'.format(configs[HOST]) settings_module = __import__(config, globals(), locals(), ['MyDjangoApp', ]) try: for setting in dir(settings_module): # Only fully-uppercase variables are supposed to be settings if setting == setting.upper(): locals()[setting] = getattr(settings_module, setting) except Exception: # you may ignore this exception, the print() is for debugging purposes print(Exception) # End: Custom per-env settings # ... the rest of the common settings go here Please note: this logic chooses the settings file to load based on the hostname of the server which is running the Django app. It's just an example- you can implement any other logic that works for you. Change only what's needed The good news is, settings.py can still hold the vast majority of your settings, and the files inside config/ just need to contain the settings that change across your environments, e.g.: DATABASES DEBUG ADMINS LOGGING Avoid --settings in the commandline You can set the Django settings as a shell environment variable, like this: export DJANGO_SETTINGS_MODULE=MyDjan…
has comment: http://stackoverflow.com/comment/135421006
downvote count: 0

http://stackoverflow.com/comment/85338372
type: AnswerComment
comment on: http://stackoverflow.com/a/49166414
type: Comment
has text: Thank you for the response. This helps me understand why the code works in that way and clears up my assumptions. I'll use your approach.
score: 0

http://stackoverflow.com/q/49214764
upvote count: 1
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85434351
has comment: http://stackoverflow.com/comment/85433998
answer count: 1
has comment: http://stackoverflow.com/comment/85434395
has answer: http://stackoverflow.com/a/49215057
has title: Django: How to use get_form() method in CreateView?
score: 1
favorite count: 0
has body: I have a CustomForm in my forms.py that needs the public key of the URL. I mean e.g. /book/&lt;pk&gt;/create. In my views.py there is this CreateView: class CustomCreateView(CreateView): form_class = CustomForm Now my question is how can I pass the public key of the URL to the CustomForm. The CustomForm expect a keyword argument named pk. I thing the get_form() method could help, but I am not sure and do not know how to use it: https://docs.djangoproject.com/en/2.0/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.get_form
type: Question
has comment: http://stackoverflow.com/comment/85434029
downvote count: 0
tagged with: django

http://stackoverflow.com/q/49146274
has answer: http://stackoverflow.com/a/49146302
has comment: http://stackoverflow.com/comment/85297204
type: Question
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/7079241
has comment: http://stackoverflow.com/comment/85297449
answer count: 1
tagged with: python
tagged with: dictionary
has title: Find the id of a dict within a list, by matching the dict's value (without a loop)
has comment: http://stackoverflow.com/comment/85297203
score: 0
tagged with: list
has body: I have list as this : [{"id": 101, "name": "music1"}, {"id": 102, "name": "music2"}] how do I get a id of object matching with specific name: for e.g, input: music2 output : 102
linked to: http://stackoverflow.com/q/7079241
has comment: http://stackoverflow.com/comment/85297409

http://stackoverflow.com/comment/85555113
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49276296
type: AnswerComment
has text: Still, tobias_k suggestion looks more like python.

http://stackoverflow.com/q/49181337
has title: Merge list of dictionary by common key
tagged with: python
tagged with: dictionary
downvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85368256
answer count: 1
has comment: http://stackoverflow.com/comment/85368768
has comment: http://stackoverflow.com/comment/85368286
has comment: http://stackoverflow.com/comment/85368357
favorite count: 0
type: Question
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49182153
has body: I am trying to merge the list of dictionaries inside a list based on a key. The sample input for the same looks like: my_data = { "id_1": [ {"er": {"ip": "myhost", "port": 80}}, {"ef": {"ip": "myhost", "port": 80}}, {"er": {"app": "falsk", "port1": 81}}, {"ef": {"app": "django", "port1": 85}} ], "id_2": [ {"er": {"ip": "myhost", "port": 80}}, {"ef": {"ip": "myhost", "port": 80}}, {"er": {"app": "falsk"," port1": 81}}, {"ef": {"app": "django", "port1": 85}} ] } I am trying to get an output looks like this: res_data = { "id_1": [ {"er": {"ip": "myhost", "port": 80, "app": "falsk"," port1": 81}}, {"ef": {"ip": "myhost", "port": 80, "app": "django", "port1": 85}} ], "id_2": [ {"er": {"ip": "myhost", "port": 80, "app": "falsk", "port1": 81}}, {"ef": {"ip": "myhost", "port": 80, "app": "django", "port1": 85}} ] } Is there any easy method in python to achieve it? Update : Solution based on comments and initial thoughts def merge_list_of_dict(data): merged_dict = dict() for k, v in data.items(): tmp_tems = dict() for j in v: for ki, vi in j.items(): if ki in tmp_tems: tmp_tems[ki].update(vi) else: tmp_tems[ki] = vi merged_dict[k] = tmp_tems return merged_dict

http://stackoverflow.com/comment/85392973
type: QuestionComment
score: 0
has text: Yes, the different names would be the multiple keys.
comment on: http://stackoverflow.com/q/49194107
type: Comment

http://stackoverflow.com/comment/85554305
comment on: http://stackoverflow.com/q/49275661
type: Comment
type: QuestionComment
has text: I think it's just a difference in encoding
score: 0

http://stackoverflow.com/comment/85511727
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49254041
has text: have not tried that but is that a "hacky" way to get it working? What if I have other changes later on? Do I just keep using the heroku postgres database for the migrations

http://stackoverflow.com/comment/85413784
comment on: http://stackoverflow.com/a/49204061
score: 1
has text: Tried the specific case and it's exactly what I needed!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85451262
comment on: http://stackoverflow.com/q/49223876
score: 1
type: Comment
has text: The underscore-prefixed modules are for the implementation of the non-underscore modules. You shouldn’t need them and they aren’t documented as part of the standard library.
type: QuestionComment

http://stackoverflow.com/comment/85334062
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49163579
has text: Yes, it's possible - I got some `nan`s returned from the answer, so even though this is less efficient I thought it was necessary. I could use `else 0` but it makes sense in my context to have `else -1` because that is a numeric representation of an impossibility in my code (I can never have a negative mean).

http://stackoverflow.com/q/49153072
score: 2
downvote count: 0
has body: I want to export some data to an app that is installed on my mobile phone. So I exported some dummy data in the app, in order to investigate how I can produce data to import. First step: It's a gzipped file. No problem, that is what gunzip is for. Second step: $ file export export: Smile binary data version 0: binary encoded, shared String values disabled, shared field names I have never heard of a smile file (which is quite ugly to google because of the emoticons), but I found pySmile. Problem: I am not even a noob regarding python. To be more specific: I don't know anything about python. But I tried it anyways. import pysmile import sys f = open(sys.argv[1],'r') a = f.read() print repr(a) o=pysmile.decode(a) print o This worked pretty well with a smile file I generated myself, but with the given export smile file I get the following error: Traceback (most recent call last): File "dec.py", line 7, in &lt;module&gt; o=pysmile.decode(a) File "/usr/local/lib/python2.7/dist-packages/pysmile/decode.py", line 224, in decode state.copy_shared_value_string() File "/usr/local/lib/python2.7/dist-packages/pysmile/decode.py", line 151, in copy_shared_value_string raise SMILEDecodeError('Cannot lookup shared value, sharing disabled!') pysmile.decode.SMILEDecodeError: Cannot lookup shared value, sharing disabled! After that I tried to investigate where the difference between the two files is: export: Smile binary data version 0: binary encoded, shared String values disabled, shared field names enabled dummyf: Smile binary data version 0: binary encoded, shared String values enabled, shared field names enabled This in addition to the Error Trace lead me to my question: How can I enable sharing in pysmile (decode and encode), and is there another python-free method to convert a smile file to a text file and (which is even more important) the other way around?
tagged with: python
favorite count: 0
type: Question
upvote count: 2
answer count: 0
type: UnansweredQuestion
has title: How to open smile file

http://stackoverflow.com/comment/85362866
score: 0
has text: Yes, this was exactly what I was looking for. Thanks. I didn't even know that it was possible to iloc multiple lines from the original dataframe using a list of indices.
type: Comment
comment on: http://stackoverflow.com/a/49162277
type: AnswerComment

http://stackoverflow.com/comment/85538290
score: 2
has text: If you _do_ need a string representing a dictionary instead of the dictionary itself, it's very likely that what you actually need is JSON. Which means you should first manipulate the dictionary using normal Python stuff, and then do a `json.dumps(d)` to get the string to pass to the API at the end.
comment on: http://stackoverflow.com/q/49267392
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49246721
tagged with: sql
score: 1
answer count: 1
downvote count: 1
has title: How to store Users' Location in a Django/Postgres Application
favorite count: 0
accepted answer: http://stackoverflow.com/a/49288660
type: Question
has comment: http://stackoverflow.com/comment/85514083
tagged with: geodjango
has comment: http://stackoverflow.com/comment/85506298
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49288660
has comment: http://stackoverflow.com/comment/85520841
tagged with: postgis
upvote count: 2
type: AnsweredQuestion
has body: I am developing a Phone app which sends a user's location to the backend every time the app is opened. My goal is to store as much location data for the user as possible so I can do some machine learning to calculate which posts in their normal area of movement every day will pertain most to them. I use GeoDjango and PostGis to make the application location-aware, and am struggling to determine which data structure in the database will best fit this scenario. The question comes down to whether I should give each user a location = pg_fields.ArrayField() attribute which will end up being extremely large, or use location=models.ManyToManyField(UserLocation). I know toast tables are an issue in Postgres with large arrays, but are they a big enough issue where it would not be worth the stress when trying to extract the data for the user when running machine learning algorithms?

http://stackoverflow.com/q/49151947
type: Question
tagged with: python-3.x
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/85308043
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/139010191
has body: How can I change the compiler that is used for compiling the Python binaries? I have Anaconda on my Mac (macOS 10.13) but it uses clang instead of gcc-mp-6 that I neeed.
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/85309451
has title: How to use Anaconda with gcc instead of clang
has comment: http://stackoverflow.com/comment/85310185
tagged with: python

http://stackoverflow.com/comment/85531957
score: 1
has text: `elif x not in:` something is missing here...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49263997

http://stackoverflow.com/a/49137178
has body: You want another dict, with hello and hi as keys. stuff = { 'hello': hello, 'hi': hi } randomOpt = random.choice(stuff[categ][opt])
score: 2
answers question: http://stackoverflow.com/q/49137082
type: Answer
upvote count: 2
downvote count: 0

http://stackoverflow.com/q/49167615
downvote count: 0
has comment: http://stackoverflow.com/comment/85341895
upvote count: 7
has comment: http://stackoverflow.com/comment/85340834
has comment: http://stackoverflow.com/comment/85343017
favorite count: 0
type: Question
has title: TypeError: unsupported operand type(s) for +: 'map' and 'float'
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/57688732
has answer: http://stackoverflow.com/a/49168814
tagged with: python
has answer: http://stackoverflow.com/a/49167653
has comment: http://stackoverflow.com/comment/85341379
has body: I was practicing tesorflow on Colaboratory and my code is as below. There is some issue, the error message is "TypeError: unsupported operand type(s) for +: 'map' and 'float'" Can someone tell me what's wrong? thanks! import matplotlib.pyplot as plt import numpy as np x = np.arange(20) y = map(lambda x: x + np.random.randn(1), x) a, b = np.polyfit(x, y, 1) plt.plot(x, y, 'o', np.arange(20), a*np.arange(20)+b, '-');**
answer count: 3
has comment: http://stackoverflow.com/comment/85340784
score: 7

http://stackoverflow.com/comment/85538838
score: 0
comment on: http://stackoverflow.com/a/49267208
has text: Sorry, I don't know how to format code within a comment reply. Thank you for devoting your time towards my issue :)
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49241401
has body: I'm trying to efficiently replicate numpy's ndarray.choose() method. Here's a numpy example of what I'm looking for: b = np.arange(15).reshape(3, 5) c = np.array([1,0,4]) c.choose(b.T) # trying to replicate in tensorflow -&gt; array([ 1, 5, 14]) The best I've been able to do with this is generate a batch_size square matrix (which is huge if batch size is huge) and take the diagonal of it: tf_b = tf.constant(b) tf_c = tf.constant(c) sess.run(tf.diag_part(tf.gather(tf.transpose(tf_b), tf_c))) -&gt; array([ 1, 5, 14]) Is there a way to do this that is just linear in the first dimension (instead of squared)?
tagged with: numpy
has title: How to replicate numpy.choose() in tensorflow?
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49241772
answer count: 1
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85490388
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85486716
accepted answer: http://stackoverflow.com/a/49241772
tagged with: python

http://stackoverflow.com/a/49164059
answers question: http://stackoverflow.com/q/49160750
score: 0
has comment: http://stackoverflow.com/comment/85376545
has comment: http://stackoverflow.com/comment/85356630
has comment: http://stackoverflow.com/comment/85356586
has comment: http://stackoverflow.com/comment/85440381
type: Answer
has body: does it open in a new page/tab? if not, you can back to the page by the previous button driver.execute_script("window.history.go(**x**)") where x = number of page/s, eg. if you need to go back 2 pages, value should be -2

http://stackoverflow.com/a/49149615
answers question: http://stackoverflow.com/q/49148280
has comment: http://stackoverflow.com/comment/85306046
has body: if you have used any sort of version control, it's just commit and push/pull to the server. if not, you have to copy the code, paste it in the server, restart the application and it work's with new code. best approach is make a service, deploy the code with git version control, run the service and you are good to go. service will start automatically in case of system-restart and such.
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/85349606

http://stackoverflow.com/comment/85431190
score: 0
comment on: http://stackoverflow.com/q/49213003
type: Comment
has text: I'd like to keep them ideally, but omitting them is a viable option
type: QuestionComment

file
tags question: http://stackoverflow.com/q/49197801
tags question: http://stackoverflow.com/q/49197103
type: Tag
tags question: http://stackoverflow.com/q/49265474
tags question: http://stackoverflow.com/q/49206353
tags question: http://stackoverflow.com/q/49179656
tags question: http://stackoverflow.com/q/49221743
tags question: http://stackoverflow.com/q/49203506
tags question: http://stackoverflow.com/q/49182367
tags question: http://stackoverflow.com/q/49132073
tags question: http://stackoverflow.com/q/49160512
tags question: http://stackoverflow.com/q/49250575
tag name: file
tags question: http://stackoverflow.com/q/49169824
tags question: http://stackoverflow.com/q/49163978
tags question: http://stackoverflow.com/q/49224917
tags question: http://stackoverflow.com/q/49167418
tags question: http://stackoverflow.com/q/49266218
tags question: http://stackoverflow.com/q/49223294
tags question: http://stackoverflow.com/q/49267452
tags question: http://stackoverflow.com/q/49154607
tags question: http://stackoverflow.com/q/49192469
tags question: http://stackoverflow.com/q/49210678
tags question: http://stackoverflow.com/q/49260329
tags question: http://stackoverflow.com/q/49259470
tags question: http://stackoverflow.com/q/49175172
tags question: http://stackoverflow.com/q/49200074
tags question: http://stackoverflow.com/q/49220409
tags question: http://stackoverflow.com/q/49122128
tags question: http://stackoverflow.com/q/49185754

http://stackoverflow.com/a/49160336
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49160190
type: Answer
has comment: http://stackoverflow.com/comment/85326167
has comment: http://stackoverflow.com/comment/85326089
has body: Here's one way to do it: In [15]: dfrm Out[15]: A B C 0 0.948898 0.587032 0.131551 1 0.385582 0.275673 0.107135 2 0.849599 0.696882 0.313717 3 0.993080 0.510060 0.287691 4 0.994823 0.441560 0.632076 5 0.711145 0.760301 0.813272 6 0.932131 0.531901 0.393798 7 0.965915 0.812821 0.287819 8 0.782890 0.478565 0.960353 9 0.908078 0.850664 0.912878 In [16]: windows Out[16]: [1, 2, 3] In [17]: pandas.DataFrame( {c: dfrm[c].rolling(windows[i]).mean() for i, c in enumerate(dfrm.columns)} ) Out[17]: A B C 0 0.948898 NaN NaN 1 0.385582 0.431352 NaN 2 0.849599 0.486277 0.184134 3 0.993080 0.603471 0.236181 4 0.994823 0.475810 0.411161 5 0.711145 0.600931 0.577680 6 0.932131 0.646101 0.613049 7 0.965915 0.672361 0.498296 8 0.782890 0.645693 0.547323 9 0.908078 0.664614 0.720350 As @Manish Saraswat mentioned in the comments, you can also express the same thing as dfrm[c].rolling_mean(windows[i]). Further, you can use sequences as the items in windows if you want, and they would express a custom window shape (size and weights), or any of the other options with different rolling aggregations and keywords.
score: 1

http://stackoverflow.com/q/49181234
tagged with: python
type: AnsweredQuestion
score: 2
answer count: 1
has body: given import pyparsing as pp lines = '''\ (xcoord -23899.747) (ycoord 14349.544) (elev 23899) (region "mountainous") (rate multiple)''' leftParen = pp.Literal('(') rightParen = pp.Literal(')') doublequote = pp.Literal('"') v_string = pp.Word(pp.alphanums) v_quoted_string = pp.Combine( doublequote + v_string + doublequote) v_number = pp.Word(pp.nums+'.'+'-') keyy = v_string valu = v_string | v_quoted_string | v_number item = pp.Group( pp.Literal('(').suppress() + keyy + valu + pp.Literal(')').suppress() items = pp.ZeroOrMore( item) dicct = pp.Dict( items) pp.ParserElement.setDefaultWhitespaceChars('\r\n\t ') print "item yields: " , item.parseString( lines).dump() print "items yields: " , items.parseString( lines).dump() print "dicct yields: ", dicct.parseString( lines).dump() gives item yields: 'xcoord', '-23899.747' [0]:['xcoord', '-23899.747'] items yields: 'xcoord', '-23899.747' [0]:['xcoord', '-23899.747'] dicct yields: 'xcoord', '-23899.747' [0]:['xcoord', '-23899.747'] Hm. I'd expect to see five items within dicct. My use of Dict, ZeroOrMore and Group seem consistant with other examples on the net. It seems like only the first item gets matched. What am I doing wrong? TIA, code-warrior
has title: building a dictionary from a string containing one or more tokens
tagged with: pyparsing
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49182991
upvote count: 2
has answer: http://stackoverflow.com/a/49182991
downvote count: 0

http://stackoverflow.com/comment/87761056
score: 0
has text: @LordDagon32thanks for asking and being a nice guy that upvote some answer that was useful for you :)
type: Comment
comment on: http://stackoverflow.com/a/49163998
type: AnswerComment

http://stackoverflow.com/comment/85435987
comment on: http://stackoverflow.com/q/49215960
score: 0
has text: Please [edit] your question to include code. Not the comments
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49219328
has answer: http://stackoverflow.com/a/49219568
has answer: http://stackoverflow.com/a/49219443
has answer: http://stackoverflow.com/a/49223250
has comment: http://stackoverflow.com/comment/85442787
tagged with: string
favorite count: 0
possible better answer: http://stackoverflow.com/a/49219554
type: Question
tagged with: python-3.x
answer count: 9
has comment: http://stackoverflow.com/comment/85442368
has answer: http://stackoverflow.com/a/49219554
downvote count: 8
has answer: http://stackoverflow.com/a/49219371
has comment: http://stackoverflow.com/comment/85442369
tagged with: python
has answer: http://stackoverflow.com/a/49223896
has title: Word with most 'o' characters
upvote count: 11
has answer: http://stackoverflow.com/a/49219378
has body: I need to write a Python function that returns the word from the string with largest number of 'o' characters. For example, get_most_ooo_word(['aa ao ooo']) should return ['ooo'] and get_most_ooo_word(['aa ao oa aaaooo aooqq aoooq']) should return ['aaaooo', 'aoooq']. I tried this: def get_most_ooo_word(words): k=0 for i in range(len(words)-1): if words[i].count('o')&gt;words[i-1].count('o'): k=words[i] return(k) The problem is that this list consists only of 1 element – the whole string – and I don't know how to separate words in this list. upd: actually, there was a mistake in the task: the input should be a string, not a list
accepted answer: http://stackoverflow.com/a/49219499
type: AnsweredQuestion
score: 3
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49219499
has answer: http://stackoverflow.com/a/49219429

http://stackoverflow.com/comment/85452806
type: QuestionComment
comment on: http://stackoverflow.com/q/49224336
score: 0
has text: Hi @Damon. The code you provided has an indentation error (see the `for` loop that goes beneath the `while True` loop). Could you please update it so that it runs without errors? That can speed up the feedback you'll get for this question.
type: Comment

http://stackoverflow.com/a/49264040
score: 0
has comment: http://stackoverflow.com/comment/85536738
type: Answer
has body: Well, you can do it with gzip module: body_stream = StringIO.StringIO(body) gzipper = gzip.GzipFile(fileobj=body_stream) data = gzipper.read() print data[:25]
answers question: http://stackoverflow.com/q/49263623

http://stackoverflow.com/a/49252300
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85508432
answers question: http://stackoverflow.com/q/49251163
type: Answer
has body: Here is the easiest way to do this, in one line: df["Original_value"] = df["Duplicate_of"].apply(lambda x: "" if x == "" else df.loc[df["Labels"] == x, "Values"].values[0]) Explanation: This simply applies a lambda function to each element of the column "Duplicate_of" First we check if the item is an empty string and we return an empty string if so: "" if x == "" is equivalent to: if x == "" return "" If it is not an empty string the following command is executed: df.loc[df["Labels"] == x, "Values"].values[0] This simple return the value in the column "Values" when the condition df["Labels"] == x is true. If you are wondering about the .values[0] part, it is there because .loc returns a series; our series in this case is just a single value so we simply get it with .values[0].
accepted answer of: http://stackoverflow.com/q/49251163

http://stackoverflow.com/comment/85559811
score: 1
comment on: http://stackoverflow.com/a/49262664
has text: @GiacomoAlzetta Avoiding bare except is not sufficient, because of a couple of more complex variants of the same issue. The finally block may not be called immediately if the generator is part of a reference cycle (it will wait until the next collection, during which time the process might have exited), and prior to Python 3.4, it might not be collected at all, if it's in a reference cycle with another object with a finalizer.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/101810375
has text: It's worth noting that `urandom()` does not have the same "reasonable default" rule when the number of bytes requested is `None`. So your backwards compatible solution would need to manually set `nbytes` to some "reasonable default" (though I'm not sure how many people use this feature).
comment on: http://stackoverflow.com/a/51207656
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49239075
answer count: 1
has answer: http://stackoverflow.com/a/49239362
accepted answer: http://stackoverflow.com/a/49239362
favorite count: 0
type: Question
has title: Plot multiple labels on the same axis
tagged with: matplotlib
tagged with: python
score: 4
upvote count: 4
linked to: http://stackoverflow.com/q/11481644
has comment: http://stackoverflow.com/comment/85481673
has comment: http://stackoverflow.com/comment/85482961
has body: Consider a simple plot with two distinct populations drawn: I want to add two separate y labels, one for the top population and one for the one below on the same left y axis. All the similar questions I've seen deal with labels on two separate axis (ie: one on the left, one on the right) which is not what I need. How can I do this? import numpy as np import matplotlib.pyplot as plt N = 50 a = np.random.uniform(100., 120., N) b = np.random.uniform(10., 20., N) plt.scatter(range(N), a) plt.scatter(range(N), b) plt.show() This question is not about adding labels to a legend as described here.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85481806
downvote count: 0

http://stackoverflow.com/comment/85486217
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49241160
has text: There's no guarantee the object even *exists*. It might have been reclaimed long ago.

http://stackoverflow.com/comment/85370200
comment on: http://stackoverflow.com/q/49182123
type: Comment
has text: I tried `print(randomSet(4, 10))` and I'm getting `[9, 6, 7, 2]` just fine. And `print(type(randomSet(4,10))` gives `<class 'list'>` as expected. How are you calling `randomSet`? Please provide a [mcve].
score: 4
type: QuestionComment

http://stackoverflow.com/comment/85357863
type: Comment
type: QuestionComment
has text: I'm not sure why you are creating a new array and appending to that for a binary search. Here's a neat solution - https://stackoverflow.com/a/46080558/6089653
comment on: http://stackoverflow.com/q/49175575
score: 0

http://stackoverflow.com/q/49243732
has body: I am trying to create GIFs using imageio. This is fairly straightforward; however, the quality of the images is poor. They appear to be interpolated. See the figures below. I am creating the GIF using the code shown below. I've tried tracing the the how the image is produced inside the source code and the issue seems to be coming from PIL. from PIL import Image import imageio import numpy as np import matplotlib.pyplot as plt outdir = r"where/you/want/it/to/go.gif" frames = np.round(100+20*np.random.randn(10, 40, 40)).astype(np.uint8) # Create single gif frame with PIL im = Image.fromarray(frames[0]) im.save(outdir) # Create gif with imageio imageio.mimsave(outdir, frames) I want a GIF that looks like the image on top (no interpolation) which I produced with matplotlib. The image on the bottom is a single frame produced using imageio.
score: 3
tagged with: python-imageio
tagged with: python-imaging-library
upvote count: 3
tagged with: python
favorite count: 0
type: Question
has title: Removing spatial interpolation or compression in GIFs created with imageio or PIL
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/71059851
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85496750
type: AnswerComment
comment on: http://stackoverflow.com/a/49246452
type: Comment
has text: Hey thanks for the reply! I tested this out however it gives the same result as my previous code. So when the next 'playerPoints' list comes through it adds the result on rather then updating it to the new result. For example, if the next 'playerPoints' list that comes through has values of 10, then the 'totalRank' or 'new_data' list values of 5 are 15 rather than 10
score: 0

http://stackoverflow.com/comment/85369897
has text: yes, I just use `spark-submit spark_gbt.py` (where `spark_gbt.py` is the name of the script above) from the command line ssh'd into the master node. Are you wondering about any specific settings on the cluster? I didn't set those up myself, but I could certainly track them down if you think that's relevant. I will say that other pyspark jobs I run on the same cluster use all the nodes.
type: Comment
comment on: http://stackoverflow.com/q/49181179
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85326908
comment on: http://stackoverflow.com/a/49160507
type: Comment
has text: Tried and still get the same error: Wrong number of items passed 30, placement implies 1
score: 0
type: AnswerComment

unit-testing
tags question: http://stackoverflow.com/q/49194557
tags question: http://stackoverflow.com/q/49196248
tags question: http://stackoverflow.com/q/49121630
tags question: http://stackoverflow.com/q/49209712
tags question: http://stackoverflow.com/q/49134178
tags question: http://stackoverflow.com/q/49196565
tags question: http://stackoverflow.com/q/49224204
tags question: http://stackoverflow.com/q/49174457
tags question: http://stackoverflow.com/q/49250200
type: Tag
tags question: http://stackoverflow.com/q/49265430
tag name: unit-testing
tags question: http://stackoverflow.com/q/49173269
tags question: http://stackoverflow.com/q/49146704
tags question: http://stackoverflow.com/q/49126766
tags question: http://stackoverflow.com/q/49149491
tags question: http://stackoverflow.com/q/49177228
tags question: http://stackoverflow.com/q/49168943
tags question: http://stackoverflow.com/q/49184586
tags question: http://stackoverflow.com/q/49128015
tags question: http://stackoverflow.com/q/49222759
tags question: http://stackoverflow.com/q/49148452

http://stackoverflow.com/comment/85449025
type: AnswerComment
comment on: http://stackoverflow.com/a/49222635
has text: Oh! my bad. I use call() wrong. All characters separated by a space needs to be its own list entity, I'll update my answer
type: Comment
score: 0

http://stackoverflow.com/comment/85919035
comment on: http://stackoverflow.com/q/49240236
has text: @AndrewCassidy we've seen about 4-5 minutes on ours and I would love to speed them up. Can you report back on what speeds you were able to achieve?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85315761
comment on: http://stackoverflow.com/q/49155418
has text: Possible duplicate of [Python - Classes and OOP Basics](https://stackoverflow.com/questions/10004850/python-classes-and-oop-basics)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49251629
has title: Converting Readability formula into python function
type: Question
tagged with: flesch-kincaid
tagged with: nltk
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/91769450
answer count: 1
tagged with: python
linked to: http://stackoverflow.com/q/49270817
has body: I was given this formula called FRES (Flesch reading-ease test) that is used to measure the readability of a document: My task is to write a python function that returns the FRES of a text. Hence I need to convert this formula into a python function. I have re-implemented my code from a answer I got to show what I have so far and the result it has given me: import nltk import collections nltk.download('punkt') nltk.download('gutenberg') nltk.download('brown') nltk.download('averaged_perceptron_tagger') nltk.download('universal_tagset') import re from itertools import chain from nltk.corpus import gutenberg VC = re.compile('[aeiou]+[^aeiou]+', re.I) def count_syllables(word): return len(VC.findall(word)) def compute_fres(text): """Return the FRES of a text. &gt;&gt;&gt; emma = nltk.corpus.gutenberg.raw('austen-emma.txt') &gt;&gt;&gt; compute_fres(emma) # doctest: +ELLIPSIS 99.40... """ for filename in gutenberg.fileids(): sents = gutenberg.sents(filename) words = gutenberg.words(filename) num_sents = len(sents) num_words = len(words) num_syllables = sum(count_syllables(w) for w in words) score = 206.835 - 1.015 * (num_words / num_sents) - 84.6 * (num_syllables / num_words) return(score) After running the code this is the result message I got: Failure Expected :99.40... Actual :92.84866041488623 File "C:/Users/PycharmProjects/a1/a1.py", line 60, in a1.compute_fres Failed example: compute_fres(emma) # doctest: +ELLIPSIS Expected: 99.40... Got: 92.84866041488623 My function is supposed to pass the doctest and result in 99.40... And I'm also not allowed to edit the syllables function since it came with the task: import re VC = re.compile('[aeiou]+[^aeiou]+', re.I) def count_syllables(word): return len(VC.findall(word)) This question has being very tricky but at least now it's giving me a result instead of an error message, not sure why it's giving me a different result though. Any help will be very appreciated. Thank you.
score: 0
has answer: http://stackoverflow.com/a/49259380
tagged with: tokenize
tagged with: regex

http://stackoverflow.com/comment/85498116
has text: What _is_ the starting point if not the center? Just another point? If so, why isn't it in the list? And why are you calling it `cx` and `cy` if it's not the center?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49247106

http://stackoverflow.com/q/49203706
upvote count: 10
type: UnansweredQuestion
has body: I have a script that I need to run indefinitely. The script is set to e-mail me confirmations of certain steps being completed on a daily basis. I am trying to use smtplib for this. The initial connection is set up so that I will enter my login (written into the script) and a password using getpass at the very initiation of the script. I do not want to leave my password written into the script or even reference by the script say in a config file. Therefore, I want to enter the password at initiation and leave the smtp connection in place. Re-connecting to the smtp connection as required in the script would defeat the point of being able to step away from the script entirely and leave it running indefinitely. The example code that I am working with at the moment looks like this: import smtplib import getpass smtpObj = smtplib.SMTP('smtp.gmail.com',587) smtpObj.ehlo() smtpObj.starttls() smtpObj.login('myemail@gmail.com',password = getpass.getpass('Enter Password: ')) Then I enter the password and the output is: (235, b'2.7.0 Accepted') So this all works fine. The problem is then that the script needs to pause for anywhere from a few minutes to potentially a few days depending on the time. This is achieved using a while loop with time conditions until a certain time when the send function will be called: smtpObj.sendmail('myemail@gmail.com','recipient@gmail.com','This is a test') However, after a period of about 20/30 mins it seems (i.e. if the pause is sufficient). Then the smptObj.sendmail call will fail due to a timeout error. The specific error is as follows: SMTPSenderRefused: (451, b'4.4.2 Timeout - closing connection. l22sm2469172wre.52 - gsmtp', 'myemail@gmail.com') I have so far tried the following: Instantiating the connection object with the following timeout parameterisation: smtpObj = smtplib.SMTP('smtp.gmail.com',587,timeout=None) smtpObj = smtplib.SMTP('smtp.gmail.com',587,timeout=86400) Neither of these seem to supress the 'timeout' of the connection (i…
answer count: 1
tagged with: email
downvote count: 0
linked to: http://stackoverflow.com/q/3978115
favorite count: 0
type: Question
tagged with: smtplib
has title: Is there a way to prevent SMTP Connection Timeout? smtplib, python
has answer: http://stackoverflow.com/a/49203976
score: 10
tagged with: timeout
tagged with: python

http://stackoverflow.com/comment/85499987
comment on: http://stackoverflow.com/q/49248036
type: QuestionComment
has text: Does this have to work with threads, or can it work only with processes? Because the latter is a whole lot easier.
score: 0
type: Comment

http://stackoverflow.com/q/49156877
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49156914
accepted answer: http://stackoverflow.com/a/49156914
downvote count: 0
answer count: 1
tagged with: python
has title: Using .loc or .iloc instead of .ix
type: AnsweredQuestion
tagged with: pandas
linked to: http://stackoverflow.com/q/31593201
score: 1
upvote count: 1
has body: I am using python 3.6. I have a pandas.core.frame.DataFrame and would like to filter the entire DataFrame based on if the column called "Closed Date" is not null. In other words, if it is null in the "Closed Date" column, then remove the whole row from the DataFrame. My code right now is the following: data = raw_data.ix[raw_data['Closed Date'].notnull()] Though it gets the job done, I get an warming message saying the following: C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:1: DeprecationWarning: .ix is deprecated. Please use .loc for label based indexing or .iloc for positional indexing I tried this code: data1 = raw_data.loc[raw_data.notnull(), 'Closed Date'] But get this error: ValueError: Cannot index with multidimensional key How do I fix this? Any suggestions?

http://stackoverflow.com/comment/131335558
comment on: http://stackoverflow.com/a/49191674
score: 0
type: Comment
type: AnswerComment
has text: This is really wrong: "In multiprocessing, processes are spawned by creating a Process object". A process is *not* a thread -- a thread is *not* a process. You're not starting a separate thread here, you're starting a process!

http://stackoverflow.com/q/49202647
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85410682
has comment: http://stackoverflow.com/comment/85410671
has answer: http://stackoverflow.com/a/49202851
downvote count: 4
answer count: 3
tagged with: for-loop
has comment: http://stackoverflow.com/comment/85410761
upvote count: 0
score: -4
has title: Indentation within a for loop
has answer: http://stackoverflow.com/a/49202741
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85410603
has comment: http://stackoverflow.com/comment/85413110
accepted answer: http://stackoverflow.com/a/49202740
has body: this question is based on this other one: Nested Loop Python One of the answer is for i in range(1, 10): for j in range(i): print(i, end='') print() I don't understand why after the print(i, end = ' ') statement Python then runs the print() statement. In other words, since print() is not in the nested loop, shouldn't this code be only run after the nested j loop is completed?
has answer: http://stackoverflow.com/a/49202740
has comment: http://stackoverflow.com/comment/85410674
possible better answer: http://stackoverflow.com/a/49202741
tagged with: python
linked to: http://stackoverflow.com/q/24591917

http://stackoverflow.com/q/49222748
has body: Is posible add icon mesh to textScrollList items in maya python ? def allMeshes(*args): listMesh = cmd.ls(type="mesh") geometry = cmd.listRelatives(listMesh, p=True ) if len(geometry) &gt; 0: for g in geometry: cmd.textScrollList('lstMesh', e=True, a=g) #here add icon else: return Thank you
tagged with: python
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: maya
accepted answer: http://stackoverflow.com/a/49227369
has answer: http://stackoverflow.com/a/49227369
type: Question
has title: How add icon to textScrollList
has comment: http://stackoverflow.com/comment/85458053

ete3
tag name: ete3
tags question: http://stackoverflow.com/q/49193417
type: Tag

http://stackoverflow.com/comment/85549888
type: AnswerComment
comment on: http://stackoverflow.com/a/49273588
type: Comment
has text: That would make it more explicit, but an empty queryset equals to False.
score: 0

http://stackoverflow.com/comment/85361399
has text: Actually, I tried with `soup.div.unwrap()`. And it's working.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49176873
score: 0

http://stackoverflow.com/q/49166560
has body: i have a dataframe as : id|amount|date 20|-7|2017:12:25 20|-170|2017:12:26 20|7|2017:12:27 i want to subtract each row from another for 'amount' column: the output should be like: id|amount|date|amount_diff 20|-7|2017:12:25|0 20|-170|2017:12:26|-177 20|7|2017:12:27|-163 i used the code: df.sort_values(by='date',inplace=True) df['amount_diff'] = df['invoice_amount'].diff() and obtained the output as: id|amount|date|amount_diff 20|-7|2017:12:25|163 20|-170|2017:12:26|-218 20|48|2017:12:27|0
has title: difference between two rows pandas
has comment: http://stackoverflow.com/comment/85338502
tagged with: python
has comment: http://stackoverflow.com/comment/85338942
tagged with: subtraction
type: Question
has comment: http://stackoverflow.com/comment/85338927
tagged with: difference
tagged with: pandas
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/49166710
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49166710

http://stackoverflow.com/q/49242768
tagged with: python
tagged with: python-requests
tagged with: http-status-code-404
has title: Getting status code 404 even though page exists
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49244215
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/85491943
has comment: http://stackoverflow.com/comment/85489438
favorite count: 0
tagged with: beautifulsoup
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49244215
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85489239
has body: I have tried web scraping this particular link with java and python, but i keep getting a 404 status code even though it exists. import requests from bs4 import BeautifulSoup from lxml import html from collections import defaultdict url = 'https://www.slacker.com/station/pop-remix' def main(): page = requests.get(url) print(page.status_code) print() if __name__ == "__main__": main()

http://stackoverflow.com/comment/85287228
score: 0
comment on: http://stackoverflow.com/q/49140878
has text: Protip 2: use if / else / elif
type: Comment
type: QuestionComment

beautifulsoup
tags question: http://stackoverflow.com/q/49240687
tags question: http://stackoverflow.com/q/49152367
tags question: http://stackoverflow.com/q/49213004
tags question: http://stackoverflow.com/q/49226161
tags question: http://stackoverflow.com/q/49245828
tags question: http://stackoverflow.com/q/49170202
tags question: http://stackoverflow.com/q/49137554
type: Tag
tags question: http://stackoverflow.com/q/49242539
tags question: http://stackoverflow.com/q/49216971
tags question: http://stackoverflow.com/q/49124037
tags question: http://stackoverflow.com/q/49222421
tags question: http://stackoverflow.com/q/49272349
tags question: http://stackoverflow.com/q/49223186
tags question: http://stackoverflow.com/q/49174794
tags question: http://stackoverflow.com/q/49176400
tags question: http://stackoverflow.com/q/49194486
tags question: http://stackoverflow.com/q/49126651
tags question: http://stackoverflow.com/q/49204518
tags question: http://stackoverflow.com/q/49172675
tags question: http://stackoverflow.com/q/49203426
tags question: http://stackoverflow.com/q/49165318
tags question: http://stackoverflow.com/q/49205608
tags question: http://stackoverflow.com/q/49237973
tags question: http://stackoverflow.com/q/49203787
tags question: http://stackoverflow.com/q/49191954
tags question: http://stackoverflow.com/q/49148370
tags question: http://stackoverflow.com/q/49168556
tags question: http://stackoverflow.com/q/49228402
tags question: http://stackoverflow.com/q/49214508
tags question: http://stackoverflow.com/q/49221270
tags question: http://stackoverflow.com/q/49267695
tags question: http://stackoverflow.com/q/49248633
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/49260014
tags question: http://stackoverflow.com/q/49143579
tags question: http://stackoverflow.com/q/49176873
tags question: http://stackoverflow.com/q/49242768
tags question: http://stackoverflow.com/q/49240103
tags question: http://stackoverflow.com/q/49209123
tags question: http://stackoverflow.com/q/49142525
tags question: http://stackoverflow.com/q/49196881
tags question: http://stackoverflow.com/q/49271250
tags question: http://stackoverflow.com/q/49143376
tags question: http://stackoverflow.com/q/49130258
tags question: http://stackoverflow.com/q/49184654
tags question: http://stackoverflow.com/q/49220179
tags question: http://stackoverflow.com/q/49229096
tags question: http://stackoverflow.com/q/49142374
tags question: http://stackoverflow.com/q/49269034
tags question: http://stackoverflow.com/q/49264796
tags question: http://stackoverflow.com/q/49145561
tags question: http://stackoverflow.com/q/49248799
tags question: http://stackoverflow.com/q/49184647
tags question: http://stackoverflow.com/q/49249620
tags question: http://stackoverflow.com/q/49157875
tags question: http://stackoverflow.com/q/49259073
tags question: http://stackoverflow.com/q/49204378
tags question: http://stackoverflow.com/q/49205643
tags question: http://stackoverflow.com/q/49210063
tags question: http://stackoverflow.com/q/49152901
tags question: http://stackoverflow.com/q/49268469
tags question: http://stackoverflow.com/q/49215787
tags question: http://stackoverflow.com/q/49136512
tags question: http://stackoverflow.com/q/49176961
tags question: http://stackoverflow.com/q/49251344
tags question: http://stackoverflow.com/q/49226935
tags question: http://stackoverflow.com/q/49148003
tags question: http://stackoverflow.com/q/49211426
tags question: http://stackoverflow.com/q/49238660
tags question: http://stackoverflow.com/q/49278686
tags question: http://stackoverflow.com/q/49126348
tags question: http://stackoverflow.com/q/49175943
tags question: http://stackoverflow.com/q/49170271
tags question: http://stackoverflow.com/q/49207782
tags question: http://stackoverflow.com/q/49268359
tags question: http://stackoverflow.com/q/49212342
tags question: http://stackoverflow.com/q/49193793
tags question: http://stackoverflow.com/q/49128385
tags question: http://stackoverflow.com/q/49216518

http://stackoverflow.com/q/49257972
type: Question
has body: I'm going to setup a Health-Check towards a Public-IP. I do not want to use Route53-HealthCheck because it pings every 2-3 seconds. I'm gonna send ping every 5-10 minutes to that IP.So I've decided to use AWS Lambda function. However I read here that Ping is not open on Lambda: https://forums.aws.amazon.com/thread.jspa?threadID=263968 Is there any AWS services that I can use it for this case? Any help would be appreciated.
has title: Send Ping towards a Public-IP for HealthCheck using AWS Lambda Function
type: UnansweredQuestion
tagged with: python
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/85835111
answer count: 0
has comment: http://stackoverflow.com/comment/85519481
score: 0
has comment: http://stackoverflow.com/comment/85524379
tagged with: aws-lambda

http://stackoverflow.com/a/49225247
type: Answer
answers question: http://stackoverflow.com/q/49224826
has comment: http://stackoverflow.com/comment/85454386
score: 0
has comment: http://stackoverflow.com/comment/85463781
has body: Greatly simplified by hpaulj's suggestion. Program: import numpy as np def change_sign(arr): """Switch sign of every second element of arr in-place Note ---- Modifies the input array (arr). """ # arr.reshape(-1) makes a 1D view of arr # # [1::2] select every other element of arr, # starting from the 1st element. # # *= -1 changes sign of selected elements. arr.reshape(-1)[1::2] *= -1 return arr def main(): N = 3 arr = np.arange(N ** 3).reshape(N, N, N) print("original array:") print(arr) print("change signs") print(change_sign(arr)) main() Result: original array: [[[ 0 1 2] [ 3 4 5] [ 6 7 8]] [[ 9 10 11] [12 13 14] [15 16 17]] [[18 19 20] [21 22 23] [24 25 26]]] change signs [[[ 0 -1 2] [ -3 4 -5] [ 6 -7 8]] [[ -9 10 -11] [ 12 -13 14] [-15 16 -17]] [[ 18 -19 20] [-21 22 -23] [ 24 -25 26]]]
has comment: http://stackoverflow.com/comment/85454407

http://stackoverflow.com/comment/85314879
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49155034
score: 0
has text: Just got done with getting what works! Now I can work on explanation (-:

http://stackoverflow.com/q/49194737
duplicate of: http://stackoverflow.com/q/47393001
has comment: http://stackoverflow.com/comment/125806472
tagged with: python
tagged with: hadoop
answer count: 0
tagged with: pandas
upvote count: 3
has comment: http://stackoverflow.com/comment/85396839
downvote count: 0
has comment: http://stackoverflow.com/comment/98283816
tagged with: hdfs
has body: I want to write a Pandas dataframe in HDFS, just like that import numpy as np import pandas as pd data = pd.DataFrame(np.arange(4).reshape(2,2),columns=['a','b']) data.to_csv('/localpath/test.csv') """ the outputfile will be : a b 0 0 1 1 2 3 """ to_csv() will write to a local path, but how can I write the panda dataframe to hdfs and the file in hdfs the same as the file output in localpath? Thanks!
linked to: http://stackoverflow.com/q/47393001
favorite count: 0
type: Question
score: 3
has title: how to write a Pandas dataframe in HDFS
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85403152

http://stackoverflow.com/comment/85441393
has text: Could everyone just stop calling backslashes forward slashes, please!
comment on: http://stackoverflow.com/q/49218782
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/49222876
type: Answer
score: 0
has body: the issue is with math.sqrt function . it does not accept negative numbers. return math.sqrt(((self._x - m_object.X) ** 2) + ((self._y - m_object.Y) ** 2)) is the correct way.
answers question: http://stackoverflow.com/q/49222472

http://stackoverflow.com/q/49180302
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49180722
has comment: http://stackoverflow.com/comment/85367336
has comment: http://stackoverflow.com/comment/85366191
accepted answer: http://stackoverflow.com/a/49180722
downvote count: 0
has answer: http://stackoverflow.com/a/59658859
has comment: http://stackoverflow.com/comment/85366280
favorite count: 0
type: Question
has title: check if 2 given number are close to each other python
has answer: http://stackoverflow.com/a/72804505
has body: i have been asked to make code that doesen't have loops and check if first number is close to second number (close means bigger or smaller by one).I tried using huge conditions but i wodered maybe there is an easyer way then do things like this: if num1 == num2 or num1 == num2 - 1 or num1 == num2 + 1
has comment: http://stackoverflow.com/comment/85366266
possible better answer: http://stackoverflow.com/a/68763927
tagged with: python
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/68763927
answer count: 4

http://stackoverflow.com/a/51582104
has body: you can run zipline inside pycharm or any IDE by using the run_algorithm method. something like this: from datetime import datetime import pandas as pd from zipline import run_algorithm start = pd.Timestamp(datetime(2018, 1, 1, tzinfo=pytz.UTC)) end = pd.Timestamp(datetime(2018, 7, 25, tzinfo=pytz.UTC)) run_algorithm(start=start, end=end, initialize=initialize, capital_base=100000, handle_data=handle_data, before_trading_start=before_trading_start, data_frequency='daily') I am using these packages: pandas==0.18.1 pandas-datareader==0.6.0 zipline-live==1.1.0.5 numpy==1.15.0 matplotlib==2.2.2 and python27
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49217482
upvote count: 2
downvote count: 0

http://stackoverflow.com/comment/85459439
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49227868
has text: So the total amount of memory used for the quickSort function will depend on the number of function calls? Like, say, the function is called three times for the `smaller` list and twice for the `larger` list, are all these lists that are created (plus the initial, unsorted list) stored in memory until the sorting is done?

http://stackoverflow.com/q/49184457
type: UnansweredQuestion
has title: counting sort - negative integers
score: -1
has comment: http://stackoverflow.com/comment/85375056
downvote count: 2
has body: I'm trying to do a counting_sort on negative numbers, the following code only seems to work on positive integers. Any pointers on how I can fix it to work on negative numbers? def count_sort(l): output = [0] * len(l) low = min(l) if low &gt;= 0: low = 0 high = max(l) working = [0 for i in range(low, high+1)] for i in l: workng[i] += 1 for j in range(1, len(working)): working[j] += working[j-1] for k in reversed(ul): output[working[k] - 1] = k working[k] -= 1 return output
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49184603
answer count: 2
has answer: http://stackoverflow.com/a/49184609
has comment: http://stackoverflow.com/comment/85374897
tagged with: python

http://stackoverflow.com/comment/85504113
score: 0
type: Comment
type: AnswerComment
has text: The sc object is the SparkContext. If you are using PySpark integrated with some IDE, automatically it starts a new spark context and provides you a SparkContext object named sc, and a SparkSession named spark. If you are not using PySpark integrated, and maybe importing libraries by hand, the sc object I refer is the object that you create with SparkContext() or SparkContext.getOrCreate() or similar instructions.
comment on: http://stackoverflow.com/a/49233568

http://stackoverflow.com/q/49136603
type: Question
has body: Is there any existing functionality to show outdated packages that are contained within a target lib directory installed with the equivalent of pip install -r requirements.txt -t lib without the use of a virtualenv? Maybe some working form of pip list -o -t lib If no functionality or simple workaround exists, what would be the proper way of maintaining packages in an external target library?
has title: pip list -o with target library without virtualenv
type: UnansweredQuestion
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/85280920
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/85278357
has comment: http://stackoverflow.com/comment/85281159
answer count: 0
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85284277
has comment: http://stackoverflow.com/comment/85280737
favorite count: 0

http://stackoverflow.com/q/49186326
has comment: http://stackoverflow.com/comment/85378598
favorite count: 0
type: Question
tagged with: python-3.x
has title: Pandas does not show the desired result on the y-axis with timedelta
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85378689
tagged with: timedelta
has answer: http://stackoverflow.com/a/49186562
has body: I would like to plot a timedelta with pandas 0.22.0 . Unfortunately, the y-axis only goes up to just over 3. Why is that? import pandas as pd df = pd.DataFrame({'date': ['2017-07-01', '2017-07-02', '2017-07-03', '2017-07-04', '2017-07-05'], 'minutes': [195, 69, 76, 25, 540]}) df.index = pd.to_datetime(df['date']) series = pd.Series(data=pd.to_timedelta(df['minutes'], 'm')) With series.describe it shows me everything correctly: series.describe() Out[6]: count 5 mean 0 days 03:01:00 std 0 days 03:30:20.768597 min 0 days 00:25:00 25% 0 days 01:09:00 50% 0 days 01:16:00 75% 0 days 03:15:00 max 0 days 09:00:00 Name: minutes, dtype: object Picture of the plot:
tagged with: plot
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85378431
has comment: http://stackoverflow.com/comment/85378845
tagged with: python

http://stackoverflow.com/comment/85551019
comment on: http://stackoverflow.com/q/49274177
type: QuestionComment
has text: ndmeiri: Ok, I guess I'll finish my custom class then
score: 0
type: Comment

http://stackoverflow.com/q/49143581
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49145891
tagged with: flask-restplus
type: AnsweredQuestion
has title: remove whitespace from JSON response by flask-restplus
score: 0
has answer: http://stackoverflow.com/a/49145891
linked to: http://stackoverflow.com/q/25773493
tagged with: flask
answer count: 1
has body: How can you get rid of whitespace in the JSON response by flask-restplus routes? In a similar question, but for flask-restful instead of flask-restplus, the answer suggested setting the config option JSONIFY_PRETTYPRINT_REGULAR = False. This does not seem to work for flask-restplus. I can't find anything in the documentation for flask-restplus around this either. What's the right way to do this? Anything better than overwriting the response handler?

http://stackoverflow.com/comment/85332802
comment on: http://stackoverflow.com/q/49163099
type: Comment
type: QuestionComment
score: 0
has text: @jarmod When I switch it to 'w', the error is `Input <_io.TextIOWrapper name='/tmp/output2.csv' mode='w' encoding='UTF-8'> of type: <class '_io.TextIOWrapper'> is not supported`

http://stackoverflow.com/a/49200908
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85408255
accepted answer of: http://stackoverflow.com/q/49200873
has comment: http://stackoverflow.com/comment/85407298
has body: When working with columns of lists in pandas, you have already decided to forfeit performance. Here's as fast an approach as you'd probably get, using a list comprehension. pd.Series( [[k + j for k in i] for i, j in zip(series1, series2)] ) 0 [a1, b1, c1] 1 [d2, e2] dtype: object
answers question: http://stackoverflow.com/q/49200873
has comment: http://stackoverflow.com/comment/85408488
type: Answer
has comment: http://stackoverflow.com/comment/85407674
has comment: http://stackoverflow.com/comment/85407960
has comment: http://stackoverflow.com/comment/85407910
has comment: http://stackoverflow.com/comment/85407371
has comment: http://stackoverflow.com/comment/85407695

http://stackoverflow.com/a/49189024
type: Answer
score: 2
upvote count: 2
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49188977
has comment: http://stackoverflow.com/comment/85384259
has body: You are doing it wrong by doing a = F.max(df['p_efc_dtm']).over(ws) a is just a reference to max function call You should be doing a = df.select(F.max(df['p_efc_dtm']).over(ws)) Then a.show() should work. If you want to see number column as you mentioned in the comment below then you can select both as a = df.select(df['number'], F.max(df['p_efc_dtm']).over(ws).alias('dtm')) Or better if you want to see all the original columns then you can use withColumn as a = df.withColumn('dtm', F.max(df['p_efc_dtm']).over(ws))
answers question: http://stackoverflow.com/q/49188977

http://stackoverflow.com/q/49221270
score: 0
answer count: 1
tagged with: loops
tagged with: web-scraping
tagged with: beautifulsoup
type: Question
has answer: http://stackoverflow.com/a/49221313
accepted answer: http://stackoverflow.com/a/49221313
has title: I'm trying to loop through and scrape a text file of links with BS4. I get an error at about the fourth iteration of the loop
has body: I'm trying to loop through a list of links from a text file and write the info to a text file. I get the 'index out of range' error and I have no idea why. import requests from bs4 import BeautifulSoup def item(a): return a[::2] def details(a): return a[1::2] sFile = open('scraped_data.txt', 'w+') with open('C:/Users/Main/Desktop/Python Web Scraper/link_list.txt') as f: lines = f.read().splitlines() def scrape(l): r = requests.get(l) soup = BeautifulSoup(r.text, "lxml") itemlist = [] for items in soup.find_all('td'): itemlist.append(items.text.strip()) for i in range(0, 6): print(item(itemlist)[i] + ' ' + details(itemlist)[i]) for i in range(0, 52): scrape(lines[i]) sFile.close() This is the console result. Traceback (most recent call last): File "C:/Users/Cobus Uys/PycharmProjects/Scraper/Scraper.py", line 33, in &lt;module&gt; scrape(lines[i]) File "C:/Users/Cobus Uys/PycharmProjects/Scraper/Scraper.py", line 29, in scrape print(item(itemlist)[i] + ' ' + details(itemlist)[i]) IndexError: list index out of range Process finished with exit code 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/49237117
tagged with: tensorflow
favorite count: 0
has body: I'm trying to add channel because of below error ValueError: could not broadcast input array from shape (48,48) into shape (48,48,1) Code: img = cv2.imread(f,0) resized = cv2.resize(img, (48,48), interpolation = cv2.INTER_AREA) print(resized.shape) (48, 48) But I need a channel image like (48,48,1). How can I solve this?
answer count: 4
has title: Python add one more channel to image
type: Question
has answer: http://stackoverflow.com/a/55747328
downvote count: 0
has answer: http://stackoverflow.com/a/52917974
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85478556
tagged with: keras
tagged with: opencv
tagged with: python-2.7
has answer: http://stackoverflow.com/a/49238987
has answer: http://stackoverflow.com/a/49238753
upvote count: 7
score: 7

http://stackoverflow.com/a/49155856
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49154589
has comment: http://stackoverflow.com/comment/85342164
accepted answer of: http://stackoverflow.com/q/49154589
type: Answer
has comment: http://stackoverflow.com/comment/85320646
has body: You probably want to use a groupby. The following will return the final table you wanted. Only including columns Year, Category and count_quantity_yearly_above_5. df.groupby(['Year', 'Category']).size().reset_index(name='count_quantity_yearly_above_5') Here is a simlar problem with more detailed answers
downvote count: 0

c++
tags question: http://stackoverflow.com/q/49168042
tags question: http://stackoverflow.com/q/49144199
tags question: http://stackoverflow.com/q/49142439
tags question: http://stackoverflow.com/q/49247628
tags question: http://stackoverflow.com/q/49175855
tags question: http://stackoverflow.com/q/49256414
tags question: http://stackoverflow.com/q/49181258
tags question: http://stackoverflow.com/q/49216605
tags question: http://stackoverflow.com/q/49246992
tags question: http://stackoverflow.com/q/49257947
tags question: http://stackoverflow.com/q/49257445
tags question: http://stackoverflow.com/q/49182978
tags question: http://stackoverflow.com/q/49226640
tags question: http://stackoverflow.com/q/49175216
tags question: http://stackoverflow.com/q/49178231
tags question: http://stackoverflow.com/q/49153671
tags question: http://stackoverflow.com/q/49142169
type: Tag
tags question: http://stackoverflow.com/q/49216412
tags question: http://stackoverflow.com/q/49270010
tag name: c++
tags question: http://stackoverflow.com/q/49209451
tags question: http://stackoverflow.com/q/49179356
tags question: http://stackoverflow.com/q/49266003

python-pika
tags question: http://stackoverflow.com/q/49154404
type: Tag
tag name: python-pika

http://stackoverflow.com/comment/85336461
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49163592
has text: Would you like to discuss this on chat?

http://stackoverflow.com/q/49217006
has body: I am a beginner and just working on a problem. I have to raise an exception if an object is passed with a string argument, but the output of this program is blank. Could anyone help? class RadiusInputError(Exception): pass class Circle: def __init__(self,radius): self.radius=radius if type(self.radius) == "&lt;class 'str'&gt;": raise RadiusInputError try: a = Circle('Hello') except RadiusInputError: print("'Hello' is not a number.")
type: Question
tagged with: python-3.x
tagged with: exception
possible better answer: http://stackoverflow.com/a/52576540
tagged with: python
has answer: http://stackoverflow.com/a/52576540
accepted answer: http://stackoverflow.com/a/49217030
has answer: http://stackoverflow.com/a/62400226
tagged with: class
has answer: http://stackoverflow.com/a/49217030
has title: Exception handling in __init__ method
type: AnsweredQuestion
answer count: 3
score: 1
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/49262475
answers question: http://stackoverflow.com/q/49260693
has comment: http://stackoverflow.com/comment/85591526
score: 0
type: Answer
has body: In [386]: alist = [[0,10,456], [1,10, 876], [0,100, 34], [5,100,22]] In [387]: arr = np.array(alist) In [388]: np.save('afile.npy',arr) In another terminal I can run the Python command 1032:~/mypy$ python3 -c "from numpy import load;print(load('afile.npy'))" [[ 0 10 456] [ 1 10 876] [ 0 100 34] [ 5 100 22]] and redirect the stdout to a file: 1034:~/mypy$ python3 -c "from numpy import load;print(load('afile.npy'))"&gt;afile.txt 1034:~/mypy$ cat afile.txt [[ 0 10 456] [ 1 10 876] [ 0 100 34] [ 5 100 22]] That's the same sort of text I get in the ipython session from arr: [391]: arr # repr display Out[391]: array([[ 0, 10, 456], [ 1, 10, 876], [ 0, 100, 34], [ 5, 100, 22]]) In [392]: print(arr) # str display [[ 0 10 456] [ 1 10 876] [ 0 100 34] [ 5 100 22]]

http://stackoverflow.com/q/49186752
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49186770
favorite count: 0
has comment: http://stackoverflow.com/comment/85378869
type: Question
has answer: http://stackoverflow.com/a/49186770
tagged with: typeerror
tagged with: pandas
upvote count: 5
tagged with: dataframe
tagged with: python
downvote count: 5
has title: TypeError: 'Series' object is not callable when accessing dtypes of a dataframe
has body: As it is [Duplicate], I have raised this to be removed. Kindly do not rollback.
type: AnsweredQuestion

http://stackoverflow.com/q/49147811
score: 1
upvote count: 1
answer count: 1
has body: I wonder whether there is a way to apply constraints on the batches to generate in Tensorflow. In particular, I would like to produce batches containing different labels. Suppose I have five possible labels, {A, B, C, D, E}, I would like batches like (A, C, E, D, B) or (B,E,D,C,A). Basically, I want to avoid batches with equal labels such as (A, A, D, E, C) or (A, B, B, B, E).
tagged with: keras
has answer: http://stackoverflow.com/a/49148433
tagged with: tensorflow
favorite count: 0
accepted answer: http://stackoverflow.com/a/49148433
type: Question
has title: Tensorflow: how to make sure all samples in each batch are with different labels?
tagged with: python
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/85299252
has text: @cᴏʟᴅsᴘᴇᴇᴅ The difference between the previous question and this one is that in the previous question I get the result as shown in the last dataframe (above) but as i mention in this question, I would like to have some columns repeating and not have missing values when the merge is performed. So i think its not a duplicate question but a further enhancement of the previous question. Can you help in solving this? Thanks!
comment on: http://stackoverflow.com/q/49147103
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85334571
type: QuestionComment
comment on: http://stackoverflow.com/q/49164363
has text: I ran out of characters before, but basically I'm trying to keep the specific columns and rows, but for output I wouldn't mind trying to remove the countrie and just have the numbers only. Also, sorry for explaining myself poorly!
type: Comment
score: 0

http://stackoverflow.com/comment/85265563
comment on: http://stackoverflow.com/a/49129997
type: Comment
has text: Thank @DeepSpace, I will try your way !
score: 0
type: AnswerComment

http://stackoverflow.com/comment/115442595
comment on: http://stackoverflow.com/a/49194271
type: Comment
type: AnswerComment
has text: Just a note: if you only expect the name to appear once (or just care about recording the first occurence) you can avoid iterating over the whole dictionary by adding `break` after `idx = ...`
score: 1

http://stackoverflow.com/comment/85325720
type: AnswerComment
type: Comment
has text: `resultX = diff[flag == 1]` should do it — put all three lines immediately after the `np.loadtxt()` line.
score: 0
comment on: http://stackoverflow.com/a/49158290

http://stackoverflow.com/q/49268734
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85540807
has title: "detail": "Method \"GET\" not allowed. on calling endpoint in django
tagged with: django
tagged with: python
tagged with: django-rest-framework
has answer: http://stackoverflow.com/a/49268800
has comment: http://stackoverflow.com/comment/85540785
downvote count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/85587957
has answer: http://stackoverflow.com/a/49268778
score: 7
upvote count: 7
linked to: http://stackoverflow.com/q/49181262
has answer: http://stackoverflow.com/a/66331669
has body: I'm using django.rest_framework. I have a get_or_create method for a particular view, class LocationView(views.APIView): def get_or_create(self, request): try: location = Location.objects.get(country=request.data.get("country"), city=request.data.get("city")) Response(location, status=status.HTTP_200_OK) except Location.DoesNotExist: serializer = LocationSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is the location Model, class Location(models.Model): country = models.CharField(max_length=255) city = models.CharField(max_length=255, unique=True) latitude = models.CharField(max_length=255) longitude = models.CharField(max_length=255) class Meta: unique_together = ('country', 'city') This is my url, url(r'^location/$', LocationView.as_view(), name='location'), When I call this endpoint in the following way, http://127.0.0.1:8000/api/v1/bouncer/location/?country=USA&amp;&amp;city=Sunnyvale&amp;&amp;latitude=122.0363&amp;&amp;longitude=37.3688 This is what I get, { "detail": "Method \"GET\" not allowed." } What am I missing here.
has comment: http://stackoverflow.com/comment/102507440
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/49274754
has body: Given that the loop count (the length of a and b) isn't a huge number as compared to the lengths along the other axes, we can run a simple loop and leverage BLAS supported matrix-multiplication at each iteration. The lengths also mean enough sum-reductions per iteration, justifying a for-loop for such a case. The implementation would be - N,M = b.shape[::2] out = np.empty((N,M)) for i in range(N): out[i] = c[i].dot(a[i]).dot(b[i]) out *= 2 Benchmarking Using the optimize argument, which seems to boost up the performance of my_func_2 appreciably and also adding in the proposed one as another function - def my_func(a,b,c, optimize=False): InnerSum = np.einsum('lpk, lkm -&gt; lpm', a, b,optimize=optimize) OuterSum = np.einsum('lp, lpm -&gt; lm', c, InnerSum, optimize=optimize) Result = 2 * OuterSum return Result def my_func_2(a,b,c, optimize=False): OuterSum = np.einsum('lpk, lkm, lp -&gt; lm', a, b, c,optimize=optimize) Result = 2 * OuterSum return Result def my_func_3(a,b,c): N,M = b.shape[::2] out = np.empty((N,M)) for i in range(N): out[i] = c[i].dot(a[i]).dot(b[i]) out *= 2 return out Timings - In [51]: # Setup used in the question ...: np.random.seed(0) ...: a = np.random.uniform(0,1,size=[14,25,25]) ...: b = np.random.uniform(0,1,size=[14,25,25]) ...: c = np.random.uniform(0,1,size=[14,25]) # With einsum optimize set as False In [52]: %timeit my_func(a,b,c, optimize=False) ...: %timeit my_func_2(a,b,c, optimize=False) ...: %timeit my_func_3(a,b,c) 1000 loops, best of 3: 255 µs per loop 1000 loops, best of 3: 302 µs per loop 10000 loops, best of 3: 28.7 µs per loop # With einsum optimize set as True In [53]: %timeit my_func(a,b,c, optimize=True) ...: %timeit my_func_2(a,b,c, optimize=True) ...: %timeit my_func_3(a,b,c) 1000 loops, best of 3: 334 µs per loop 10000 loops, best of 3: 77.6 µs per loop 10000 loops, best of 3: 28.6 µs per loop
has comment: http://stackoverflow.com/comment/85656610
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85656573
accepted answer of: http://stackoverflow.com/q/49274174
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85656670
downvote count: 0
has comment: http://stackoverflow.com/comment/85656775
has comment: http://stackoverflow.com/comment/85656546
answers question: http://stackoverflow.com/q/49274174

http://stackoverflow.com/a/49185647
answers question: http://stackoverflow.com/q/49185316
has body: If you're running python (cpython) on windows the &lt;built-in function system&gt; os.system will execute under the curtains _wsystem while if you're using a non-windows os, it'll use system. While subprocess.call will use CreateProcess on windows and _posixsubprocess.fork_exec in posix-based operating-systems. The above points should answer your questions about the main differences (structurally)... That said, I'd suggest you follow the most important advice from the os.system docs, which is: The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85377494
score: 3
accepted answer of: http://stackoverflow.com/q/49185316
upvote count: 3
type: Answer

http://stackoverflow.com/a/49159704
has comment: http://stackoverflow.com/comment/85324772
has comment: http://stackoverflow.com/comment/85324806
has comment: http://stackoverflow.com/comment/85325876
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49159638
score: 3
accepted answer of: http://stackoverflow.com/q/49159638
upvote count: 3
has comment: http://stackoverflow.com/comment/85324787
has body: While this is possible, it is not a good idea. Code with dynamically-generated variable names is difficult to read and maintain. That said, you could do it using the exec function, which executes code from a string. This would allow you to dynamically construct your variables names using string concatenation. However, you really should use a dictionary instead. This gives you an object with dynamically-named keys, which is much more suited to your purposes. For example: import pandas as pd Data = {} for i in range(2010,2017): Data[i] = pd.read_csv("Data_from_" +str(i) + ".csv") # Stores data from file "Data_from_YYYY.csv" as dataset DataYYYY. # Access data like this: Data[2011] You should also use snake_case for variable names in Python, so Data should be data. If you really wanted to dynamically generate variables, you could do it like this. (But you aren't going to, right?) import pandas as pd for i in range(2010,2017): exec("Data{} = pd.read_csv(\"Data_from_\" +str(i) + \".csv\")".format(i)) # Stores data from file "Data_from_YYYY.csv" as dataset DataYYYY. You can do this without exec too; have a look at Jooks' answer.
type: Answer
has comment: http://stackoverflow.com/comment/85324727

http://stackoverflow.com/q/49196759
tagged with: django
score: 1
upvote count: 1
tagged with: django-rest-framework
answer count: 1
favorite count: 0
type: Question
has title: django Lists are not currently supported in HTML input
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52299271
downvote count: 0
has body: Sorry for my english. I want create field, this field must contains list of files. my serializer: class FileSerializer(serializers.Serializer): file = serializers.FileField() class MySerializer(serializers.Serializer): list_files = FileSerializer(many=True, required=False) But in UI i have this text List files Lists are not currently supported in HTML input. How i can fix it?

http://stackoverflow.com/comment/85399132
score: 0
has text: I didn't know that decorators don't get inherited. Now this is starting to make sense.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49197081

http://stackoverflow.com/q/49201142
upvote count: 0
has comment: http://stackoverflow.com/comment/85407379
answer count: 1
has comment: http://stackoverflow.com/comment/85407457
tagged with: flask
downvote count: 1
favorite count: 0
type: Question
has title: Python flask controller says "url not found error"
has comment: http://stackoverflow.com/comment/85407468
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49203215
tagged with: python
score: -1
has body: from flask import Blueprint, request from flask import render_template from jinja2 import TemplateNotFound create_testcases_bp = Blueprint('create_testcases', __name__, template_folder='templates') create_testcases_bp.url_map.strict_slashes = False @create_testcases_bp.route('/create_testcases/') def create_testcases(): print "&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;&amp;" return render_template('/forms/create_testcase_view.html') I am getting 404 URL not found error. Any help? Is there anything I am missing? URL: http://localhost:8000/create_testcases/

http://stackoverflow.com/comment/85504776
comment on: http://stackoverflow.com/a/49250533
score: 0
type: AnswerComment
has text: Thank you so much!
type: Comment

http://stackoverflow.com/q/49185980
tagged with: set
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/49186402
type: UnansweredQuestion
has body: I have to change a list to a set and a powerset using recursion. My code works on the powerset, but I cannot get it to work on the set that we began with. Code: def printSet (A): if type(A) == int: return A elif len(A) == 1: return {} else: elementA = A.pop() return str(printSet(A))+ ',' + str(set(elementA)) print('{' + str(printSet(A)),end='}'); I can get the code to work for the second example below, but not for the first example below: &gt;&gt;&gt; printSet ([1,2,3,4]) {1, 2, 3, 4} &gt;&gt;&gt; printSet ([[1,2], [1,3]] {{1, 2}, {1, 3}} The input is: Params: A (list): set of integers, represented internally as a list The output is to print a set in standard set notation.
has title: Python: printing a set using recursion
tagged with: python
has comment: http://stackoverflow.com/comment/85377501
tagged with: recursion
score: 0
has comment: http://stackoverflow.com/comment/85377884

http://stackoverflow.com/a/49178680
upvote count: 1
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85397837
has body: If you really want to use a while loop i = 1 counter = 0 while counter &lt; a: if i % 2 == 1: print(i) counter += 1 i += 1
answers question: http://stackoverflow.com/q/49178102
downvote count: 0

http://stackoverflow.com/comment/85463944
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49145852
has text: Because in my opinion it is not possible. Or something missing?
score: 0

http://stackoverflow.com/comment/85817837
type: Comment
has text: So what is the difference between my solution and `QThread`s? You said you recommended them but without really explaining their advantages.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49175436

http://stackoverflow.com/comment/85453016
has text: looks like we ended up with the same solution :) Thanks
comment on: http://stackoverflow.com/a/49223444
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49185428
has comment: http://stackoverflow.com/comment/85452538
has comment: http://stackoverflow.com/comment/85435608
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85376547
tagged with: python
has comment: http://stackoverflow.com/comment/85376571
type: Question
has title: Bar chart labelling issue with Matplotlib and PyQt5
answer count: 0
has comment: http://stackoverflow.com/comment/85376925
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/85429607
downvote count: 0
tagged with: pyqt5
upvote count: 1
has comment: http://stackoverflow.com/comment/85434654
has comment: http://stackoverflow.com/comment/85376667
favorite count: 0
has comment: http://stackoverflow.com/comment/85377054
has comment: http://stackoverflow.com/comment/85376853
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85376692
has body: I have a bar chart embedded in a QWidget. When the window size of my GUI is maximum, the chart looks great (see picture 1) but when I reduce the size of the window, ticks labels almost disapear (see picture 2). How can I preserve my labels and how can I avoid labels overlaping on each others? Here my code: class Graph_init(FigureCanvas): def __init__(self, parent=None): self.fig = Figure() self.fig.patch.set_facecolor("None") self.axes = self.fig.add_subplot(111) self.fig.tight_layout() self.compute_initial_figure() FigureCanvas.__init__(self, self.fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) class Graph_populate(Graph_init): def compute_initial_figure(self): n=3 label = ['','Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'] x1 = [0.7,1.7,2.7,3.7,4.7,5.7,6.7,7.7,8.7,9.7,10.7,11.7] x2 = [1,2,3,4,5,6,7,8,9,10,11,12] x3 = [1.3,2.3,3.3,4.3,5.3,6.3,7.3,8.3,9.3,10.3,11.3,12.3] y1 = [15,25,35,45,55,65,75,85,95,105,115,125] y2 = [10,20,30,40,50,60,70,80,90,100,110,120] y3 = [20,30,40,50,60,70,80,90,100,110,120,130] self.axes.bar(x1,y1,width=0.80/n) self.axes.bar(x2,y2,width=0.80/n) self.axes.bar(x3,y3,width=0.80/n) self.axes.set_xticks(np.arange(13)) self.axes.set_xticklabels(label) self.axes.patch.set_facecolor('None') Thank you
has comment: http://stackoverflow.com/comment/85376499

http://stackoverflow.com/q/49215384
accepted answer: http://stackoverflow.com/a/49215465
type: Question
has comment: http://stackoverflow.com/comment/85434987
has title: User input in subprocess.call
tagged with: python
has comment: http://stackoverflow.com/comment/85435339
has comment: http://stackoverflow.com/comment/85435086
has answer: http://stackoverflow.com/a/49215465
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/3172470
score: 0
has body: I am writing a program to automate some qiime2 commands. I want to incorporate user input. So far, I have: # Items to import import subprocess from sys import argv #Variables format=argv[1] # Import sequences for Phred33 format if format=='Phred33': cmnd = 'qiime tools import --type SampleData[PairedEndSequencesWithQuality] --input-path manifest.csv --output-path paired-end-demux.qza --source-format PairedEndFastqManifestPhred33' print('executing {}'.format(cmnd)) res = subprocess.call(cmnd, shell=True) print('command terminated with status', res) # Import sequences for Phred64 format if format=='Phred64': cmnd = 'qiime tools import --type SampleData[PairedEndSequencesWithQuality] --input-path manifest.csv --output-path paired-end-demux.qza --source-format PairedEndFastqManifestPhred64' print('executing {}'.format(cmnd)) res = subprocess.call(cmnd, shell=True) print('command terminated with status', res) This works fine since there's only two possible user inputs, but I'd rather not have the if statements down the line when there will be countless possible user inputs. This would be better: cmnd = 'qiime tools import --type SampleData[PairedEndSequencesWithQuality] --input-path manifest.csv --output-path paired-end-demux.qza --source-format PairedEndFastqManifest', format But qiime2 gives me errors with this. Is there another way? Thank you!
linked to: http://stackoverflow.com/q/15109665
tagged with: subprocess
tagged with: qiime
answer count: 1
has comment: http://stackoverflow.com/comment/85435069
tagged with: user-input

http://stackoverflow.com/q/49223576
has title: Print multiple lines between two specific lines (keywords) from a text file
tagged with: text-files
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49223690
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49223653
answer count: 2
has answer: http://stackoverflow.com/a/49223690
downvote count: 0
tagged with: python
tagged with: lines
has body: I have a textfile and want to print the lines between two other lines, using Python 3.5 on Windows. I want to print the characters of a drama to another file. The textfile looks like this: ... Characters: Peter, the king. Anna, court lady. Michael, caretaker. Andre, soldier. Tina, baker. First scene. ... I want to print all the character names between the lines "Characters:" and "First scene." My first try was: newfile = open('newfile.txt', 'w') with open('drama.txt', 'r') as f: for line in f: if line.startswith('Characters:'): print(next(f), file = newfile) But this only prints one line and i need several lines and the iteration with the next() function led always to a StopIteration Error after printing one line. So is there a way to say: Print all lines between the lines "Characters:" and "First Scene."? It is not really possible to work with indices, because i'm doing it for several dramas and they have all a different number of characters.
type: AnsweredQuestion
score: 3
tagged with: printing
has answer: http://stackoverflow.com/a/49223653
upvote count: 3

http://stackoverflow.com/q/49255795
has title: NLTK Dependency issue on ADLA
score: 2
answer count: 2
has answer: http://stackoverflow.com/a/49584133
downvote count: 0
has comment: http://stackoverflow.com/comment/85521302
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49592137
upvote count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/22211525
tagged with: nltk
has body: I am trying to use nltk from azure data lake analytics using python. I have followed this link for Using Custom Python Libraries with U-SQL. I have zipped the source code of NLTK and have used it using the DeployResource. The source code is dependent on nltk_data folder, which is deployed on the vertex but its location is unknown. Following is the U-SQL code that i am executing. REFERENCE ASSEMBLY [ExtPy]; DEPLOY RESOURCE @"/FeedbackAnalysisService/Assemblies/nltk. DEPLOY RESOURCE @"/FeedbackAnalysisService/Assemblies/nltk_data.zip"; DECLARE @myScript = @" import sys sys.path.insert(0, 'nltk.zip') import nltk def usqlml_main(df): del df['number'] df['hello_world'] = nltk.word_tokenize('hello world') return df "; @rows = SELECT * FROM (VALUES (1)) AS D(number); @rows = REDUCE @rows ON number PRODUCE hello_world string USING new Extension.Python.Reducer(pyScript:@myScript); OUTPUT @rows TO "/demo_python_custom_module.csv" USING Outputters.Csv(outputHeader: true); I get the following error: Error|Running| File "nltk.zip\nltk\data.py", line 673, in find Error|Running| raise LookupError(resource_not_found) Error|Running| Searched in: Error|Running| - '/home//nltk_data' Error|Running| - 'C:\\nltk_data' Error|Running| - 'D:\\nltk_data' Error|Running| - 'E:\\nltk_data' Error|Running| - 'D:\\Data\\Temp\\f40f07f586ce4469ac593a701790ba00\\3.5.1\\nltk_data' Error|Running| - 'D:\\Data\\Temp\\f40f07f586ce4469ac593a701790ba00\\3.5.1\\lib\\nltk_data' Error|Running| - 'C:\\Windows\\system32\\config\\systemprofile\\AppData\\Roaming\\nltk_data' Error|Running| - '' Question: I have tried executing it locally and it runs without any error but when i run the script on cloud i get the error because it is unable to find nltk_data. How can i get the path where nltk_data is located on the vertex?
tagged with: azure-data-lake
tagged with: python

http://stackoverflow.com/q/49139953
score: 3
has title: Fill gaps in DataFrame MultiIndex level 1, differently for each level 0
tagged with: dataframe
tagged with: python
tagged with: multi-index
linked to: http://stackoverflow.com/q/17287933
type: Question
accepted answer: http://stackoverflow.com/a/49140028
has answer: http://stackoverflow.com/a/49140028
tagged with: pandas
upvote count: 3
answer count: 1
downvote count: 0
has body: I have a MultiIndex DataFrame with gappy date values on level 1, like this: np.random.seed(456) j = [(a, b) for a in ['A','B','C'] for b in random.sample(pd.date_range('2018-01-01', periods=100, freq='D').tolist(), 5)] j.sort() i = pd.MultiIndex.from_tuples(j, names=['Name','Date']) df = pd.DataFrame(np.random.random_integers(0,100,15), i, columns=['Vals']) # print(df): Vals Name Date A 2018-01-01 27 2018-01-08 43 2018-03-26 89 2018-03-29 42 2018-04-01 28 B 2018-01-02 79 2018-01-26 60 2018-02-18 45 2018-03-11 37 2018-03-23 92 C 2018-03-17 39 2018-03-20 81 2018-03-21 11 2018-03-27 77 2018-04-08 69 For each level 0 value, I want to fill in the index level 1 with every calendar date between the min and max date values for that level 0. (This Q&amp;A addresses the scenario of filling in level 1 with the same value set for all level 0 values.) E.g., for subset = df.loc['A'] I want to insert rows so that subset.index.values == pd.date_range(subset.index.values.min(), subset.index.values.max()).values. I.e., the resulting DataFrame would look like: Vals Name Date A 2018-01-01 27 2018-01-02 NaN 2018-01-03 NaN 2018-01-04 NaN 2018-01-05 NaN 2018-01-06 NaN 2018-01-07 NaN 2018-01-08 43 2018-01-09 NaN ... Is there a pandaic way to accomplish this? (The best I can come up with is to inefficiently and iteratively append new DataFrames for each level 0 value. Or similarly iteratively construct a list of index values and then pandas.concat them with the original DataFrame.)
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/85365084
score: 0
type: Comment
type: AnswerComment
has text: A short update on the brewer error. I had to remove a number of python files in /usr/local/bin/. Then could run `brew link python` which at least allowed me to get the correct Python version when using `python --version`.
comment on: http://stackoverflow.com/a/49173404

http://stackoverflow.com/q/49140718
downvote count: 1
favorite count: 0
type: Question
has body: As per the title, Apache 2.4 seems to be appending '/' to the URL (according to request.url) and Flask's routes don't match with or without it. (relevant) File structure /var/www/wsgi ... ├── dizmo │ └── __init__.py ├── foo.wsgi ├── hello1.wsgi └── __pycache__ └── adapter.cpython-35.pyc foo.wsgi import sys import inspect sys.path.append('/var/www/wsgi') from dizmo import app as application dizmo/__init__.py from flask import Flask, request import inspect import sys app = Flask(__name__) app.debug = True print( "app.config['SERVER_NAME']={}".format(app.config['SERVER_NAME']) ) print("{}:{} (outside)".format( inspect.currentframe().f_code.co_filename, inspect.currentframe().f_lineno ) ) @app.route('/foo') @app.route('/foo/') def tattletale(): return 'I\'m foo' @app.errorhandler(404) def err_handler_404(error): return '{}: no route'.format(request.url), 404 mysite.conf &lt;VirtualHost *:9000&gt; &lt;Directory /var/www/wsgi&gt; Require all granted DirectorySlash Off &lt;/Directory&gt; WSGIDaemonProcess CDRDB processes=2 threads=15 display-name=%{GROUP} python-path=/var/www/python-packages WSGIProcessGroup CDRDB WSGIScriptReloading On WSGIScriptAlias /foo /var/www/wsgi/foo.wsgi WSGIScriptAlias /hello1 /var/www/wsgi/hello1.wsgi &lt;/VirtualHost&gt; When it runs: curl http://127.0.0.1:9000/foo http://127.0.0.1:9000/foo/: no route Notice the trailing slash in request.url. I went through two dozen posts here and on Reddit regarding routes before I added the 404 handler, and now I'm at the end of my wits/rope. There's no 'foo' directory so DirectorySlash shouldn't even matter. Edit: strict_slashes=False doesn't seem to change anything, as well as using a single decorator, /foo or /foo/. Edit 2: Apparently, Apache or mod_wsgi plays tricks with the path, and /foo/foo somehow works. The Flask standalone server works as expected: curl http://127.0.0.1:9000/foo/foo # Apache I'm foo. route=http://127.0.0.1:9000/foo/foo curl http://127.0.0.1:5000/foo # flask run I'm foo. route=http:…
accepted answer: http://stackoverflow.com/a/49142499
has answer: http://stackoverflow.com/a/49148599
possible better answer: http://stackoverflow.com/a/49141169
has comment: http://stackoverflow.com/comment/85289474
tagged with: python
has comment: http://stackoverflow.com/comment/85289652
has comment: http://stackoverflow.com/comment/85286806
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85287664
tagged with: apache2.4
answer count: 3
has answer: http://stackoverflow.com/a/49142499
tagged with: mod-wsgi
upvote count: 2
has comment: http://stackoverflow.com/comment/85289609
score: 1
has answer: http://stackoverflow.com/a/49141169
linked to: http://stackoverflow.com/q/33241050
has comment: http://stackoverflow.com/comment/85290343
has title: Flask adds trailing slash to URL, no routes match
tagged with: flask

http://stackoverflow.com/comment/85295337
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49144990
has text: use winpython https://winpython.github.io/.

http://stackoverflow.com/q/49226447
tagged with: python
has comment: http://stackoverflow.com/comment/85665757
has title: Resnet network doesn't work as expected
type: UnansweredQuestion
tagged with: keras
score: 13
upvote count: 13
tagged with: conv-neural-network
tagged with: tensorboard
has comment: http://stackoverflow.com/comment/85662843
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49272905
type: Question
has body: Hi I was trying to train a cancer dataset, using the Resnet neural network by using the fine-tuning approach Here is how I used to fine-tune it. image_input = Input(shape=(224, 224, 3)) model = ResNet50(input_tensor=image_input, include_top=True,weights='imagenet') model.summary() last_layer = model.get_layer('avg_pool').output x= Flatten(name='flatten')(last_layer) out = Dense(num_classes, activation='softmax', name='output_layer')(x) custom_resnet_model = Model(inputs=image_input,outputs= out) custom_resnet_model.summary() for layer in custom_resnet_model.layers[:-1]: layer.trainable = False custom_resnet_model.layers[-1].trainable custom_resnet_model.compile(Adam(lr=0.001),loss='categorical_crossentropy',metrics=['accuracy']) custom_resnet_model.summary() tensorboard = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=False) hist = custom_resnet_model.fit(X_train, X_valid, batch_size=32, epochs=nb_epoch, verbose=1, validation_data=(Y_train, Y_valid),callbacks=[tensorboard]) (loss, accuracy) = custom_resnet_model.evaluate(Y_train,Y_valid,batch_size=batch_size,verbose=1) print("[INFO] loss={:.4f}, accuracy: {:.4f}%".format(loss,accuracy * 100)) df = pd.read_csv('C:/CT_SCAN_IMAGE_SET/resnet_50/dbs2017/data/stage1_sample_submission.csv') df2 = pd.read_csv('C:/CT_SCAN_IMAGE_SET/resnet_50/dbs2017/data/stage1_solution.csv') x = np.array([np.mean(np.load('E:/224x224/%s.npy' % str(id)), axis=0) for id in df['id'].tolist()]) x = x.transpose(0,2,3,1) # Make predictions pred = model.predict(x, batch_size=batch_size, verbose=1) #predict(self, x, batch_size=None, verbose=0, steps=None) print (pred) I used a validation set to predict my final results. But even with 100 epochs, my predicted classes probabilities are very low. 5.41865666e-05 2.16298591e-04 2.77880055e-04 7.53038039e-05 6.03657216e-04 1.30494649e-04 4.92068466e-05 5.37877844e-04 1.61486780e-04 6.16881996e-04 9.92802554e-04 5.50923753e-04 3.62671199e-05 3.44127137e-03 7.17231014e-05 2.7…
answer count: 2
has answer: http://stackoverflow.com/a/49353530
tagged with: resnet

http://stackoverflow.com/comment/85379539
type: Comment
has text: Or, you could always [edit] this time.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49185727

http://stackoverflow.com/comment/85398945
comment on: http://stackoverflow.com/q/49196780
type: Comment
type: QuestionComment
score: 0
has text: Yes, I can use skiprows, but I would like to transforme the entire dataset and then filter it. So, Is a good solution to use chunksize? and with a "for" funtion iterate all dataset?

http://stackoverflow.com/a/49250626
has comment: http://stackoverflow.com/comment/85559519
has comment: http://stackoverflow.com/comment/85510775
has comment: http://stackoverflow.com/comment/85580983
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85514710
has comment: http://stackoverflow.com/comment/85510606
accepted answer of: http://stackoverflow.com/q/49237041
type: AcceptedAnswer
type: Answer
has body: The default naming scheme for collection relationships is: return referred_cls.__name__.lower() + "_collection" So given that you have a model class addresses, then your relationship should be User.addresses_collection If you wish to alter this behaviour, pass your own implementation as the name_for_collection_relationship= keyword argument to AutomapBase.prepare().
upvote count: 1
has comment: http://stackoverflow.com/comment/85517261
answers question: http://stackoverflow.com/q/49237041

http://stackoverflow.com/a/49160844
score: 0
answers question: http://stackoverflow.com/q/49160738
has body: You can always just check if the environment has a timestamp already and not create it in that case. It is using the already-existing attribute as a flag instead of making a new one: def transaction(write=False): def _transaction_deco(fn): @wraps(fn) def _wrapper(*args, **kwargs): if hasattr(env, 'timestamp'): ret = fn(*args, **kwargs) else: env.timestamp = arrow.utcnow() with TxnManager(write=write) as txn: ret = fn(*args, **kwargs) delattr(env, 'timestamp') return ret return _wrapper return _transaction_deco This will let you nest an arbitrary number of transacted calls, and only use the timestamp and context manager of the outermost one.
type: Answer

http://stackoverflow.com/q/49148280
tagged with: flask
has answer: http://stackoverflow.com/a/49149615
tagged with: uwsgi
favorite count: 0
has title: How do I update my web app features in the linux server? web app is build with Python, Flask, uwsgi and server nginx
has body: I am new to Python development. I am building a test Python app and already deployed into a web server and accessing it through public IP. Now I have updated the source(that is added some more models and templates), Now I want my public IP under port 80 should show updated code. How do I do this?
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85301552
type: Question
upvote count: 0
type: UnansweredQuestion
answer count: 1
downvote count: 1

http://stackoverflow.com/comment/85442656
type: Comment
comment on: http://stackoverflow.com/a/49219371
has text: see again. I edited my answer. First time I wrote answer according to your call examples where your argument 'words' were list, not string
type: AnswerComment
score: 0

http://stackoverflow.com/q/49151938
tagged with: aws-glue
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/118244124
tagged with: pyspark
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/85312303
has comment: http://stackoverflow.com/comment/85320108
linked to: http://stackoverflow.com/q/46329561
type: UnansweredQuestion
has body: I am working with AWS Glue and PySpark ETL scripts, and want to use auxiliary libraries such as google_cloud_bigquery as a part of my PySpark scripts. The documentation states this should be possible. This previous Stack Overflow discussion, especially one comment in one of the answers seems to provide additional proof. However, how to do it is unclear to me. So the goal is to turn the pip installed packages into one or more zip files, in order to be able to just host the packages on S3 and point to them like so: s3://bucket/prefix/lib_A.zip,s3://bucket_B/prefix/lib_X.zip How that should be done is not clearly stated anywhere I've looked. i.e. how do I pip install a package and then turn it into a zip file that I can upload to S3 so PySpark can use it with such an S3 URL? By using the command pip download I have been able to fetch the libs, but they are not .zip files by default but instead either .whl files or .tar.gz ..so not sure what to do to turn them into zip files that AWS Glue can digest. Maybe with .tar.gz I could just tar -xf them and then zip them back up, but how about whl files?
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/29495435
score: 6
has answer: http://stackoverflow.com/a/49175969
tagged with: amazon-web-services
favorite count: 0
type: Question
has title: How to turn pip / pypi installed python packages into zip files to be used in AWS Glue
linked to: http://stackoverflow.com/q/17486578

http://stackoverflow.com/q/49246713
has title: libpython2.7.so.1.0()(64bit) not found by yum
tagged with: centos
score: 0
tagged with: azure
has answer: http://stackoverflow.com/a/49247414
answer count: 1
has comment: http://stackoverflow.com/comment/85497973
type: Question
tagged with: yum
has body: So I'm trying to install Azure on CentOS with yum: link. But it keeps telling me it needs libpython2.7.so.1.0: [root@minnow02 Desktop]# yum install azure-cli Loaded plugins: fastestmirror, refresh-packagekit, security Setting up Install Process Loading mirror speeds from cached hostfile * base: mirror.sfo12.us.leaseweb.net * extras: mirror.sfo12.us.leaseweb.net * updates: mirror.sfo12.us.leaseweb.net Resolving Dependencies --&gt; Running transaction check ---&gt; Package azure-cli.x86_64 0:2.0.28-1.el7 will be installed --&gt; Processing Dependency: libpython2.7.so.1.0()(64bit) for package: azure-cli-2.0.28-1.el7.x86_64 --&gt; Finished Dependency Resolution Error: Package: azure-cli-2.0.28-1.el7.x86_64 (azure-cli) Requires: libpython2.7.so.1.0()(64bit) You could try using --skip-broken to work around the problem You could try running: rpm -Va --nofiles --nodigest But I have python 2.7: [root@minnow02 Desktop]# python -V Python 2.7.5 [root@minnow02 Desktop]# find / -iname "pyth.so*" /usr/lib/libpython2.7.so.1.0 /usr/lib/libpython2.7.so /usr/lib/libpython2.7.so.1.0()(64bit) /usr/local/python2.7/lib/libpython2.7.so.1.0 /usr/local/python2.7/lib/libpython2.7.so /usr/local/python2.7/lib/libpython2.7.so.1.0()(64bit) What's going on?
type: UnansweredQuestion
tagged with: python
tagged with: shared-libraries

http://stackoverflow.com/comment/85281065
type: QuestionComment
has text: I've never tried this, but you could "vendor" the shared packages by placing them in your `/lib` folder? However, if both services depend on shared models it sounds more like an architectural issue, as the services are not independent. Perhaps consider having the model in one service, and have that service provide an API for the other service to access the model data?
type: Comment
comment on: http://stackoverflow.com/q/49136417
score: 0

http://stackoverflow.com/comment/85474778
score: 0
type: Comment
has text: @Jean-FrançoisFabre Thankyou that fixed my problem and i understand now that it is removing the number from the list.
type: QuestionComment
comment on: http://stackoverflow.com/q/49235379

http://stackoverflow.com/comment/85320144
type: AnswerComment
score: 1
type: Comment
has text: This is wrong. The button will not be removed, because it has a parent. There is no need to create an attribute for it. The OPs code works fine with `w = customWidget()` instead of `w = QWidget()`.
comment on: http://stackoverflow.com/a/49155416

http://stackoverflow.com/comment/85416220
type: QuestionComment
score: 1
has text: @cricket_007: I thought the same thing, but it turns out `json.load` is literally a single line long and just reads the whole file into a string that's passed into `json.loads`. There are no optimizations at all for file objects.
comment on: http://stackoverflow.com/q/49204735
type: Comment

http://stackoverflow.com/q/49136417
has comment: http://stackoverflow.com/comment/85281065
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85312181
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/85324930
tagged with: python
score: 4
upvote count: 4
has title: Reuse datastore models across services without symlink
has answer: http://stackoverflow.com/a/49137161
tagged with: google-cloud-datastore
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85281381
type: Question
has body: If App Engine service A and service B both depend on a datastore model, is there an effective way to share that model between both services without either duplicating the model or symlinking the file the model class definition is declared in? Would like to hear anyone's experience with this. Maybe storing the shared dependencies in Cloud Storage and pulling the relevant files from there?

http://stackoverflow.com/comment/85292010
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49143206
has text: *Why* do you need to concatenate numbers and strings in a dictionary key?

http://stackoverflow.com/q/49206811
has answer: http://stackoverflow.com/a/49206874
has title: Python - Beginner Level - User input and while Loop combination
possible better answer: http://stackoverflow.com/a/49206874
has comment: http://stackoverflow.com/comment/85418732
accepted answer: http://stackoverflow.com/a/49206867
favorite count: 0
has answer: http://stackoverflow.com/a/49207122
type: Question
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85418733
tagged with: while-loop
has body: I have did a little research around "Google", "YouTube", "Facebook" and "Stack Overflow" and I haven't found what I was looking for. So, I need your guidance. :) I want program to ask user input "PASSWORD" and every time user inputs wrong password the program asks password again, and again, and again until user types the correct password. Let's say that the password is as simple as "abc123". So, I start the program and it asks to input: "PASSWORD: ". If user types "abc123" then program prints "GOOD PASSWORD". If user types anything what is not "abc123" then program prints "BAD PASSWORD". As simple as that.. for now. My best attempt: #SECTION1_ASKING passwordInput=input('PASSWORD: ') password='abc123' while password == passwordInput: print('GOOD PASSWORD') break else: print('BAD PASSWORD') passwordInput=input('PASSWORD: ') #SECTION2_RE-ASKING while False: while password == paswordInput: print('GOOD PASSWORD') else: print('BAD PASSWORD') passwordInput=input('PASSWORD: ') but I either make password asked once or twice or I stuck in Infinite while Loop.
has comment: http://stackoverflow.com/comment/85419051
tagged with: input
tagged with: python
has answer: http://stackoverflow.com/a/49206867
has comment: http://stackoverflow.com/comment/85418702
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/85418712
downvote count: 2

http://stackoverflow.com/q/49163239
downvote count: 2
answer count: 1
has title: Copy Entry widget text and paste into another Entry widget in the same window
has comment: http://stackoverflow.com/comment/85420568
favorite count: 0
type: Question
has body: How do I copy Entry widget text and paste into another Entry widget in the same window. i.e. Let's imagine you are completing a joint credit application but you and the co-applicant have the same mailing address. Instead of re-typing the same address over again, there should be a checkbutton on the application that when it's checked it will auto-populate the co-applicant's mailing address with the main applicant's address. How do I get this done in tkinter? (I'm a tkinter and python rookie) thanks in advance DP​
has comment: http://stackoverflow.com/comment/85334624
has comment: http://stackoverflow.com/comment/85420289
has answer: http://stackoverflow.com/a/49208070
score: -2
tagged with: python
has comment: http://stackoverflow.com/comment/85334597
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85332679
has comment: http://stackoverflow.com/comment/85332747
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/49263681
score: 0
tagged with: java
answer count: 1
accepted answer: http://stackoverflow.com/a/49263833
type: Question
has answer: http://stackoverflow.com/a/49263833
has comment: http://stackoverflow.com/comment/85531485
tagged with: android
tagged with: matplotlib
tagged with: python
has title: Integrating matplotlib (Python) with Android Studio
has body: I would like to know if it's possible to run some Python script containing matplotlib graphs (e.g 3D surfaces) on Android Studio. If no, what could be another way I can do that?
has comment: http://stackoverflow.com/comment/85531347
tagged with: android-studio
type: AnsweredQuestion

http://stackoverflow.com/comment/85275377
has text: (ab)using `x` like that (`for x in x`) is not recommended. There are many more letters to choose from. xD
type: Comment
score: 3
type: AnswerComment
comment on: http://stackoverflow.com/a/49135363

http://stackoverflow.com/q/49192418
tagged with: python
has body: from django.contrib import admin from django.urls import path from adoptions import views urlpatterns = [ path('admin/', admin.site.urls), path(r'^$', views.home name='home'), path(r'^adoptions/(\d+)/', views.pet_detail, name='pet_detail'), ] this is my code when I run python manage.py runserver... It returns a syntax error.. saying third line in urlpatterns "name" error which is (name='home') here..
has comment: http://stackoverflow.com/comment/85390313
has title: Django-url cmd server error
answer count: 0
score: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85390299
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85389867
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85389651
tagged with: django

http://stackoverflow.com/q/49275639
has comment: http://stackoverflow.com/comment/85553834
has title: How to provide credentials as user input runtime during python automation?
tagged with: python
possible better answer: http://stackoverflow.com/a/49275856
score: -3
tagged with: user-input
tagged with: selenium-webdriver
type: AnsweredQuestion
answer count: 2
downvote count: 4
has comment: http://stackoverflow.com/comment/85553681
accepted answer: http://stackoverflow.com/a/49276248
has body: How to automate the Facebook login without hard-coding my username and password?
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/49276248
has comment: http://stackoverflow.com/comment/85553759
favorite count: 0
has answer: http://stackoverflow.com/a/49275856
type: Question
tagged with: python-3.x

http://stackoverflow.com/a/49148313
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49148050
answers question: http://stackoverflow.com/q/49148050
type: AcceptedAnswer
type: Answer
has body: This is possible with .loc accessor and using reset_index to elevate index to column: res = df.loc[df['des'].isin(set(df1['des'])), 'des'].reset_index() # index des # 0 0 abc # 1 1 bcd # 2 2 nna # 3 4 man

http://stackoverflow.com/comment/97037319
score: 0
comment on: http://stackoverflow.com/q/49158140
type: Comment
type: QuestionComment
has text: Take a look here: https://stackoverflow.com/a/53783956/2230045

http://stackoverflow.com/q/49199646
type: UnansweredQuestion
has title: Raspbian Pi program to calculate vehicle Speed using hall effect sensor
tagged with: addition
tagged with: python
has body: I was facing a problem to break counter variable after every 1 second. This counter variable will keep tract of vehicle wheel revolution per seond which will help to calculate speed. Also how we can pass a parameter in a function callback inside GPIO.add_event_detect() method. My code for calculating vehicle speed is as follows : import time import datetime import RPi.GPIO as GPIO def sensorCallback(channel,cir=1.884): #Called if sensor output changes ts = datetime.datetime.now() s=ts.second count=0 if s%59==0: count=0 else: #Magnet count=count+1 speed = count*cir*3600/1000 print(speed) def main(): count=0 r=30 cir = (2*3.14*r)/100 s=0 last=0 speed=0 try: while True : time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setup(17 , GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(17, GPIO.BOTH, callback=sensorCallback(count), bouncetime=200)
tagged with: detect
answer count: 0
tagged with: gpio
downvote count: 0
tagged with: events
upvote count: 1
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/85367199
score: 0
type: Comment
has text: @jpp: true. Also – if we want to explore all possibilities –, if `x` has only one significant digit, just like those in the ranges, multiplying both sides by 10 should make it work.
type: QuestionComment
comment on: http://stackoverflow.com/q/49180523

http://stackoverflow.com/a/49170071
score: 0
has body: So what you're trying to do is a histogram? Here's a simple way to do it: input_list = ['a', 'a', 'b', 'b', 'b', 'c'] def histogram(my_list): result = {} for item in my_list: result[item] = result.get(item, 0) + 1 return result print(str(histogram(input_list))) The .get() method returns the value for the given key from the dictionary. If the key isn't there, it is inserted and given the value provided in the second argument.
type: Answer
answers question: http://stackoverflow.com/q/49169465

http://stackoverflow.com/q/49188432
tagged with: string
score: -6
has answer: http://stackoverflow.com/a/49188780
downvote count: 7
has comment: http://stackoverflow.com/comment/85382279
tagged with: sequence
favorite count: 0
type: Question
has title: Counting maximum k-mer repetition frequency
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/77954472
has body: If n is 3, then the sequence "ATATATATAG" contains 4x "ATA", 3x "TAT" and 1x "TAG". The proportion is thus 4/8=0.5. The higher this number, the more repetitive the sequence. Write a function simple(s,n) where s is a sequence and n is the length of the k-mer to consider. The function should return the proportion described above. Could someone help me with this, please?
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/49189234
has answer: http://stackoverflow.com/a/49188958
has comment: http://stackoverflow.com/comment/85382161
upvote count: 1

http://stackoverflow.com/a/49197435
type: Answer
answers question: http://stackoverflow.com/q/49197386
has comment: http://stackoverflow.com/comment/125770992
has body: df'weekday' returns a dataframe, which is incorrect. Convert the series column to categorical instead. Also, use the ordered=True argument to establish order in your categorical column. categories = np.array( ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes', 'Sabado', 'Domingo']) df['weekday'] = pd.Categorical( df['weekday'], categories=categories, ordered=True) df.sort_values(by='weekday') weekday venta_total_cy 1 Lunes 3.425554e+09 5 Martes 3.328418e+09 6 Miercoles 3.136277e+09 4 Jueves 2.748710e+09 0 Viernes 5.430211e+09 2 Sabado 6.833202e+09 3 Domingo 6.566466e+09
score: 5
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49197386
type: AcceptedAnswer
upvote count: 5

http://stackoverflow.com/q/49267999
has answer: http://stackoverflow.com/a/70670642
has answer: http://stackoverflow.com/a/56458598
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/59517285
has answer: http://stackoverflow.com/a/49268133
accepted answer: http://stackoverflow.com/a/49268133
has body: I'm trying to open a file in Python, but I got an error, and in the beginning of the string I got a /u202a character... Does anyone know how to remove it? def carregar_uml(arquivo, variaveis): cadastro_uml = {} id_uml = 0 for i in open(arquivo): linha = i.split(",") carregar_uml("‪H:\\7 - Script\\teste.csv", variaveis) OSError: [Errno 22] Invalid argument: '\u202aH:\7 - Script\teste.csv'
downvote count: 3
has answer: http://stackoverflow.com/a/58131698
has answer: http://stackoverflow.com/a/49281061
has comment: http://stackoverflow.com/comment/85540534
possible better answer: http://stackoverflow.com/a/49281061
favorite count: 0
type: Question
answer count: 8
has answer: http://stackoverflow.com/a/68568248
upvote count: 6
tagged with: python
linked to: http://stackoverflow.com/q/36974461
has comment: http://stackoverflow.com/comment/85539580
has answer: http://stackoverflow.com/a/58894235
has title: Remove u202a from Python string

http://stackoverflow.com/comment/85475119
type: Comment
type: AnswerComment
score: 0
has text: No worries, what you have here is great, it just took me a minute to connect the output times with which code was run.
comment on: http://stackoverflow.com/a/49235142

http://stackoverflow.com/comment/85470152
type: QuestionComment
has text: I defined the variable as static DetectionWindowArray win(100000); I suppose that now I can access the same piece of memory between calls ....
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49226640

http://stackoverflow.com/comment/85381865
score: 0
type: Comment
type: AnswerComment
has text: angry people :'(
comment on: http://stackoverflow.com/a/49188149

http://stackoverflow.com/comment/85380014
type: AnswerComment
comment on: http://stackoverflow.com/a/49186860
score: 0
type: Comment
has text: No problem - subclassing is a way to add additional functionality or modify existing functionality of a class. It can be very powerful and helps maintain the DRY (Don’t repeat yourself) method.

http://stackoverflow.com/comment/85311270
comment on: http://stackoverflow.com/q/49138692
score: 2
type: QuestionComment
type: Comment
has text: @quanty: I would say it depends on your intent. If it was specific for sklearn, then it is no duplicate. If you are interested in general Python, then Vivek Kumar is right, and it is a duplicate. If it is the first, then I think my answer is the more correct one though ;)

http://stackoverflow.com/a/49137761
type: Answer
answers question: http://stackoverflow.com/q/49137508
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49137508
type: AcceptedAnswer
has body: Your understanding here is correct. The second example works identically in terms of performance and what's happening "under the hood". Often, you'll see code structured like your second example when you're chaining together many filters and exclusions and don't want to repeat yourself. For simple queries, though, your first example is what you'd normally see stylistically.

http://stackoverflow.com/comment/85431013
has text: check out [this answer](https://stackoverflow.com/a/13940335/4225229)
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49213200

http://stackoverflow.com/comment/85444662
has text: @poke Thanks, so in this case when it will be working for `foo` then our key will be 55 and 43, since in single dict there is only 1 value.
comment on: http://stackoverflow.com/a/49220468
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49295550
has comment: http://stackoverflow.com/comment/85624792
type: AcceptedAnswer
has body: You can do something like this (note you have given no real code so this is barebones) X = [...] y = [...] def custom_scorer_function(y, y_pred, **kwargs): a_feature = X[:,1] # now have y, y_pred and the feature you want custom_scorer = make_scorer(custom_scorer_function, greater_is_better=True) ...
has comment: http://stackoverflow.com/comment/85599053
has comment: http://stackoverflow.com/comment/85597635
has comment: http://stackoverflow.com/comment/101376601
answers question: http://stackoverflow.com/q/49246856
type: Answer
has comment: http://stackoverflow.com/comment/85598461
accepted answer of: http://stackoverflow.com/q/49246856
has comment: http://stackoverflow.com/comment/85596916
score: 0
has comment: http://stackoverflow.com/comment/85639533

http://stackoverflow.com/q/49264788
downvote count: 0
has answer: http://stackoverflow.com/a/49265832
has title: Unhandled error in Deferred in twisted deferToThread
has body: I have client/server code example from twisted. Now, my requirement is that when a call is made to server from the client - the server defers the call to a thread, who actually replies back to the client and the server can do something else. In simple words, let's say client C1 makes a call to server S1 with a template Temp1. Server defers it to a thread T1. T1 now has to process function A, B, and C and finally get back to client C1. Below is my code for the server. I am new to twisted and I am getting the error: Unhandled error in Deferred: from twisted.internet import reactor, protocol, threads def foo(): time.sleep(5) print('Hello how are you!!!!') def print_result(): print('Processing done!!') def onError(): print('Error!!!!') class Echo(protocol.Protocol): """This is just about the simplest possible protocol""" def process_func(self, data): print('hello i am in process_func!!!') self.transport.write(data) return foo() def onErrorfunc(self): onError() def onProcessDone(self): print_result() def dataReceived(self, data): "As soon as any data is received, write it back." # thr = threading.Thread(target=foo, args=(), kwargs={}) # thr.start() d = threads.deferToThread(self.process_func, *data) d.addCallback(self.onProcessDone) d.addErrback(self.onErrorfunc) # do something else here # self.transport.write(data) def main(): """This runs the protocol on port 8000""" factory = protocol.ServerFactory() factory.protocol = Echo reactor.listenTCP(8000,factory) reactor.run() # this only runs if the module was *not* imported if __name__ == '__main__': main() Why twisted, because the client/server is written in twisted already and I am doing minor changes. Help is appreciated. Thanks!
favorite count: 0
linked to: http://stackoverflow.com/q/49491568
type: Question
accepted answer: http://stackoverflow.com/a/49265832
tagged with: python
tagged with: twisted.web
type: AnsweredQuestion
tagged with: twisted.internet
tagged with: twisted
score: 1
upvote count: 1
answer count: 1

http://stackoverflow.com/q/49248036
has comment: http://stackoverflow.com/comment/85527665
has comment: http://stackoverflow.com/comment/85501665
has comment: http://stackoverflow.com/comment/85536937
has comment: http://stackoverflow.com/comment/85500014
tagged with: return
has comment: http://stackoverflow.com/comment/85500349
has comment: http://stackoverflow.com/comment/85501950
tagged with: function
tagged with: multithreading
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85499987
upvote count: 1
has body: I need to be able to capture the return value of a function and its stdout/stderr in a threaded context. Currently, I'm evaluating a number of subclasses (my_class_foo, my_class_bar) based on this base class (my_base_class) by invoking the is_true method in each subclass. I'd like to be able to capture both the return value from each is_true as well as the stdout/stderr. The current solution below works in a non-threaded or non-multiprocess context. However, it relies on redirecting the stdout/stderr which obviously won't work if I'm evaluating more than one of these subclasses in parallel. I've looked at the concurrent.futures and multiprocess and subprocess packages and can't figure out a solution. I'm trying to avoid using loggers so that users can just rely on printing to stdout instead of using an explicit method. I would like to execute the is_true methods from my_class_foo and my_class_bar and in parallel and be able to capture the stdout messages with each class' return value. class my_class_foo(my_base_class): def is_true(self): print('foo') return True class my_class_bar(my_base_class): def is_true(self): print('bar') return False class my_base_class(object): def is_true(self): Raise NotImplementedError def evaluate_node_is_true(self): with Capturing() as is_true_stdout: node_is_true = self.is_true() self.output = ''.join(is_true_stdout) class Capturing(list): """ Context manager for capturing the stdout of the is_true() function call """ def __enter__(self): self._stdout = sys.stdout self._stderr = sys.stderr sys.stdout = self._stringio_out = io.StringIO() sys.stderr = self._stringio_err = io.StringIO() return self def __exit__(self, *args): self.extend(self._stringio_out.getvalue().splitlines()) self.extend(self._stringio_err.getvalue().splitlines()) del self._stringio_out del self._stringio_err sys.stdout = self._stdout sys.stderr = self._stderr
favorite count: 0
type: Question
has title: Capturing stdout/stderr and function return value in a threaded context
has comment: http://stackoverflow.com/comment/85528577
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/49248427
tagged with: stdout
linked to: http://stackoverflow.com/q/1501651
tagged with: python

http://stackoverflow.com/comment/85508522
type: AnswerComment
has text: Yes and it's executed. I've found an other way, basically just to specify -w to ping in order to make it last 5 seconds. But I'm still interested in knowing why it's not working with Popen
score: 0
comment on: http://stackoverflow.com/a/49251754
type: Comment

http://stackoverflow.com/q/49267010
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85545786
favorite count: 0
type: Question
tagged with: opencv
score: 3
has body: I follow the steps in the opencv tutorial: http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_video/py_lucas_kanade/py_lucas_kanade.html and it doesn't work for me here. can anyone help me figure out why i can't get output like that import numpy as np import cv2 cap = cv2.VideoCapture('Shorttest.mp4') # params for ShiTomasi corner detection feature_params = dict( maxCorners = 100, qualityLevel = 0.3, minDistance = 7, blockSize = 7 ) # Parameters for lucas kanade optical flow lk_params = dict( winSize = (15,15), maxLevel = 2, criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03)) # Create some random colors color = np.random.randint(0,255,(100,3)) # Take first frame and find corners in it ret, old_frame = cap.read() old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY) p0 = cv2.goodFeaturesToTrack(old_gray, mask = None, **feature_params) # Create a mask image for drawing purposes mask = np.zeros_like(old_frame) while(1): ret,frame = cap.read() frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # calculate optical flow p1, st, err = cv2.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params) # Select good points good_new = p1[st==1] good_old = p0[st==1] # draw the tracks for i,(new,old) in enumerate(zip(good_new,good_old)): a,b = new.ravel() c,d = old.ravel() mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2) frame = cv2.circle(frame,(a,b),5,color[i].tolist(),-1) img = cv2.add(frame,mask) cv2.imshow('frame',img) k = cv2.waitKey(30) &amp; 0xff if k == 27: break # Now update the previous frame and previous points old_gray = frame_gray.copy() p0 = good_new.reshape(-1,1,2) cv2.destroyAllWindows() cap.release()
tagged with: opticalflow
linked to: http://stackoverflow.com/q/35397740
tagged with: python
has title: Lucas-Kanade Optical Flow in OpenCV Doesn't work for me
has answer: http://stackoverflow.com/a/49402322
has comment: http://stackoverflow.com/comment/85806397
upvote count: 3
type: UnansweredQuestion

http://stackoverflow.com/q/49125925
has comment: http://stackoverflow.com/comment/85259067
tagged with: django-views
tagged with: django-models
tagged with: python
tagged with: django-forms
has comment: http://stackoverflow.com/comment/85256659
has body: I am trying to create a website with two dropdown menus: Department and Course Number. The data for the dropdown menus comes from the "courses" table of my SQL database. Right now my website initializes properly and shows the correct options in the dropdown menus. However, when the user selects an option within the dropdown menus and submits their choices, the website reloads as a blank slate so their selections are not being saved or processed. The error lies somewhere in the CourseForm form because I have another form (Working_Form) that is created in a different way but works perfectly. What is wrong with CourseForm/its associated models? models.py from django.db import models class Dept(models.Model): dept = models.CharField(max_length=255, db_column = 'dept') class Meta: managed = False db_table = 'courses' def __str__(self): return self.dept class Course_num(models.Model): course_num = models.CharField(max_length=255, db_column = 'course_number') class Meta: managed = False db_table = 'courses' def __str__(self): return self.course_num forms.py from django import forms from django_select2.forms import ModelSelect2Widget from .models import Dept, Course_num class CourseForm(forms.Form): dept = forms.ModelChoiceField( queryset=Dept.objects.distinct().\ order_by('dept').exclude(dept__isnull=True), required=False, empty_label="No preference", label=u"Department") course_num = forms.ModelChoiceField( queryset=Course_num.objects.distinct().\ order_by('course_num').exclude(course_num__isnull=True), required=False, empty_label="No preference", label=u"Course Number") views.py from django.shortcuts import render from django import forms from .models import Dept, Course_num from .forms import CourseForm ... class Working_Form(forms.Form): working_info = forms.ChoiceField(choices=WORKING_DATA_LIST, required=False) show_args = forms.BooleanField(label='Show args_to_ui', required=False) def home(request): context = {} res = None if request.method == 'POST': form_CourseForm…
has comment: http://stackoverflow.com/comment/85256712
has comment: http://stackoverflow.com/comment/85259232
has answer: http://stackoverflow.com/a/49126067
has comment: http://stackoverflow.com/comment/85259413
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85258652
tagged with: django
has title: Django form not saving inputs- refreshes upon submission
type: Question
score: 0

http://stackoverflow.com/q/49122527
upvote count: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49164502
score: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/85252878
has answer: http://stackoverflow.com/a/49164502
downvote count: 1
favorite count: 0
tagged with: lightgbm
type: Question
possible better answer: http://stackoverflow.com/a/59906404
has answer: http://stackoverflow.com/a/59906404
tagged with: python
has body: I'm trying LightGBMRegressor parameter tuning with Sklearn RandomizedSearchCV. I got an error with message below. error: LightGBMError: b'Check failed: num_data &gt; 0 at /src/LightGBM/src/io/dataset.cpp, line 27 .\n' I cannot tell why and the specific parameters caused this error. Any of params_dist below was not suitable for train_x.shape:(1630, 1565)? Please tell me any hints or solutions. Thank you. LightGBM version: '2.0.12' function caused this error: def get_lgbm(train_x, train_y, val_x, val_y): lgbm = lgb.LGBMRegressor( objective='regression', device='gpu', n_jobs=1, ) param_dist = {'boosting_type': ['gbdt', 'dart', 'rf'], 'num_leaves': sp.stats.randint(2, 1001), 'subsample_for_bin': sp.stats.randint(10, 1001), 'min_split_gain': sp.stats.uniform(0, 5.0), 'min_child_weight': sp.stats.uniform(1e-6, 1e-2), 'reg_alpha': sp.stats.uniform(0, 1e-2), 'reg_lambda': sp.stats.uniform(0, 1e-2), 'tree_learner': ['data', 'feature', 'serial', 'voting' ], 'application': ['regression_l1', 'regression_l2', 'regression'], 'bagging_freq': sp.stats.randint(1, 11), 'bagging_fraction': sp.stats.uniform(1e-3, 0.99), 'feature_fraction': sp.stats.uniform(1e-3, 0.99), 'learning_rate': sp.stats.uniform(1e-6, 0.99), 'max_depth': sp.stats.randint(1, 501), 'n_estimators': sp.stats.randint(100, 20001), 'gpu_use_dp': [True, False], } rscv = RandomizedSearchCV( estimator=lgbm, param_distributions=param_dist, cv=3, n_iter=3000, n_jobs=4, verbose=1, refit=True, fit_params={'eval_set':(val_x, val_y.ravel()), 'early_stopping_rounds':1, 'eval_metric':['l2', 'l1'], 'verbose': False, }, ) # This line throws error rscv = rscv.fit(train_x, train_y.ravel(), ) return rscv.best_estimator_ Too long to put full stack trace, here is on the lightgbm src. ........................................................................... /opt/conda/lib/python3.6/site-packages/lightgbm/sklearn.py in fit(self=LGBMRegressor(application='regression_l1', ..., subsample_freq=1, tree_learner='voting'), X=memmap([[-0.802568…
has comment: http://stackoverflow.com/comment/85252441
has title: LightGBMError "Check failed: num_data > 0" with Sklearn RandomizedSearchCV
answer count: 4
has comment: http://stackoverflow.com/comment/85253819
has answer: http://stackoverflow.com/a/73098097
has answer: http://stackoverflow.com/a/49837762

http://stackoverflow.com/a/49200659
downvote count: 1
answers question: http://stackoverflow.com/q/49200609
upvote count: 9
type: Answer
has body: The absolute value of a complex number a+bj, is defined as the distance between the origin (0,0) and the point (a,b) in the complex plane. In other words, it's sqrt(a2 + b2).
has comment: http://stackoverflow.com/comment/85413318
score: 8
has comment: http://stackoverflow.com/comment/85413018

http://stackoverflow.com/q/49164935
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49215926
tagged with: pandas
has comment: http://stackoverflow.com/comment/85335666
has title: How to use .loc with groupby and two conditions in pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/85375886
favorite count: 0
possible better answer: http://stackoverflow.com/a/49244325
type: Question
has answer: http://stackoverflow.com/a/49244325
has body: I asked a similar question here, but I want to expand on this question because I'm asked to do something a little different where I cannot use .duplicates() I have a df that's grouped by 'Key'. I want to flag any row within a group where the discharge date matches the admit date AND between those rows, the row with the discharge date has a num1 value in the range of 5-12. df = pd.DataFrame({'Key': ['10003', '10003', '10003', '10003', '10003','10003','10034', '10034'], 'Num1': [12,13,13,13,12,13,15,12], 'Num2': [121,122,122,124,125,126,127,128], 'admit': [20120506, 20120508, 20121010,20121010,20121010,20121110,20120520,20120520], 'discharge': [20120508, 20120510, 20121012,20121016,20121023,20121111,20120520,20120520]}) df['admit'] = pd.to_datetime(df['admit'], format='%Y%m%d') df['discharge'] = pd.to_datetime(df['discharge'], format='%Y%m%d') initial df Key Num1 Num2 admit discharge 0 10003 12 121 2012-05-06 2012-05-08 1 10003 13 122 2012-05-08 2012-05-10 2 10003 13 122 2012-10-10 2012-10-12 3 10003 13 124 2012-10-10 2012-10-16 4 10003 12 125 2012-10-10 2012-10-23 5 10003 13 126 2012-11-10 2012-11-11 6 10034 15 127 2012-05-20 2012-05-20 7 10034 12 128 2012-05-20 2012-05-20 final df Key Num1 Num2 admit discharge flag 0 10003 12 121 2012-05-06 2012-05-08 1 1 10003 13 122 2012-05-08 2012-05-10 1 2 10003 13 122 2012-10-10 2012-10-12 0 3 10003 13 124 2012-10-10 2012-10-16 0 4 10003 12 125 2012-10-10 2012-10-23 0 5 10003 13 126 2012-11-10 2012-11-11 0 6 10034 15 127 2012-05-20 2012-05-20 1 7 10034 12 128 2012-05-20 2012-05-20 1 I was trying to use filter() but I can't quite figure out how to apply any() to the discharge date. My logic was to pick the first admit date in a group and then check that date among each discharge date and once there is a match then check if the row that has the same discharge date has a value in Num1 in the range of 5-12. num1_range = [5,6,7,8,9,10,11,12] df.loc[df.groupby(['Key']).filter(lambda x : (x['admit'] == x['discharge'].any())&amp;(x['Nu…
answer count: 5
accepted answer: http://stackoverflow.com/a/49216115
tagged with: python
has answer: http://stackoverflow.com/a/49216115
has comment: http://stackoverflow.com/comment/85436476
has comment: http://stackoverflow.com/comment/85435818
has answer: http://stackoverflow.com/a/49215868
score: 11
has comment: http://stackoverflow.com/comment/85335269
upvote count: 11
has answer: http://stackoverflow.com/a/78597983
linked to: http://stackoverflow.com/q/49144154

http://stackoverflow.com/a/74352702
downvote count: 0
score: 1
upvote count: 1
has body: Final answer you can plug in: def count_number_of_parameters(model: nn.Module, only_trainable: bool = True) -&gt; int: &quot;&quot;&quot; Counts the number of trainable params. If all params, specify only_trainable = False. Ref: - https://discuss.pytorch.org/t/how-do-i-check-the-number-of-parameters-of-a-model/4325/9?u=brando_miranda - https://stackoverflow.com/questions/49201236/check-the-total-number-of-parameters-in-a-pytorch-model/62764464#62764464 :return: &quot;&quot;&quot; if only_trainable: num_params: int = sum(p.numel() for p in model.parameters() if p.requires_grad) else: # counts trainable and none-traibale num_params: int = sum(p.numel() for p in model.parameters() if p) assert num_params &gt; 0, f'Err: {num_params=}' return int(num_params)
type: Answer
answers question: http://stackoverflow.com/q/49201236

http://stackoverflow.com/comment/85328048
comment on: http://stackoverflow.com/q/49161231
type: Comment
type: QuestionComment
score: 4
has text: I get `op,ov = (<CartesianRepresentation (x, y, z) in m (-4205308.60307185, 4788305.10424286, 262644.44317487)>, <CartesianRepresentation (x, y, z) in m / s (-349.16875571, -306.65597541, 0.)>)` with Python 3.6. Googling "For this input type lists must contain either int or Ellipsis" leads me to [this thread](https://github.com/astropy/astropy/issues/7051) where it looks (from a quick glance) like it has to do with the numpy/astropy version. I suggest an upgrade, and if it doesn't help, it's probably more a question for StackOverflow. I don't think it has to do with astronomy.

http://stackoverflow.com/a/52254006
has body: I am using ubuntu 18.04 and I was facing exactly same issue after installing pillow following the official documentation. I tried all hacks shared by other users but no solution. But the problem got immediately resolved when I installed python-pil using the following command: sudo apt-get install python3-pil
has comment: http://stackoverflow.com/comment/139890360
type: Answer
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/49247310
downvote count: 0

http://stackoverflow.com/comment/85279229
type: QuestionComment
comment on: http://stackoverflow.com/q/49137041
has text: will there always be only 3 sub arrays or can the the number of subarrays increase?
score: 1
type: Comment

http://stackoverflow.com/comment/85365189
score: 0
comment on: http://stackoverflow.com/q/49179845
type: QuestionComment
type: Comment
has text: You can't share Python higher-level data structures like `dict` and `list` between processes in the first place. You can find libraries on PyPI that give you dict-like and list-like sharable data structures, but you can also find sharable "concurrent" data structures. And, for that matter, you can find persistent (non-mutating) sharable data structures for both languages.

http://stackoverflow.com/comment/85471946
has text: I can't use his because I need to specify column, there are some column that need to be used for average, min, max, etc, not just a sum.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49234358

http://stackoverflow.com/a/49259590
answers question: http://stackoverflow.com/q/49258949
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/106271047
has body: This should work: data.sort_values('date', inplace=True)
type: Answer

http://stackoverflow.com/q/49154090
has body: The full question, and I'm starting to learn python online but having issue with this question marked as easy Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ k=0 for i in range(i+1,len(nums)-1): j=i+1 for j in range(j+1,len(len(nums))): if nums[i] == nums[j]: del nums[j] len_list = nums return(len_list, nums)
has answer: http://stackoverflow.com/a/71300585
has comment: http://stackoverflow.com/comment/85313575
has comment: http://stackoverflow.com/comment/85313149
has comment: http://stackoverflow.com/comment/85312930
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85312998
score: 5
possible better answer: http://stackoverflow.com/a/65516394
has answer: http://stackoverflow.com/a/61368165
linked to: http://stackoverflow.com/q/49071897
upvote count: 5
has answer: http://stackoverflow.com/a/65516394
downvote count: 0
accepted answer: http://stackoverflow.com/a/49155588
tagged with: python
has answer: http://stackoverflow.com/a/49155588
answer count: 4
has title: Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length
type: AnsweredQuestion
tagged with: list

http://stackoverflow.com/a/56046347
score: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49144446
accepted answer of: http://stackoverflow.com/q/49144446
downvote count: 0
type: Answer
has body: try this: conda config --set ssl_verify false
upvote count: 3

http://stackoverflow.com/a/69484511
has body: This works (Python 3): def shapeArea(n): area = n*n + (n-1)*(n-1) return area print(shapeArea(5))
answers question: http://stackoverflow.com/q/49270277
downvote count: 0
upvote count: 1
score: 1
type: Answer

http://stackoverflow.com/q/49235375
has title: argparse store to multiple destination
accepted answer: http://stackoverflow.com/a/49240882
tagged with: python
has answer: http://stackoverflow.com/a/49235736
possible better answer: http://stackoverflow.com/a/49235736
type: AnsweredQuestion
score: 0
has body: I am writing a Python script. I have two variables with some default values. I want to pass one argument and set them to special values. Can I do it directly using argparse? My current code: import argparse ap = argparse.ArgumentParser() ap.add_argument('-s', help="set special values", action='store_true') args = ap.parse_args() if args.s: # special args.a = 100 args.b = 100 else: # default args.a = 10 args.b = 10 print(vars(args)) I want to do something like this: ap.add_argument("-s", action="store_const", dest=["a", "b"], const=[100,100], default=[10,10], help="set special values")
tagged with: argparse
has answer: http://stackoverflow.com/a/49240882
has comment: http://stackoverflow.com/comment/85512662
type: Question
has comment: http://stackoverflow.com/comment/85487940
answer count: 2
linked to: http://stackoverflow.com/q/48834678

http://stackoverflow.com/comment/85540375
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49268492
type: Comment
has text: alternatively you can do: working_directory = 'C:\\Users\\Admin\\Downloads\\'

windows-10
tags question: http://stackoverflow.com/q/49245355
tags question: http://stackoverflow.com/q/49197625
tags question: http://stackoverflow.com/q/49238744
tag name: windows-10
tags question: http://stackoverflow.com/q/49245642
tags question: http://stackoverflow.com/q/49183536
type: Tag

http://stackoverflow.com/comment/85416682
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49205715
type: QuestionComment
has text: Hi @Blender, that was just an example I need to make various changes like I also need to add `target="_blank"` to `PaypalPaymentsForm` .

http://stackoverflow.com/comment/85530355
type: Comment
has text: I guess this could have worked if the tests are part of the source distribution, but they're not (they depend on non-distributable setup data and are useless to distribute at the current stage). The first approach runs into horrible `ImportMismatchError`s and the second one can work if I add `{toxinidir}/tests` in addition to "." as an argument to `pytest` (after letting `tox` chdir), but it splits the coverage data in different virtualenvs and combining them requires extra processing.
comment on: http://stackoverflow.com/a/49260730
type: AnswerComment
score: 0

http://stackoverflow.com/q/49142463
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49142573
tagged with: python
has body: I'm trying to make some code Python 3 compatible. To my understanding, in Python 3, importing a module from the same package must be relative. So if this is the directory structure: /package /modA /modB there's a lot of existing code that looks like this (in modA): import modB modB.some_function() Is there a way to change the imports so I can keep calling the methods/properties the same way? I know you can do this: from .modB import some_function some_function() But I'd like to avoid changing all the calls if possible. When I call it like so: import .modB it gives an error
tagged with: python-2.7
score: 0
answer count: 3
upvote count: 1
has answer: http://stackoverflow.com/a/49142543
has title: Python 3 relative import full module
has answer: http://stackoverflow.com/a/52096880
downvote count: 1
tagged with: import
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/85389098
has text: Does it help if you flush first (`ds.FlushCache()`), or close the file and reopen?
comment on: http://stackoverflow.com/q/49182189
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49254129
tagged with: python
has comment: http://stackoverflow.com/comment/85512165
has comment: http://stackoverflow.com/comment/85521322
has comment: http://stackoverflow.com/comment/85511932
score: 0
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/22211525
type: Question
has comment: http://stackoverflow.com/comment/85512218
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85512190
has title: Dealing with pickel files in nltk corpora
has comment: http://stackoverflow.com/comment/85521485
has comment: http://stackoverflow.com/comment/85511707
has comment: http://stackoverflow.com/comment/85523186
tagged with: nltk
has comment: http://stackoverflow.com/comment/85513056
linked to: http://stackoverflow.com/q/49130879
has body: I am trying out nltk tutorial. The problem I was facing was that it requires to download various corpora. After all solutions failed to solve the problem I was facing to download nltk corpora with nltk.download(), I resorted to steps stated here. I started downloading corpora required for any example from this page, putting it in directory D:\nltk_data\corpora. I was able to try out various example. But then at one example I got error : Resource punkt not found. Please use the NLTK Downloader to obtain the resource: &gt;&gt;&gt; import nltk &gt;&gt;&gt; nltk.download('punkt') So I downloaded punkt from same page and copy pasted in same above directory. But it did not worked. Also tried to do from nltk.corpus import punkt as in case of other corpora. But no use. It says Unresolved import: punkt One difference in punkt from other corpora is that it contains pickle files instead of text files as in case of other corpora. How should I fix this? Code: import nltk; from nltk.corpus import gutenberg for fileid in gutenberg.fileids(): num_chars = len(gutenberg.raw(fileid)) num_words = len(gutenberg.words(fileid)) num_sents = len(gutenberg.sents(fileid)) num_vocab = len(set(w.lower() for w in gutenberg.words(fileid))) print(round(num_chars/num_words), round(num_words/num_sents), round(num_words/num_vocab), fileid) Error: Traceback (most recent call last): File "D:\Mahesh\workspaces\pyworkspace\nltkdemo\chp2\chp2.py", line 8, in &lt;module&gt; num_sents = len(gutenberg.sents(fileid)) File "D:\Softwares\python\WinPython-64bit-3.4.4.4Qt5\python-3.4.4.amd64\lib\nltk\corpus\reader\util.py", line 233, in __len__ for tok in self.iterate_from(self._toknum[-1]): pass File "D:\Softwares\python\WinPython-64bit-3.4.4.4Qt5\python-3.4.4.amd64\lib\nltk\corpus\reader\util.py", line 296, in iterate_from tokens = self.read_block(self._stream) File "D:\Softwares\python\WinPython-64bit-3.4.4.4Qt5\python-3.4.4.amd64\lib\nltk\corpus\reader\plaintext.py", line 129, in _read_sent_block for sent in …
tagged with: pickle

http://stackoverflow.com/a/49250154
has body: Try this: Before the: cell = browser.find_element_by_xpath("""//*[@id="module-detail"]/div/div/div[1]/div/div[3]/div[2]/span""") Line add browser.switch_to.window(browser.current_window_handle) Then it try again. Hope this will helps you! :)
score: 0
answers question: http://stackoverflow.com/q/49249853
type: Answer

http://stackoverflow.com/q/49154375
favorite count: 0
has body: I have a dataframe that looks like this: intakeNo 1 2 3 intakeDate 3/21/1978 4/28/1979 1/11/1981 intakeAmt 9.3E-04 5.1E-02 2.4E-04 intakeSD 2.2E-02 7.7E-01 5.8E-03 incident F F F intakeDate 3/19/1978 5/6/1979 1/3/1981 intakeAmt 3.2E-02 1.9E-02 4.7E-03 intakeSD 9.6E-01 5.3E-01 1.4E-01 I could get the average of say intakeAmt by df.loc['intakeAmt_avg'] = df.loc['intakeAmt'].mean() But, I would like to apply the following function to get the average of the intakeDates in the dataframe, and add a row called, say intakeDate_avg: def average_of_two_dates(datestr1, datestr2): a = dt.datetime.strptime(datestr1, '%m/%d/%Y') b = dt.datetime.strptime(datestr2, '%m/%d/%Y') ave = a+(b-a)/2 return dt.datetime.strftime(ave, "%m/%d/%Y") First, I have tried transposing the 'intakeDate' slice of the df: a = df['intakeDate'] b = a.T which gives me the following dataframe b: intakeNo intakeDate intakeDate 1 3/21/1978 3/19/1978 2 4/28/1979 5/6/1979 3 1/11/1981 1/3/1981 Now, I need to add a column called intakeDate_avg that applies the average_of_two_dates function to the values in the two intakeDate columns. The original transposed df looks like: intakeNo intakeDate intakeAmt intakeSD incident intakeDate intakeAmt intakeSD 1 3/21/1978 9.30E-04 2.20E-02 F 3/19/1978 3.20E-02 9.60E-01 2 4/28/1979 5.10E-02 7.70E-01 F 5/6/1979 1.90E-02 5.30E-01 3 1/11/1981 2.40E-04 5.80E-03 F 1/3/1981 4.70E-03 1.40E-01
has answer: http://stackoverflow.com/a/49154612
tagged with: pandas
has comment: http://stackoverflow.com/comment/85315266
answer count: 1
has comment: http://stackoverflow.com/comment/85314491
tagged with: dataframe
score: -1
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/85314252
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85316781
has comment: http://stackoverflow.com/comment/85316696
tagged with: python
has comment: http://stackoverflow.com/comment/85313420
downvote count: 1
has title: Apply a formula to two rows in a pandas dataframe

http://stackoverflow.com/a/49164767
has body: You can try this: import re s = ['C b a', 'c B a', 'c b A'] new_s = sorted(s, key=lambda x:re.findall('[A-Z]+', x)[0]) Output: ['c b A', 'c B a', 'C b a']
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49164711
score: 3
type: Answer

http://stackoverflow.com/a/49182622
accepted answer of: http://stackoverflow.com/q/49182568
upvote count: 5
score: 5
answers question: http://stackoverflow.com/q/49182568
type: Answer
has body: Strings are immutable, the str.split() method doesn't change the string you split. Instead, a new list is returned. You got confused by what happens in the shell when you don't assign the result of an expression and just echo that result instead. When you executed x.split(), the new list was returned and echoed in the shell. That list was not referenced by anything else, and x still points to the original string, which didn't change. type(x) shows that x still points to the original string. Next, you actually assigned the list that str.split() produced, to a new name y. You then echoed y and tested the type of y, which is the list object produced by str.split(). That's logical, because you told Python to make y a reference to the result of x.split(). type(y) tells you that y references a list object. I strongly recommend you read the excellent Facts and myths about Python names and values by Ned Batchelder, it explains, in very clear terms, how names (like x and y) are different from the Python objects like the string "Hello, string methods!" or the list ['Pleased', 'to', 'meet', 'you'].
has comment: http://stackoverflow.com/comment/85371364
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/49275686
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49276088
tagged with: python
has title: Add new columns to comma delimited text file python
has answer: http://stackoverflow.com/a/49276088
has comment: http://stackoverflow.com/comment/85553860
type: Question
has comment: http://stackoverflow.com/comment/85553836
has comment: http://stackoverflow.com/comment/85553789
upvote count: 0
answer count: 1
downvote count: 3
score: -3
has body: I am new to python and facing some problems. I have a file with two columns separated by comma having numerical values (sample) - 2306,12017 2307,9416.6 2308,7378.5 2309,5781.4 and so on.. I am willing to have an output file somewhat like this - bfe,2306,hgen,,12017 bfe,2307,hgen,,9416.6 bfe,2308,hgen,,7378.5 bfe,2309,hgen,,5781.4 and so on.. thanks in advance. This is what I have tried so far, data = open("myFile1.txt", "r").readlines() output = ["%s,%s,%s,%s" % ("bfe",item.strip(),"hgen",item.strip()) for item in data] f = open("output.txt", "w") f.write("\n".join(output)) f.close()
favorite count: 0

http://stackoverflow.com/q/49125405
answer count: 2
has body: I am new to Machine Learning and python. Recently i have been working with Amazon fine food review data from kaggle and its code. What i don't understand is how is the 'partiton' method used here ? Moreover, What actually does last 3 lines of code do ? %matplotlib inline import sqlite3 import pandas as pd import numpy as np import nltk import string import matplotlib.pyplot as plt import seaborn as sns from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text import CountVectorizer from sklearn.metrics import confusion_matrix from sklearn import metrics from sklearn.metrics import roc_curve, auc from nltk.stem.porter import PorterStemmer # using the SQLite Table to read data. con = sqlite3.connect('./amazon-fine-food-reviews/database.sqlite') #filtering only positive and negative reviews i.e. # not taking into consideration those reviews with Score=3 filtered_data = pd.read_sql_query(""" SELECT * FROM Reviews WHERE Score != 3 """, con) # Give reviews with Score&gt;3 a positive rating, and reviews with a score&lt;3 a negative rating. def partition(x): if x &lt; 3: return 'negative' return 'positive' #changing reviews with score less than 3 to be positive vice-versa actualScore = filtered_data['Score'] positiveNegative = actualScore.map(partition) filtered_data['Score'] = positiveNegative
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85255650
has answer: http://stackoverflow.com/a/49125545
downvote count: 1
tagged with: machine-learning
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85256026
has comment: http://stackoverflow.com/comment/85255560
has title: Trying to work out a python code
has comment: http://stackoverflow.com/comment/85256127
tagged with: kaggle
tagged with: python
has answer: http://stackoverflow.com/a/58678677
score: -1
has comment: http://stackoverflow.com/comment/85255951
tagged with: data-science
has comment: http://stackoverflow.com/comment/85255757
has comment: http://stackoverflow.com/comment/85255977
upvote count: 0

http://stackoverflow.com/q/49153253
downvote count: 0
linked to: http://stackoverflow.com/q/21287624
linked to: http://stackoverflow.com/q/3793838
has answer: http://stackoverflow.com/a/49153755
accepted answer: http://stackoverflow.com/a/49153755
score: 42
has answer: http://stackoverflow.com/a/67032376
tagged with: int
has answer: http://stackoverflow.com/a/49153785
type: AnsweredQuestion
has body: I've got a pandas DataFrame with a float (on decimal) index which I use to look up values (similar to a dictionary). As floats are not exactly the value they are supposed to be multiplied everything by 10 and converted it to integers .astype(int) before setting it as index. However this seems to do a floor instead of rounding. Thus 1.999999999999999992 is converted to 1 instead of 2. Rounding with the pandas.DataFrame.round() method before does not avoid this problem as the values are still stored as floats. The original idea (which obviously rises a key error) was this: idx = np.arange(1,3,0.001) s = pd.Series(range(2000)) s.index=idx print(s[2.022]) trying with converting to integers: idx_int = idx*1000 idx_int = idx_int.astype(int) s.index = idx_int for i in range(1000,3000): print(s[i]) the output is always a bit random as the 'real' value of an integer can be slightly above or below the wanted value. In this case the index contains two times the value 1000 and does not contain the value 2999.
tagged with: rounding
tagged with: pandas
tagged with: python
tagged with: floating-point
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/68173440
upvote count: 42
type: Question
possible better answer: http://stackoverflow.com/a/49153785
has title: pandas rounding when converting float to integer

http://stackoverflow.com/comment/85416228
type: QuestionComment
comment on: http://stackoverflow.com/q/49203161
score: 0
has text: I dont think a database would be necessary for remembering what a user entered in the same script. I am just trying to pass the users information from a previous function into a different function
type: Comment

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/49234333
tags question: http://stackoverflow.com/q/49253272
tag name: kivy-language
tags question: http://stackoverflow.com/q/49277692
tags question: http://stackoverflow.com/q/49167891

http://stackoverflow.com/q/49215718
tagged with: http://stackoverflow.com/tag/csv
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49215756
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/49215756
score: 1
has body: Hello so I am having a problem with some of my python. I am trying to make a program to take in a csv file and tell me the 50 highest appearing words in a column. my csv file follows this format: ID, City, State, Hotel Name, Price 1, Atlanta, GA, Le Royale, 200 I want for instance to go through this list and tell me the 50 most common cities. My code: def count_amount(fin_name): with open(fin_name, 'rb') as fin: reader = csv.reader(fin) next(reader) sortedlist = sorted(reader, key=operator.itemgetter(1), reverse=False) d = defaultdict(list) for row in sortedlist: print(row[0], row[1], row[2], row[3], row[4]) if row[1] != 'City': d[row[1]].append(float(row[3])) for k,v in d.iteritems(): c = Counter(k) print c.most_common(50) I'm sure that my problem is coming from my c = Counter(k), it prints the individual letters of each city name instead of the city itself. So it will print (('a', 2), ('d', 1), ('k', 1), ('l', 1), ('O', 1), ('n', 1) instead of telling me how many times 'Oakland' shows up in my csv file. How do I get it to show me the entire string? (note: I am aware of the indentation I am just terrible at entering my code into stack overflow)
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Trouble getting the top N reoccuring values out of a csv file

http://stackoverflow.com/comment/85356004
type: Comment
comment on: http://stackoverflow.com/q/49159952
type: QuestionComment
has text: None in particular but i just need monitor Job name and total pages. I updated this topic to show full code. If i use pywin32, what is the array index containin total document pages?
score: 0

http://stackoverflow.com/comment/113506148
has text: But what do the variables a, b, c, d, and e that you've used represent?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49186164
type: AnswerComment

http://stackoverflow.com/q/49231677
accepted answer: http://stackoverflow.com/a/49231689
has comment: http://stackoverflow.com/comment/88441364
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49231689
tagged with: pandas
upvote count: 2
has body: I am trying to drop a list of columns that are in df cols = df.columns[df.isna().any()].tolist() df = df.dropna([cols], axis = 1) But I get the error TypeError: dropna() got multiple values for argument 'axis' Any ideas how I can drop the list in cols ?
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: TypeError: dropna() got multiple values for argument 'axis'
tagged with: python

http://stackoverflow.com/comment/85485049
has text: *Where* do you need to retain the ability to perform arithmetic? You've cited only Python and PANDAS in your tags, but your text suggests that you need that capability in Excel.
type: Comment
comment on: http://stackoverflow.com/q/49240707
type: QuestionComment
score: 0

http://stackoverflow.com/a/49254638
downvote count: 0
answers question: http://stackoverflow.com/q/49254337
type: Answer
score: 3
upvote count: 3
has body: One of the solutions could be this: the object returned by the plot has an ax_heatmap method that has a set_title method. If you set it with a title your plot will have one: import seaborn as sns sns.set(color_codes=True) iris = sns.load_dataset("iris") species = iris.pop("species") g = sns.clustermap(iris) g.ax_heatmap.set_title('lalal') However this approach adds a title above your heatmap and not the whole plot.

http://stackoverflow.com/a/54027213
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49146065
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49146065
has body: UserWarning: Update your `Model` call to the Keras 2 API: `Model(inputs=[&lt;tf.Tenso…, outputs=Tensor(“ma…)` model = Model(input=[sentence_input, neg_input], output=loss) Here we can see that the new api of keras, the input and output should be inputs and outputs. The original code is: model = Model(input=[sentence_input, neg_input], output=loss) So if we want to get this warning away, we should write like this: model = Model(inputs=[sentence_input, neg_input], outputs=loss) Just a little s here and there, that’s all.

http://stackoverflow.com/comment/85814381
comment on: http://stackoverflow.com/a/49347108
has text: @Anton Kostenko
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/49279280
score: 0
has answer: http://stackoverflow.com/a/49280478
tagged with: scikit-image
has comment: http://stackoverflow.com/comment/85561665
has comment: http://stackoverflow.com/comment/85563200
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49280478
has answer: http://stackoverflow.com/a/49284181
answer count: 2
has comment: http://stackoverflow.com/comment/85562021
has body: I was going through a code of converting gray images to colored images, but before doing that, code converts the input image to desaturated image with the help of given line of code : def load_image(path): img = imread(path) # crop image from center short_edge = min(img.shape[:2]) yy = int((img.shape[0] - short_edge) / 2) xx = int((img.shape[1] - short_edge) / 2) crop_img = img[yy : yy + short_edge, xx : xx + short_edge] # resize to 224, 224 img = skimage.transform.resize(crop_img, (224, 224)) # desaturate image return (img[:,:,0] + img[:,:,1] + img[:,:,2]) / 3.0 I am getting error in this particular line, error read as: return (img[:,:,0] + img[:,:,1] + img[:,:,2]) / 3.0 IndexError: too many indices for array Please help me with the problem i am facing.
tagged with: python
tagged with: image
type: AnsweredQuestion
has title: How to desaturate the image in Python?
accepted answer: http://stackoverflow.com/a/49284181

http://stackoverflow.com/comment/85427801
has text: Please also add the code you call `__goal_action_callback`.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49211064
score: 0

http://stackoverflow.com/a/49167171
has comment: http://stackoverflow.com/comment/85339835
score: 0
has comment: http://stackoverflow.com/comment/85339652
answers question: http://stackoverflow.com/q/49167056
has comment: http://stackoverflow.com/comment/85340007
has body: Most likely, the installation of node.msi modifies your system's PATH variable. This change does not become visible inside your running Python process. If you know the path to your node installation, you can specify it explicitly in a call such as subprocess.run([r'C:\node\bin\apium.exe', '-v'])
has comment: http://stackoverflow.com/comment/85339904
type: Answer

http://stackoverflow.com/comment/85424204
score: 1
has text: `requests` will only get the initial HTML page content, not any content subsequently loaded via JavaScript. There are endless duplicates here about web scraping sites with JS, see e.g. https://stackoverflow.com/q/8049520/3001761.
type: Comment
comment on: http://stackoverflow.com/q/49209765
type: QuestionComment

http://stackoverflow.com/comment/85391848
has text: Doesn't work either. At the 15s index, Time is now 19.999. Also FYI, `how` seems to be deprecated in future versions: `FutureWarning: how in .resample() is deprecated the new syntax is .resample(...).last()`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49191998
score: 0

http://stackoverflow.com/a/70561986
downvote count: 2
upvote count: 9
has body: View the environments in Anaconda or miniconda: conda env list If you have created an environment using name then use: conda remove -n envname --all if you have created an environment using prefix then use: conda remove -p [path] --all Change the envname with your environment name and in case of prefix provide the complete path of the environment eg: C:/Users/techv/Desktop/project/env. --all will remove all the dependencies of the target environment. I hope this answer will be helpful.
answers question: http://stackoverflow.com/q/49127834
score: 7
type: Answer

http://stackoverflow.com/q/49147875
answer count: 3
has comment: http://stackoverflow.com/comment/85300696
score: 1
possible better answer: http://stackoverflow.com/a/49148449
downvote count: 0
tagged with: utf-8
has title: How to save/load a 2d array containing unicode to/from a .txt file [Python] [encoding issues][utf8]
upvote count: 1
has comment: http://stackoverflow.com/comment/85301610
has answer: http://stackoverflow.com/a/49148449
tagged with: unicode
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49149856
tagged with: python
has body: So the basic issue i am having is when i write to the txt file the unicode character \u2656 becomes this b'\xe2\x99\x96' (i believe this is byte code?). Then when i read the file i cannot decode it back to \u2656. Board_visual is just a 2d array where each item is either a unicode character or None type (an empty square). It is used to represent the position of pieces on a chess board used by my tkinter gui. The actual pieces are objects so this is just the unicode characters that represent chess pieces. Example board_visual contents ['♖', '♘', '♗', '♔', '♕', '♗', '♘', '♖'] ['♙', None, '♙', '♙', '♙', '♙', '♙', '♙'] [None, '♙', None, None, None, None, None, None] [None, None, None, None, None, None, None, None] [None, None, None, '♟', None, None, None, None] [None, None, None, None, None, None, None, None] ['♟', '♟', '♟', None, '♟', '♟', '♟', '♟'] ['♜', '♞', '♝', '♚', '♛', '♝', '♞', '♜'] Here is the code i used: def save(): filename=input("Enter the name of the file") myFile=open(str(filename)+".txt","w") for i in board_visual: for j in i: myFile.write(str(str(j).encode('utf8'))) myFile.write("\n") myFile.close() It gives this file format (in the .txt file): b'\xe2\x99\x97' b'\xe2\x99\x98' b'\xe2\x99\x96' b'None' b'\xe2\x99\x99' b'\xe2\x99\x99' b'None' b'\xe2\x99\x99' b'\xe2\x99\x99' b'\xe2\x99\x99' b'\xe2\x99\x99' b'None' ... Then i attempt to read it with def load(): global board_visual global board filename=input("Enter the name of the file") myFile=open(str(filename)+".txt","r", encoding='utf8') index=0 index2=0 for i in myFile: if i!="b'None'\n": i=i.strip("\n") board_visual[index//8][index%8]=i#places it into the 8*8 grid else: board_visual[index//8][index%8]=None index=index+1 myFile.close() A few posts on this website mention using .decode but that only works in python 2 i'm using python 3.3, This program worked perfectly when i didn't have any unicode characters.This means the issue must be with the encoding but this is my first time working with it and i ca…
has comment: http://stackoverflow.com/comment/85300794
accepted answer: http://stackoverflow.com/a/49148592
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49148592

http://stackoverflow.com/comment/85488608
type: AnswerComment
has text: You'll end up with a list that looks just like your current the_list which you can use however you wish. And correct, you could safely remove your filter line and your filter function. You could do `small_states = [x for x in the_list if x[1] < 10]` and `large_states = [x for x in the_list if x[1] > 20]` or whatever numbers you wanted
type: Comment
comment on: http://stackoverflow.com/a/49242141
score: 0

http://stackoverflow.com/comment/85577495
type: AnswerComment
has text: There seems to be some problem with your imports that you need to figure out. Have you imported gtk? I had to import the following modules: `import gtk`, `import gtk.gdk`, `import gobject`, `import pygtk`.
type: Comment
comment on: http://stackoverflow.com/a/49276075
score: 0

nltk
tags question: http://stackoverflow.com/q/49197667
tags question: http://stackoverflow.com/q/49208630
tags question: http://stackoverflow.com/q/49207097
tags question: http://stackoverflow.com/q/49217493
tags question: http://stackoverflow.com/q/49218417
tags question: http://stackoverflow.com/q/49240058
tag name: nltk
tags question: http://stackoverflow.com/q/49263269
tags question: http://stackoverflow.com/q/49147128
tags question: http://stackoverflow.com/q/49255795
tags question: http://stackoverflow.com/q/49130879
tags question: http://stackoverflow.com/q/49161277
tags question: http://stackoverflow.com/q/49251629
tags question: http://stackoverflow.com/q/49219826
tags question: http://stackoverflow.com/q/49270817
tags question: http://stackoverflow.com/q/49128964
tags question: http://stackoverflow.com/q/49206399
tags question: http://stackoverflow.com/q/49216339
tags question: http://stackoverflow.com/q/49143626
tags question: http://stackoverflow.com/q/49165289
tags question: http://stackoverflow.com/q/49193966
tags question: http://stackoverflow.com/q/49260329
tags question: http://stackoverflow.com/q/49219142
type: Tag
tags question: http://stackoverflow.com/q/49254129
tags question: http://stackoverflow.com/q/49193435
tags question: http://stackoverflow.com/q/49166071

http://stackoverflow.com/a/49267349
type: Answer
answers question: http://stackoverflow.com/q/49267293
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49267293
has body: Your list appears to be valid python, so regex is not an option (regexes cannot reliably parse programming languages). Consider ast.literal_eval instead: &gt;&gt;&gt; s = "['abc', 'xxx', '3c2', '111112', 'x']" &gt;&gt;&gt; import ast &gt;&gt;&gt; ast.literal_eval(s)[0] 'abc' If you insist of using regexes, you'll have to create a fairy complex expression to match python literals. A naive example, that only handles single-quoted strings, would be: &gt;&gt;&gt; s = "['abc', 'xxx', '3c2', '111112', 'x']" &gt;&gt;&gt; import re &gt;&gt;&gt; str_re = r"'(\\.|[^'])*'" &gt;&gt;&gt; re.search(str_re, s).group(1) 'abc' Quite obviously, adding double-quoted, multi-quoted, raw- and byte-strings, and eventually a variety of number formats to this would be a tedious and totally pointless job ;)

http://stackoverflow.com/comment/85553494
has text: Wouldn't you want to compare last day of each month? Seems like if you compare last day with first day, you'll miss one day
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49275514
type: QuestionComment

http://stackoverflow.com/comment/85332402
has text: Where are you running the code ?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49163367
type: QuestionComment

http://stackoverflow.com/comment/85551431
comment on: http://stackoverflow.com/a/49273514
score: 0
has text: Now when I want to use it for my real Excel-File, I get the UserWarnings: "Conditional Formatting extension is not supported and will be removed" and "Data Validation extension is not supported and will be removed", which completely messes up my file. Do you know any workarounds for this aswell?
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49221705
score: 0
type: AcceptedAnswer
has body: In summary, you can use the builtin functions: sort or sorted. The difference is that, using sort you will change your original list, while using sorted will not. First, you need to set accordingly your special value for each of your list Example object: for example in list: example.see_if_special() After that, you can do a sort on your list: list.sort(key=lambda example: int(example.special), reverse=True) Or generate a new list without modifying your original list: sorted(list, key=lambda example: int(example.special), reverse=True)
accepted answer of: http://stackoverflow.com/q/49221571
answers question: http://stackoverflow.com/q/49221571
type: Answer

http://stackoverflow.com/comment/85476441
comment on: http://stackoverflow.com/q/49233188
score: 0
type: Comment
has text: Yes. You can keep a reference to each of the values returned by `create_rect`, and change their colors later with `itemconfig`. You can also use the canvas' various `find` methods to locate rectangles based on coordinates. (although if your rects are in a nice grid pattern, it may be faster to find them with arithmetic, e.g. `row=y//rectangle_height; col=x//rectangle_width; rect=my_rectangle_references[col][row]`)
type: QuestionComment

http://stackoverflow.com/q/49122265
has comment: http://stackoverflow.com/comment/85250332
tagged with: while-loop
has comment: http://stackoverflow.com/comment/85250076
has body: I am trying to write a program/code that asks the user for how many steps to draw the stairs. The user will always enter an integer greater than zero. Example, if entered 4, the output should be next: How many steps? 4 _ _ #top line made out of 2 underscores |_ |_ |_ ______ _ | #bottom line consist of 8 underscores The horizontal lines are created using underscores (_) and the vertical lines using the pipe character (|). My code is next: n = int(input("How many steps? ")) print('_ _') while n &gt; 0: n = n-1 a = " |_" print (n*a) print (n*'|_') print('_'*2*n, '|') This is what I get: How many steps? 4 _ _ |_ |_ |_ |_|_|_ ______ | |_ |_ |_|_ ____ | |_ |_ __ | __ | | I am confused with those lines. Thanks for help!
tagged with: python
has answer: http://stackoverflow.com/a/49141521
has comment: http://stackoverflow.com/comment/85250036
has comment: http://stackoverflow.com/comment/85250025
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85250085
downvote count: 4
type: UnansweredQuestion
has title: Trying to write a code in Python 3 that asks for how many steps to draw the stairs
answer count: 1
score: -3
upvote count: 1
tagged with: loops
tagged with: string
has comment: http://stackoverflow.com/comment/85250049
has comment: http://stackoverflow.com/comment/85250089

http://stackoverflow.com/q/49265404
has body: How do I merge a specific value from one array of dicts into another array of dicts if a single specific value matches between them? I have an array of dicts that represent books books = [{'writer_id': '123-456-789', 'index': None, 'title': 'Yellow Snow'}, {'writer_id': '888-888-777', 'index': None, 'title': 'Python for Dummies'}, {'writer_id': '999-121-223', 'index': 'Foo', 'title': 'Something Else'}] and I have an array of dicts that represents authors authors = [{'roles': ['author'], 'profile_picture': None, 'author_id': '123-456-789', 'name': 'Pat'}, {'roles': ['author'], 'profile_picture': None, 'author_id': '999-121-223', 'name': 'May'}] I want to take the name from authors and add it to the dict in books where the books writer_id matches the authors author_id. My end result would ideally change the book array of dicts to be (notice the first dict now has the value of 'name': 'Pat' and the second book has 'name': 'May'): books = [{'writer_id': '123-456-789', 'index': None, 'title': 'Yellow Snow', 'name': 'Pat'}, {'writer_id': '888-888-777', 'index': None, 'title': 'Python for Dummies'}, {'writer_id': '999-121-223', 'index': 'Foo', 'title': 'Something Else', 'name': 'May'}] My current solution is: for book in books: for author in authors: if book['writer_id'] == author['author_id']: book['author_name'] = author['name'] And this works. However, the nested statements bother me and feel unwieldy. I also have a number of other such structures so I end up with a function that has a bunch of code resembling this in it: for book in books: for author in authors: if book['writer_id'] == author['author_id']: book['author_name'] = author['name'] books_with_foo = [] for book in books: for thing in things: if something: // do something for blah in books_with_foo: for book_foo in otherthing: if blah['bar'] == stuff['baz']: // etc, etc. Alternatively, how would you aggregate data from multiple database tables into one thing... some of the data comes back as dicts, some as arr…
accepted answer: http://stackoverflow.com/a/49265721
has comment: http://stackoverflow.com/comment/85534653
has comment: http://stackoverflow.com/comment/85534436
has title: Merge a specific value from one array of dicts into another if a value matches
has answer: http://stackoverflow.com/a/49265721
tagged with: python
tagged with: list-comprehension
type: AnsweredQuestion
score: 1
tagged with: dictionary-comprehension
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85534344
has comment: http://stackoverflow.com/comment/85534643

http://stackoverflow.com/comment/85332834
comment on: http://stackoverflow.com/q/49155102
score: 0
type: Comment
type: QuestionComment
has text: Your edit is insufficient to diagnose the issue. Please read the link ekhumoro posted.

http://stackoverflow.com/comment/85469741
type: AnswerComment
comment on: http://stackoverflow.com/a/49226792
has text: What if the shape of x is unknown? For example, the first dimension of x and y are computed in the runtime and I do not know the value during graph construction. `tf.range` function will fail if the parameter is `Dimension(None)`.
type: Comment
score: 0

http://stackoverflow.com/a/49263197
answers question: http://stackoverflow.com/q/49263071
downvote count: 0
upvote count: 1
has body: That's because you executed the len() function at the top, when the list is still empty: prices=[] # ... nItems = len(prices) Calling len() produces a result, here the integer 0, and the name nItems is then set to reference that result. Python does not store anything about how the value a name references was produced, nItems only references the integer, not that the integer was produced from a call to the function len() applied to the list prices. Until you assign something different to nItems, it'll keep pointing to 0. You then call discount(), and in the function print nItems. It still references 0, and so that results in 0 being printed. If you wanted to print the length of prices, you need to call len() again. Either print the result of the len() call: print(len(prices)) or assign the result to a variable and then print that variable: price_count = len(prices) print(price_count)
score: 1
type: Answer

http://stackoverflow.com/comment/85259874
score: 0
comment on: http://stackoverflow.com/a/49127586
type: Comment
type: AnswerComment
has text: tree1 is the name of treeview, I can not change that. I use that to get the values for tree view.

http://stackoverflow.com/comment/85629555
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49268387
type: QuestionComment
has text: Updated the answer to include Python3 (your linux system). Hope that helps!

http://stackoverflow.com/comment/85499075
comment on: http://stackoverflow.com/q/49247648
type: Comment
type: QuestionComment
has text: Why use a list comprehension that creates a list of pairs just to pass it to `dict`, when you can use a dict comprehension instead? `dict1 = {tournamentResults[i]: rankingPoints[8] for i in range(0, len(tournamentResults))}` Or, more simply, `dict1 = {result: rankingPoints[8] for result in tournamentResults}`
score: 0

http://stackoverflow.com/a/49259581
type: Answer
upvote count: 48
has body: One trivial solution is to choose a method dependent on an estimate of how completely values are covered by dictionary keys. General case Use df['A'].map(d) if all values mapped; or Use df['A'].map(d).fillna(df['A']).astype(int) if >5% values mapped. Few, e.g. &lt; 5%, values in d Use df['A'].replace(d) The "crossover point" of ~5% is specific to Benchmarking below. Interestingly, a simple list comprehension generally underperforms map in either scenario. Benchmarking import pandas as pd, numpy as np df = pd.DataFrame({'A': np.random.randint(0, 1000, 1000000)}) lst = df['A'].values.tolist() ##### TEST 1 - Full Map ##### d = {i: i+1 for i in range(1000)} %timeit df['A'].replace(d) # 1.98s %timeit df['A'].map(d) # 84.3ms %timeit [d[i] for i in lst] # 134ms ##### TEST 2 - Partial Map ##### d = {i: i+1 for i in range(10)} %timeit df['A'].replace(d) # 20.1ms %timeit df['A'].map(d).fillna(df['A']).astype(int) # 111ms %timeit [d.get(i, i) for i in lst] # 243ms Explanation The reason why s.replace is so slow is that it does much more than simply map a dictionary. It deals with some edge cases and arguably rare situations, which typically merit more care in any case. This is an excerpt from replace() in pandas\generic.py. items = list(compat.iteritems(to_replace)) keys, values = zip(*items) are_mappings = [is_dict_like(v) for v in values] if any(are_mappings): # handling of nested dictionaries else: to_replace, value = keys, values return self.replace(to_replace, value, inplace=inplace, limit=limit, regex=regex) There appear to be many steps involved: Converting dictionary to a list. Iterating through list and checking for nested dictionaries. Feeding an iterator of keys and values into a replace function. This can be compared to much leaner code from map() in pandas\series.py: if isinstance(arg, (dict, Series)): if isinstance(arg, dict): arg = self._constructor(arg, index=arg.keys()) indexer = arg.index.get_indexer(values) new_values = algos.take_1d(arg._values, indexer)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49259580
answers question: http://stackoverflow.com/q/49259580
score: 48

http://stackoverflow.com/q/49266390
has title: Python: Count combinations of values within two columns and find max frequency of each combination
downvote count: 0
answer count: 1
favorite count: 0
tagged with: calculated-columns
type: Question
accepted answer: http://stackoverflow.com/a/49266583
has answer: http://stackoverflow.com/a/49266583
tagged with: dataframe
tagged with: python
has body: My pandas dataframe looks like this: +-----+---------+-------+ | No. | Section | Group | +-----+---------+-------+ | 123 | 222 | 1 | | 234 | 222 | 1 | | 345 | 222 | 1 | | 456 | 222 | 3 | | 567 | 241 | 1 | | 678 | 241 | 2 | | 789 | 241 | 2 | | 890 | 241 | 3 | +-----+---------+-------+ First, I need to add another column containing the frequency of each combination of Section and Group. It is important to keep all rows. Desired output: +-----+---------+-------+-------+ | No. | Section | Group | Count | +-----+---------+-------+-------+ | 123 | 222 | 1 | 3 | | 234 | 222 | 1 | 3 | | 345 | 222 | 1 | 3 | | 456 | 222 | 3 | 1 | | 567 | 241 | 1 | 1 | | 678 | 241 | 2 | 2 | | 789 | 241 | 2 | 2 | | 890 | 241 | 3 | 1 | +-----+---------+-------+-------+ The second step would be marking the highest value within Count for each Section. For example, with a True/False column like this: +-----+---------+-------+-------+-------+ | No. | Section | Group | Count | Max | +-----+---------+-------+-------+-------+ | 123 | 222 | 1 | 3 | True | | 234 | 222 | 1 | 3 | True | | 345 | 222 | 1 | 3 | True | | 456 | 222 | 3 | 1 | False | | 567 | 241 | 1 | 1 | False | | 678 | 241 | 2 | 2 | True | | 789 | 241 | 2 | 2 | True | | 890 | 241 | 3 | 1 | False | +-----+---------+-------+-------+-------+ The original data frame has lots of rows. That is why I'm asking for an efficient way because I cannot think of one. Thank you very much!
score: 2
type: AnsweredQuestion
tagged with: pandas
upvote count: 2

http://stackoverflow.com/a/49130087
upvote count: 7
accepted answer of: http://stackoverflow.com/q/49129858
score: 7
type: Answer
answers question: http://stackoverflow.com/q/49129858
has body: weights = [layer.get_weights() for layer in model.layers]
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49189054
type: AnsweredQuestion
upvote count: 0
has title: How do i remove this error?
answer count: 1
favorite count: 0
has body: I am trying to count the number of times the word 'awesome' has been used in the dictionary and use that function in order to apply it on an SFrame data. but i keep getting an error stating -local variable 'aw_count' referenced before assignment the code is something like this:: def awesome_count(word_count): if 'awesome' in word_count: aw_count = word_count['awesome'] return aw_count; products['awesome'] = products['word_count'].apply(awesome_count)
type: Question
downvote count: 2
accepted answer: http://stackoverflow.com/a/49189071
tagged with: python
has answer: http://stackoverflow.com/a/49189071
score: -2
tagged with: sframe

http://stackoverflow.com/a/49151093
score: 0
has body: Try this: &gt;&gt;&gt; import json &gt;&gt;&gt; str = ''' ... { ... "page" : 0, ... "size" : 20, ... "totalCount" : 2, ... "data" : [ { ... "namespace" : "android", ... "id" : "0000001111111", ... "creationTs" : 1516216756819, ... "name" : "Eric's phone", ... "description" : "This device was auto registered by [mqtt] ", ... "tags" : [ ], ... "properties" : { }, ... "lastUpdateTs" : 1518610495832, ... "connected" : false, ... "path" : [ ], ... "metadata" : { ... "api_key_id" : "XXX000XXX000XXX", ... "connection_start_time" : "2018-02-14T12:14:04.778Z", ... "mqtt_version" : 4, ... "mqtt_username" : "json+device", ... "mqtt_timeout" : 20, ... "remote_addr" : "00.00.00.00/PORT" ... }, ... "groupId" : "root", ... "groupPath" : "/" ... }, { ... "namespace" : "sensor", ... "id" : "temp001", ... "creationTs" : 1520415684605, ... "name" : "mySensor001", ... "description" : "moisture sensor", ... "tags" : [ "france", "lyon" ], ... "properties" : { ... "manufacturer" : "miel", ... "model" : "MoistureSensorV3" ... }, ... "lastUpdateTs" : 1520415684605, ... "connected" : false, ... "path" : [ ], ... "groupId" : "root", ... "groupPath" : "/" ... } ]}''' &gt;&gt;&gt; d = json.loads(str) &gt;&gt;&gt; d {u'totalCount': 2, u'data': [{u'lastUpdateTs': 1518610495832L, u'description': u'This device was auto registered by [mqtt] ', u'tags': [], u'namespace': u'android', u'creationTs': 1516216756819L, u'properties': {}, u'connected': False, u'groupPath': u'/', u'groupId': u'root', u'path': [], u'metadata': {u'api_key_id': u'XXX000XXX000XXX', u'remote_addr': u'00.00.00.00/PORT', u'mqtt_username': u'json+device', u'mqtt_timeout': 20, u'connection_start_time': u'2018-02-14T12:14:04.778Z', u'mqtt_version': 4}, u'id': u'0000001111111', u'name': u"Eric's phone"}, {u'lastUpdateTs': 1520415684605L, u'description': u'moisture sensor', u'tags': [u'france', u'lyon'], u'namespace': u'sensor', u'creationTs': 1520415684605L, u'properties': {u'model': u'MoistureSensorV3', u'manufacturer': u'miel'}, u'co…
answers question: http://stackoverflow.com/q/49150902
has comment: http://stackoverflow.com/comment/85308890
type: Answer

http://stackoverflow.com/comment/85344239
score: 0
comment on: http://stackoverflow.com/q/49168374
has text: I'm not sure how to use this command: mysql -h localhost -u root -ppassword. I'm on a mac using terminal in which I execute my python script in.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85510711
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49253616
has text: `re.sub(pattern, repl, string, count=0, flags=0)` and `re.search(pattern, string, flags=0)`

http://stackoverflow.com/q/49262993
has answer: http://stackoverflow.com/a/49263135
score: 0
tagged with: list
tagged with: loops
tagged with: eof
type: Question
has body: im trying to transform ohlcv data from kraken downloaded via ccxt library into longer candles (longer ohlcv data) import ccxt import numpy as np source_ohlcv = exchange.fetch_ohlcv("BTC/USD", '15m') n_minutes = 3 def transform_ohlcv(source_ohlcv,n_minutes): i = 0 i_len = 0 i_len_end = (n_minutes-1) timestamp = [x[0] for x in source_ohlcv] o = [x[1] for x in source_ohlcv] h = [x[2] for x in source_ohlcv] l = [x[3] for x in source_ohlcv] c = [x[4] for x in source_ohlcv] v = [x[5] for x in source_ohlcv] print(len(timestamp)) while i_len_start &lt; len(timestamp): ts = timestamp[i_len_start] op = o[i_len_start] hi = np.amax(h[i_len_start:i_len_end]) lo = np.amin(l[i_len_start:i_len_end]) cl = c[i_len_end] vo = sum(v[i_len_start:i_len_end]) results.append(ts,op,hi,lo,cl,vo) i_len_end += (n_minutes) i_len_start += (n_minutes) return results print(transform_ohlcv(source_ohlcv,n_minutes) I think that the results should be the same as the source however im getting error while parsing somewhere EOF!! so please help me find where the rogue entry is. best regards :)
type: UnansweredQuestion
answer count: 1
has title: "EOF while parsing" in Python loop
tagged with: python
tagged with: ccxt

ubuntu
tags question: http://stackoverflow.com/q/49247204
tags question: http://stackoverflow.com/q/49226394
tags question: http://stackoverflow.com/q/49145136
tags question: http://stackoverflow.com/q/49187039
tags question: http://stackoverflow.com/q/49123937
tag name: ubuntu
tags question: http://stackoverflow.com/q/49185598
tags question: http://stackoverflow.com/q/49269631
tags question: http://stackoverflow.com/q/49164347
tags question: http://stackoverflow.com/q/49205467
tags question: http://stackoverflow.com/q/49200056
tags question: http://stackoverflow.com/q/49157336
tags question: http://stackoverflow.com/q/49171782
tags question: http://stackoverflow.com/q/49158493
tags question: http://stackoverflow.com/q/49194523
tags question: http://stackoverflow.com/q/49271464
tags question: http://stackoverflow.com/q/49130679
tags question: http://stackoverflow.com/q/49247310
type: Tag
tags question: http://stackoverflow.com/q/49205801
tags question: http://stackoverflow.com/q/49263846
tags question: http://stackoverflow.com/q/49218749
tags question: http://stackoverflow.com/q/49245779

http://stackoverflow.com/q/49253503
type: Question
has answer: http://stackoverflow.com/a/49253779
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49254968
has comment: http://stackoverflow.com/comment/85510709
answer count: 3
tagged with: lxml
has comment: http://stackoverflow.com/comment/85518072
has title: Unable retrieve a list of elements using find_elements_by_xpath in selenium using python
score: 1
has answer: http://stackoverflow.com/a/49254273
tagged with: selenium
has body: I am trying to make a bot which retrieves a list of links from a website using its xapth and then making it click on all the links. The xpath looks something like this: [@class="gridicons"]/li[i]/div/ul/li/p/a and the i in the li[i] is from 1 to n, n being the number of links present. The code snippet is: urls=driver.find_elements_by_xpath('//[@id="gridicons"]/ul/li/div/ul/li/p/a') for url in urls: driver.execute_script("window.open(arguments[0]);",url.get_attribute("href")) This works perfectly fine as find_elements_by_xpath returns a list and its being stored in urls. In this case, if you take a look at the xpath, each division has only one url associated with it. Here is an image for reference. However, if there are more than one links per division, then the xpath changes to something like this: //*[@class="gridicons"]/li[i]/div/ul/li[j]/p/a where i constitutes the number of blocks and j is the number of links in each block. If I use the code: urls = driver.find_elements_by_xpath('//*[@class="gridicons"]/li/div/ul/li[1]/p/a') print(urls) in order to retrieve only the first link on each block, when i print urls, its an empty list. I can't understand why because the inspect element box is showing me the list of urls thus making the xpath valid. Here is the image.
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/85340784
has text: Are you on Python 3? You cannot pass a `map` object to `np.polyfit`, it expects an array-like object. What does this have to do with tensorflow?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49167615
score: 1

http://stackoverflow.com/comment/85415016
type: Comment
type: QuestionComment
has text: Why is `bag` a class attribute instead of an instance attribute? Do you really want all instances of the `BeadBag` class sharing and performing operation on the same dictionary?
comment on: http://stackoverflow.com/q/49204684
score: 0

http://stackoverflow.com/q/49216593
linked to: http://stackoverflow.com/q/13315922
answer count: 1
has title: Pig Latin- keep non-letters python
downvote count: 3
has comment: http://stackoverflow.com/comment/85437580
has comment: http://stackoverflow.com/comment/85437480
has comment: http://stackoverflow.com/comment/85437478
favorite count: 0
has comment: http://stackoverflow.com/comment/85437328
type: Question
has comment: http://stackoverflow.com/comment/85437432
tagged with: non-alphanumeric
has comment: http://stackoverflow.com/comment/85437523
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/85437322
has answer: http://stackoverflow.com/a/49216807
accepted answer: http://stackoverflow.com/a/49216807
tagged with: regex
has comment: http://stackoverflow.com/comment/85437249
type: AnsweredQuestion
has body: I am currently writing a pig Latin code and it requires all the non-letters to be ignored ie left in the same place of the word. For instance, Tom's would be om'sTay. So I deleted all non-alphabetic characters using: word = re.sub('[^A-Za-z]', '', word) did the pig latin code and I want to bring the non-letters back. Not sure how to bring back the non-letters to the same place of the changed word.
upvote count: 0

http://stackoverflow.com/comment/85407644
score: 0
has text: @afg229 Have you visited [the tour](https://stackoverflow.com/tour) or read some of the [help center](https://stackoverflow.com/help)? These can help you learn [how to ask a good question](https://stackoverflow.com/help/how-to-ask).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49200885

http://stackoverflow.com/q/49183656
favorite count: 0
has comment: http://stackoverflow.com/comment/85373653
type: Question
has comment: http://stackoverflow.com/comment/85374933
has body: I recently updated my matplotlib python package to version 2.2.0, and now some previously working code to save an animation does not work. Instead of saving an animation, the code freezes at a certain iteration number. It becomes unresponsive to interrupts and throws a PyEval_RestoreThread fatal error when I manage to close the command window. I am using Enthought Canopy. The code still works as normal with other versions of python and matplotlib. I can replicate the problem with this: import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np SIZE = 128 fig, ax = plt.subplots() ims = ax.imshow(np.random.rand(SIZE, SIZE)) i = 0 def update_animation(*args): global i i = i + 1 image = np.random.rand(SIZE, SIZE) ims.set_data(image) print "Iteration "+str(i) F_NAME = "anim_test.mp4" NUM_ITERS = 1000 FFwriter = animation.FFMpegWriter(fps=6, bitrate=500) anim=animation.FuncAnimation(fig,update_animation,frames=NUM_ITERS,blit=False, repeat=False, interval=200) anim.save(F_NAME, writer=FFwriter) print "saved animation to " + F_NAME Changing the bitrate parameter changed the number of the frame the program halts at. For bitrate=500, it halts around frame 46. How can I stop pyplot freezing before all frames can be saved? EDIT My system details: Python 2.7.6 64bit Enthought Canopy Windows 8 8GB RAM ffmpeg version N-79075-ga7b8a6e
has comment: http://stackoverflow.com/comment/85384148
tagged with: ffmpeg
type: UnansweredQuestion
has title: Animation freezes after a number of frames after upgrading Matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/85375375
has comment: http://stackoverflow.com/comment/85380778
has comment: http://stackoverflow.com/comment/85383990
answer count: 0
downvote count: 0
upvote count: 1
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85373365

http://stackoverflow.com/comment/85411771
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49203110
has text: @Prateek his answer is clean and simple, just wanted to add my 2 cents. Happy programming!

http://stackoverflow.com/q/49267293
has comment: http://stackoverflow.com/comment/85537998
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85538043
has body: I have a list in the following format: s = "['abc', 'xxx', '3c2', '111112', 'x']" How would I get the element "1" -- the item that comes after the [ but before the ,. So far I had: re.search(r'[.+,',s) But it is too 'greedy'. What would be the correct regex here?
possible better answer: http://stackoverflow.com/a/49267410
has comment: http://stackoverflow.com/comment/85537980
tagged with: python
has answer: http://stackoverflow.com/a/49267448
tagged with: regex
accepted answer: http://stackoverflow.com/a/49267349
has title: get first element of a list using regex
has answer: http://stackoverflow.com/a/49267349
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/49267410
score: 1

http://stackoverflow.com/a/49220286
score: 0
answers question: http://stackoverflow.com/q/49220179
type: Answer
has body: soup.find does not return a list, but a single object that is not iterable. Consider using find_all instead.

http://stackoverflow.com/q/49121732
tagged with: django
upvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49527570
tagged with: http://stackoverflow.com/tag/csv
score: 1
has body: For a web application of naturalistic data for the study of bats (http://www.dbchiro.org), I need to be able to propose a view allowing to import files from spreadsheets (csv, ods files , xls) into database. To import this data into a single table, no problem, several extensions exist (django-import-export or django-csvimport in particular). On the other hand, my need is more particular because my naturalistic data is distributed in several distinct tables (not counting the tables of dictionaries). Here is the schematic diagram: Model Place Place (a locality is a site with unique x / y coordinates as a building). 1-n Model Session (one data = one date and one inventory method by locality) 1-n Model Sighting (one data = one species per session) 1-n Model CountDetail (one data = 1 detail for a species: eg number of males, number of females, etc.) What I would like to get is the ability to import the data of a session with a single csv file that would populate the last two models: Observations (Sighting) and for each observation (each species observed), its detailed data (CountDetail). Is there one or more simple solutions (I'm doing well but I'm not a great python expert either). Otherwise, the solution that I imagined would be to load this csv data (in a specific model?) and for each import, to execute queries to populate models : Import the source file ( CSV, ods, excel) by form. Create and insert the data set in the parent table with the command "select distinct" on the fields corresponding to the observation model (species). Then for each species of the session (for ...), creation and insertion of the data in the child table (CountDetail). I am taking advice / examples / snippets :) Thank you! Fred. class Place(models.Model): id_place = models.AutoField(primary_key=True, db_index=True) [...] class Meta: verbose_name = "Localité" unique_together = ['name', 'municipality', 'type'] class Session(models.Model): id_session = models.AutoField(primary_key=True) contact =…
tagged with: python
tagged with: import
has title: django import csv in several related models
type: UnansweredQuestion
downvote count: 0
answer count: 1

http://stackoverflow.com/q/49203157
score: 1
has title: In h5py file upload, what is the difference between np.array(file[key][:]) and np.array(file[key])
tagged with: python
has body: I am currently playing around h5py file extract. When I run the script below, it seems to output the same result. Anyone knows the difference? train_dataset = h5py.File('datasets/train_happy.h5', "r") train_set_x_orig1 = np.array(train_dataset["train_set_x"][:]) train_set_x_orig2 = np.array(train_dataset["train_set_y"]) Thanks for anyone providing the input!
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85414111
downvote count: 0
answer count: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49204393
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49204393
tagged with: h5py

http://stackoverflow.com/a/49148969
has body: The usual way to handle this in python is to catch the error. try: ham = float("spam") except ValueError: print("could not parse to float")
score: 0
answers question: http://stackoverflow.com/q/49148877
type: Answer

music21
type: Tag
tag name: music21
tags question: http://stackoverflow.com/q/49224029

http://stackoverflow.com/a/69568584
has body: if you are unfamiliar with the command line , you can remove it using the anaconda dashboard
downvote count: 1
upvote count: 5
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49127834

http://stackoverflow.com/q/49235318
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: Python - How to specify an order in fnmatch()?
has answer: http://stackoverflow.com/a/49235922
tagged with: for-loop
has body: I am trying to create for loop in Python, using fnmatch to catch all desired files in directory. Due to further merging of files, I would require to run this loop based on file names (e.g. run file 20180301 through code before 20180302 etc.). Currently I simply use the following line to get files: for file_name in fnmatch.filter(os.listdir(source_dir), "Test_" + instance + "_*.csv"): Is it possible to create some sort of sorting within fnmatch? I found some options to do that with glob, but would prefer to stick with fnmatch if possible (as otherwise there will be quite some changes required within code).
upvote count: 1
tagged with: python
tagged with: sorting
accepted answer: http://stackoverflow.com/a/49235922
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/85609572
type: Comment
type: AnswerComment
has text: @BGP-python Oops, there’s a newline on the end of the filename. Use `relpath.rstrip()` instead of just `relpath`.
score: 0
comment on: http://stackoverflow.com/a/49303145

http://stackoverflow.com/comment/85251914
type: QuestionComment
has text: For example if I say `print(markdown.markdown("\n\nXXX", output_format='HTML5'))` it deletes the newlines and wraps the XXX in tags. Is this its intended behavior?
score: 0
comment on: http://stackoverflow.com/q/49123270
type: Comment

http://stackoverflow.com/comment/85294252
type: AnswerComment
comment on: http://stackoverflow.com/a/49144279
has text: @maynull ummm adding a way for fix your date :-)
type: Comment
score: 0

http://stackoverflow.com/comment/85543632
type: AnswerComment
has text: Oh, I see, it seems I misunderstood the expecting result, let me fix it
comment on: http://stackoverflow.com/a/49269944
type: Comment
score: 0

http://stackoverflow.com/comment/85285096
score: 0
type: Comment
type: QuestionComment
has text: "<form xaction". I guess you meant "<form action"
comment on: http://stackoverflow.com/q/49139506

http://stackoverflow.com/q/49125105
downvote count: 0
upvote count: 1
has body: Hi need some help in regards to python smtplib. Code works as per below import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart sender = "sender@abc.com" subject = "Test Email" to_list = ["recipient@xyz.com"] cc_list = ["sender@abc.com"] bcc_list = ["sender@abc.com"] msg = MIMEMultipart('alternative') body = " This is a test message" emailbody = MIMEText(body, 'html') msg.attach(emailbody) msg['Subject'] = subject msg['From'] = sender msg['To'] = ",".join(to_list) msg['Cc'] = ",".join(cc_list) recipients = to_list + cc_list + bcc_list s = smtplib.SMTP('localhost') s.sendmail(sender, recipients, msg.as_string()) The code works and able to receive by the recipient. However, the email is not received by cc and/or bcc, in which it sending to itself. Using Python 2.6.6 / (Red Hat 4.4.7-17)] on linux2 [EDIT] I have somewhat isolated the issue. If I use xx@abc.com as sender, xx@abc.com and xx@xyz.com will be able to receive the email. However, when I use xx@xyz.com as sender, only xx@abc.com will be able to receive the email. Could this be an issue on the SMTP server or is there any parameter that I can use in smtplib? Below is the output Note: I have replaced some info with xxxxxxxxxx :) : >>> s.sendmail(sender, toaddrs, msg.as_string()) send: 'ehlo [xxxxxxxxxx]\r\n' reply: '250-xxxxxxxxxx\r\n' reply: '250-PIPELINING\r\n' reply: '250-SIZE 10240000\r\n' reply: '250-VRFY\r\n' reply: '250-ETRN\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250-8BITMIME\r\n' reply: '250 DSN\r\n' reply: retcode (250); Msg: xxxxxxxxxx PIPELINING SIZE 10240000 VRFY ETRN ENHANCEDSTATUSCODES 8BITMIME DSN send: 'mail FROM:<xxxxxxxxxx> size=425\r\n' reply: '250 2.1.0 Ok\r\n' reply: retcode (250); Msg: 2.1.0 Ok send: 'rcpt TO:<XXXXXXXXXXXX>\r\n' reply: '354 End data with <CR><LF>.<CR><LF>\r\n' reply: retcode (354); Msg: End data with <CR><LF>.<CR><LF> data: (354, 'End data with <CR><LF>.<CR><LF>') send: 'Content-Type: multipart/alternative;\r\n\tboundary=…
has comment: http://stackoverflow.com/comment/85260204
has comment: http://stackoverflow.com/comment/85260584
has comment: http://stackoverflow.com/comment/85260832
has comment: http://stackoverflow.com/comment/85260698
score: 1
has comment: http://stackoverflow.com/comment/85259987
has comment: http://stackoverflow.com/comment/85260035
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/85260632
type: Question
has comment: http://stackoverflow.com/comment/85260793
has comment: http://stackoverflow.com/comment/85260509
tagged with: smtplib
answer count: 0
has title: sending email to self using python smtplib
has comment: http://stackoverflow.com/comment/85259369
has comment: http://stackoverflow.com/comment/85259782
type: UnansweredQuestion

http://stackoverflow.com/comment/91708039
comment on: http://stackoverflow.com/q/49252946
score: 0
type: Comment
type: QuestionComment
has text: Unrelated: in the edit queue, I came across a question that you voted on in triage. You made the wrong choice there. Please: study the help for triage really carefully, and avoid putting items into the edit queue that don't belong there. Please understand that your votes have consequences! This is the one I am talking about: https://stackoverflow.com/review/triage/20889741

http://stackoverflow.com/a/49123627
has comment: http://stackoverflow.com/comment/102541494
answers question: http://stackoverflow.com/q/49123439
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/102660344
has comment: http://stackoverflow.com/comment/102537576
has body: Python will not end if there exists a non-daemon process. By setting, daemon attribute before start() call, you can make the process daemonic. p = Process(target=func) p.daemon = True # &lt;----- p.start() print('done') NOTE: There will be no sub process finished message printed; because the main process will terminate sub-process at exit. This may not be what you want. You should do double-fork: import os import time from multiprocessing import Process def func(): if os.fork() != 0: # &lt;-- return # &lt;-- print('sub process is running') time.sleep(5) print('sub process finished') if __name__ == '__main__': p = Process(target=func) p.start() p.join() print('done')
upvote count: 15
type: Answer
accepted answer of: http://stackoverflow.com/q/49123439
score: 15

http://stackoverflow.com/comment/85286665
type: QuestionComment
has text: it's pagination. sometimes results are too large to return all at once so you need to return them bit by bit, by offsetting rows from your result you can ensure you don't return the same data twice, and this isn't specific to APIs either
score: 0
comment on: http://stackoverflow.com/q/49140663
type: Comment

google-app-engine
tags question: http://stackoverflow.com/q/49192977
tag name: google-app-engine
type: Tag
tags question: http://stackoverflow.com/q/49185508
tags question: http://stackoverflow.com/q/49243572
tags question: http://stackoverflow.com/q/49175110
tags question: http://stackoverflow.com/q/49267877
tags question: http://stackoverflow.com/q/49264652
tags question: http://stackoverflow.com/q/49136190
tags question: http://stackoverflow.com/q/49247827
tags question: http://stackoverflow.com/q/49179965
tags question: http://stackoverflow.com/q/49194575
tags question: http://stackoverflow.com/q/49136417

http://stackoverflow.com/a/49211322
answers question: http://stackoverflow.com/q/49210059
type: Answer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85433678
has comment: http://stackoverflow.com/comment/85429860
has body: Regex seems to do the trick: import re gcode = [ ';TYPE:SKIN', 'G1 F1200 X-9.914 Y-9.843 E3.36222', 'G0 F9000 X-9.843 Y-9.914', 'G1 F1200 X9.914 Y9.843 E3.65844', 'G0 F9000 X9.914 Y9.702', 'G1 F1200 X-9.702 Y-9.914 E3.95254', 'G0 F9000 X-9.560 Y-9.914', 'G1 F1200 X9.914 Y9.560 E4.24451', 'G0 F9000 X9.914 Y9.419', 'G1 F1200 X-9.419 Y-9.914 E4.53437', 'G0 F9000 X-9.277 Y-9.914', 'G1 F1200 X9.914 Y9.277 E4.82211', 'G0 F9000 X9.914 Y9.136', 'G1 F1200 X-9.136 Y-9.914 E5.10772', 'G0 F9000 X-8.995 Y-9.914', 'G1 F1200 X9.914 Y8.995 E5.39123', 'G0 F9000 X9.914 Y8.853', 'G1 F1200 X-8.853 Y-9.914 E5.67260' ] for line in gcode: coord = re.findall(r'[XY]-\d.\d\d\d', line) if coord: print("{} - {}".format(coord[0], coord[1])) Result: X-9.914 - Y-9.843 X-9.843 - Y-9.914 X-9.702 - Y-9.914 X-9.560 - Y-9.914 X-9.419 - Y-9.914 X-9.277 - Y-9.914 X-9.136 - Y-9.914 X-8.995 - Y-9.914 X-8.853 - Y-9.914 EDIT: Please try the following. I've integrated your code with the sample I provided and made some adjustments: import re with open('PI_25mm_cube.gcode') as gcode: for line in gcode: line = line.strip() coord = re.findall(r'[XY].?\d+.\d+', line) if coord: print("{} - {}".format(coord[0], coord[1])) By replacing open with with, it prevents you from forgetting to close() the file, and reduces the risk of causing any memory issues, as I understand it. As its not clear whether your code will be used on other gcode files, my initial regex may not be suitable. Using Cura I created a gcode file and reviewed the coordinates provided. Based on this information you may find the pattern '[XY].?\d+.\d+' more useful. Regex101 is great website for testing these

http://stackoverflow.com/q/49215956
tagged with: python
has answer: http://stackoverflow.com/a/49216356
type: UnansweredQuestion
answer count: 1
downvote count: 0
upvote count: 1
has title: How can I make a pandas TimedeltaIndex act as a denominator?
has body: I am trying to divide a pandas (0.22.0) Timedelta by a TimedeltaIndex to obtain a Float64Index of fractional values. For example: &gt;&gt;&gt; td_index = pd.TimedeltaIndex(['1 days', '2 days', '3 days']) &gt;&gt;&gt; td_index TimedeltaIndex(['1 days', '2 days', '3 days'], dtype='timedelta64[ns]', freq=None) &gt;&gt;&gt; td = pd.Timedelta('1D') &gt;&gt;&gt; td Timedelta('1 days 00:00:00') &gt;&gt;&gt; td_index / td # expected, like division Float64Index([1.0, 2.0, 3.0], dtype='float64') &gt;&gt;&gt; td / td_index # unexpected, why the same as above? Float64Index([1.0, 2.0, 3.0], dtype='float64') &gt;&gt;&gt; td.total_seconds() / td_index.total_seconds() # this works in a pinch Float64Index([1.0, 0.5, 0.3333333333333333], dtype='float64' It seems that the former of these, i.e., the one with the Timedelta in the denominator, can be thought of as "frequency conversion", but I am unsure about why putting the index in the denominator would have the same behavior, especially when this behavior is unlike that exhibited by other indexes. For instance, this doesn't seem to apply to using Float64Index directly: &gt;&gt;&gt; pd.Float64Index([1, 2, 3]) / 1) Float64Index([1.0, 2.0, 3.0], dtype='float64') &gt;&gt;&gt; 1 / pd.Float64Index([1, 2, 3])) Float64Index([1.0, 0.5, 0.3333333333333333], dtype='float64') # the behavior I want Why do pandas Timedeltas and TimedeltaIndexes act like this? Is there any way to achieve float-like division with a TimedeltaIndex and Timedelta, i.e., without first converting to a different representation (like with .total_seconds())?
favorite count: 0
type: Question
tagged with: pandas
score: 1

http://stackoverflow.com/comment/85458688
type: QuestionComment
has text: Your second code block says `esponse = urllib2.urlopen`, is that just a typo?
comment on: http://stackoverflow.com/q/49223186
score: 0
type: Comment

http://stackoverflow.com/comment/86161575
type: QuestionComment
comment on: http://stackoverflow.com/q/49153530
score: 0
has text: @YanKhonski Are you now avoiding the "Got timeout reading communication packets"? If so, please up vote my comment of Mar 9. Thanks
type: Comment

http://stackoverflow.com/a/55372694
score: 0
has body: The issue is with regex not escaping the special characters in your search term. To get this to work, simply change your statement to the following: import re regex = re.escape("???0") re.findall(regex,data['cc_flags']) data['cc_flags'] should be a string, not a list.
type: Answer
answers question: http://stackoverflow.com/q/49176643

http://stackoverflow.com/q/49131111
accepted answer: http://stackoverflow.com/a/49141685
has title: Flask-SocketIO connection gets interrupted when code execution takes too long
tagged with: socket.io
type: Question
tagged with: websocket
has body: Hi my conversion finished stops arriving on the client side once the code execution takes too long. This works: @socketio.on('nifti_conversion') def handle_message(message): elehelper.send_status({'code': 201, 'message':'conversion started!'}) sleep(5) elehelper.send_status({'code': 202, 'message':'conversion finished!'}) while the following fails: @socketio.on('nifti_conversion') def handle_message(message): elehelper.send_status({'code': 201, 'message':'conversion started!'}) sleep(120) elehelper.send_status({'code': 202, 'message':'conversion finished!'}) also note that this works: @socketio.on('nifti_conversion') def handle_message(message): elehelper.send_status({'code': 201, 'message':'conversion started!'}) socketio.sleep(120) elehelper.send_status({'code': 202, 'message':'conversion finished!'}) First I expected some kind of timeout but the disconnect happened after varying times..so far I observed 90, 94, 100, 104 seconds. On the client side the console looks like following. Working 5 seconds case: Failing 120 seconds case:
tagged with: python
tagged with: flask
type: AnsweredQuestion
score: 0
tagged with: flask-socketio
answer count: 1
has answer: http://stackoverflow.com/a/49141685

http://stackoverflow.com/q/49134152
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/49135112
linked to: http://stackoverflow.com/q/47178371
has title: Finding implementation of methods in Tensorflow
has answer: http://stackoverflow.com/a/49135112
downvote count: 0
answer count: 1
upvote count: 1
has body: I want to change a bit minimization optimizers like AdadeltaOptimizer, which is used in Tensorflow. I got the license but there is no code in lib, only reference, so how can I find the implementation? Here is Adadelta example of API: @tf_export("train.AdadeltaOptimizer") class AdadeltaOptimizer(optimizer.Optimizer) Optimizer that implements the Adadelta algorithm. See [M. D. Zeiler](http://arxiv.org/abs/1212.5701) ([pdf] (http://arxiv.org/pdf/1212.5701v1.pdf))
tagged with: tensorflow
favorite count: 0
tagged with: optimization
type: AnsweredQuestion
tagged with: gradient-descent
score: 1

http://stackoverflow.com/q/49149278
has comment: http://stackoverflow.com/comment/85307677
has comment: http://stackoverflow.com/comment/85307864
has comment: http://stackoverflow.com/comment/85307506
has comment: http://stackoverflow.com/comment/85307346
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49152055
has comment: http://stackoverflow.com/comment/85306588
tagged with: python
has answer: http://stackoverflow.com/a/49154315
has comment: http://stackoverflow.com/comment/85307561
has comment: http://stackoverflow.com/comment/85308004
has comment: http://stackoverflow.com/comment/85308120
has comment: http://stackoverflow.com/comment/85307613
score: 0
has body: I am using MLPClassifer example from scikit-learn The code for training: from sklearn.neural_network import MLPClassifier X = [[0., 0.], [1., 1.]] y = [0, 1] clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1) clf.fit(X, y) At the predict step, we use test data [2., 2.], [-1., -2.] in clf.predict([[2., 2.], [-1., -2.]]). The output of this function is array([1, 0]) As we observe, the test data [2.,2.] is not in the train dataset we passed. Still, we got the closest match as label 1. What i am trying to find is if the test data i supplied is not in the train dataset, i should print a message to user that data is not valid instead of telling him the wrong label as 1. For instance, in knn classification, i have kneighbours function which tells the distance of my closest neighbours to the test data i supplied in a 0 to 1 scale. So, i could easily eliminate the test data samples who are highly distant from my train data samples by keeping threshold at 0.6 or 0.7. Is there any criteria/threshold like this i could do with MLPClassifier or with any one of Incremental Classifiers mentioned here which can restrict my test samples if not present in train dataset ?
has comment: http://stackoverflow.com/comment/85303450
has comment: http://stackoverflow.com/comment/85307342
answer count: 2
has title: MLPClassifier threshold factor to eliminate test samples that are not in match with train data
has comment: http://stackoverflow.com/comment/85307922
has comment: http://stackoverflow.com/comment/85303563
has comment: http://stackoverflow.com/comment/85307465
tagged with: machine-learning
tagged with: scikit-learn
type: Question

http://stackoverflow.com/a/49267270
has comment: http://stackoverflow.com/comment/86109644
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49267203
type: AcceptedAnswer
has body: The spaces aren't the issue, your ampersand is the problem. Ampersand is the separator between the different parameters, which are name=value pairs. Parsing your query string results in: A name of public_location_description with a value of =SW%206th%20 and %20Salmon with no value. Escape your ampersand by replacing it with %26 (and remove the redundant '=') to get a url of: http://localhost:8000/api/passenger-census/?public_location_description=SW%206th%20%26%20Salmon and try it again
answers question: http://stackoverflow.com/q/49267203
has comment: http://stackoverflow.com/comment/85914082
score: 2
downvote count: 0
type: Answer

http://stackoverflow.com/a/49251471
type: Answer
answers question: http://stackoverflow.com/q/49251312
upvote count: 1
has body: You want a numpy.array not a numpy.matrix. The np.matrix docs is a 2D data structure, np.array is an nd dimensional structure. If you look at B.shape immediately after creating you will discover that it is (1,2), not (2,) as you intended. B.A.reshape(2,) # or B.A1 will give you a np.array that is 1-dimensional. NumPy arrays ARE NOT equivalent to NumPy matrices, the meaning of operations is different between the two, for instance * is a dot product for matrix but an element wise product for an array.
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85540136
accepted answer of: http://stackoverflow.com/q/49251312

http://stackoverflow.com/comment/85360611
type: AnswerComment
comment on: http://stackoverflow.com/a/49177596
score: 1
has text: Ridiculous as the question may be, I really think this is the right answer.
type: Comment

http://stackoverflow.com/comment/85529232
comment on: http://stackoverflow.com/q/49262574
has text: @chrisz solutions using `awk` or `sed` were also welcome, but @Wiktor nailed it already. Could you please post your comment as an answer so I can accept it?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49196077
accepted answer of: http://stackoverflow.com/q/49143066
answers question: http://stackoverflow.com/q/49143066
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85406308
has body: There's no public interface to the information you're interested in. In your case, imap_unordered will return a IMapUnorderedIterator but this return type is not guaranteed. In some cases, a generator is returned instead (and the documentation promises nothing beyond an iterator). In the case where IMapUnorderedIterator is returned, a private attribute _items holds all elements that are available but haven't yet been iterated over. So, accessing this private attribute, you can inspect len(result_iter._items) to find the information you want (obviously it is only correct at most at the instant of inspection since the pool may add new results at any time, but presumably that's still useful to you). You may want to consider contributing a patch to the multiprocessing library which exposes this information under a public interface.
type: Answer
has comment: http://stackoverflow.com/comment/85406108

http://stackoverflow.com/a/49186715
has comment: http://stackoverflow.com/comment/85409824
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85410103
accepted answer of: http://stackoverflow.com/q/49159493
answers question: http://stackoverflow.com/q/49159493
has body: If you need to replicate ping exactly in Python, you would need administrator privileges to send ICMP packets to a host. You could instead rely on TCP packets and tap the http port. That does not require admin privileges. Neither is it quite as accurate but it is an more accurate portrayal of web browsing ability. Simplifying this TCP ping code: import sys import socket import time import signal from timeit import default_timer as timer host = "google.com" port = 80 # Default to 10000 connections max maxCount = 10000 count = 0 # Pass/Fail counters passed = 0 failed = 0 def getResults(): """ Summarize Results """ lRate = 0 if failed != 0: lRate = failed / (count) * 100 lRate = "%.2f" % lRate print("\nTCP Ping Results: Connections (Total/Pass/Fail): [{:}/{:}/{:}] (Failed: {:}%)".format((count), passed, failed, str(lRate))) def signal_handler(signal, frame): """ Catch Ctrl-C and Exit """ getResults() sys.exit(0) # Register SIGINT Handler signal.signal(signal.SIGINT, signal_handler) # Loop while less than max count or until Ctrl-C caught while count &lt; maxCount: # Increment Counter count += 1 success = False # New Socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 1sec Timeout s.settimeout(1) # Start a timer s_start = timer() # Try to Connect try: s.connect((host, int(port))) s.shutdown(socket.SHUT_RD) success = True # Connection Timed Out except socket.timeout: print("Connection timed out!") failed += 1 except OSError as e: print("OS Error:", e) failed += 1 # Stop Timer s_stop = timer() s_runtime = "%.2f" % (1000 * (s_stop - s_start)) if success: print("Connected to %s[%s]: tcp_seq=%s time=%s ms" % (host, port, (count-1), s_runtime)) passed += 1 # Sleep for 1sec if count &lt; maxCount: time.sleep(1) # Output Results if maxCount reached getResults() Once you can create a 'ping' you could encapsulate the result of each time / ping result into an object stream to display as you wish.
type: AcceptedAnswer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49218215
has comment: http://stackoverflow.com/comment/85440522
has comment: http://stackoverflow.com/comment/85440369
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/49218332
has comment: http://stackoverflow.com/comment/85440467
accepted answer: http://stackoverflow.com/a/49218332
answer count: 2
has comment: http://stackoverflow.com/comment/85440353
downvote count: 0
linked to: http://stackoverflow.com/q/1132941
has answer: http://stackoverflow.com/a/49218297
possible better answer: http://stackoverflow.com/a/49218297
has comment: http://stackoverflow.com/comment/85440237
has comment: http://stackoverflow.com/comment/85440240
has comment: http://stackoverflow.com/comment/85440238
has comment: http://stackoverflow.com/comment/85440268
has comment: http://stackoverflow.com/comment/85440235
favorite count: 0
has comment: http://stackoverflow.com/comment/85440259
type: Question
has comment: http://stackoverflow.com/comment/85440508
tagged with: python-3.x
score: 3
has comment: http://stackoverflow.com/comment/85440215
has title: Functions with mutable default values
tagged with: python
has comment: http://stackoverflow.com/comment/85440316
has body: I am confused about python's evaluation of default function arguments. As mentioned in the documentation (https://docs.python.org/3.6/tutorial/controlflow.html#more-on-defining-functions) def f(a, L=[]): L.append(a) return L print(f(1)) print(f(2)) print(f(3)) results in [1] [1,2] [1,2,3] But def f(a, L=[]): L = L+[a] return L print(f(1)) print(f(2)) print(f(3)) results in [1] [2] [3] If L is evaluated only once, shouldn't both the function return the same result? Can someone explain what am I missing here? This question is different than "Least Astonishment" and the Mutable Default Argument. That question is questioning the design choice while here I am trying to understand a specific case.

http://stackoverflow.com/comment/85551401
comment on: http://stackoverflow.com/a/49274421
score: 0
has text: This is so much better than what I had started doing, thanks a lot!
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49216987
has comment: http://stackoverflow.com/comment/85438141
has comment: http://stackoverflow.com/comment/85438299
has answer: http://stackoverflow.com/a/67814862
has answer: http://stackoverflow.com/a/65608317
possible better answer: http://stackoverflow.com/a/49828148
has answer: http://stackoverflow.com/a/59854437
type: AnsweredQuestion
tagged with: python-3.x
score: 5
has answer: http://stackoverflow.com/a/49828148
has title: Python 3: Solving arrayChange in CodeFights
downvote count: 0
answer count: 7
has comment: http://stackoverflow.com/comment/85438157
has answer: http://stackoverflow.com/a/49972418
has comment: http://stackoverflow.com/comment/85438394
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/67106250
has comment: http://stackoverflow.com/comment/85438055
has answer: http://stackoverflow.com/a/69593640
upvote count: 5
accepted answer: http://stackoverflow.com/a/49972418
has comment: http://stackoverflow.com/comment/85438286
has body: I am currently working on the arrayChange level of Code Fights Arcade. This is the objective: You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input. Example For inputArray = [1, 1, 1], the output should be arrayChange(inputArray) = 3. I have written this code in Python 3: def arrayChange(inputArray): original = inputArray[:] count = 0 if len(set(inputArray)) == 1: return ((len(inputArray)-1)**2 + (len(inputArray)-1)) / 2 elif sorted(inputArray) == inputArray: return 0 for index, value in enumerate(inputArray): if index != len(inputArray) - 1 and value &gt; inputArray[index+1]: inputArray[index+1] += abs(inputArray[index+1] - value) + 1 elif index != len(inputArray) - 1 and value == inputArray[index+1]: inputArray[index+1] += 1 elif index == len(inputArray) - 1 and value &lt; inputArray[index-1]: inputArray[index] += inputArray[index-1] - value + 1 print (inputArray) for index, value in enumerate(inputArray): count = count + abs(value - original[index]) return count It passes all the non-hidden tests but fails the 7th hidden test. Can someone please help me figure out what bug my code has? Thank you so much in advance!
tagged with: python
has comment: http://stackoverflow.com/comment/85438185

http://stackoverflow.com/q/49211097
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49212836
has answer: http://stackoverflow.com/a/49212836
tagged with: http://stackoverflow.com/tag/json
answer count: 1
tagged with: web-scraping
type: Question
has body: I'm trying to scrape a site, when I run the following code without region_id=[any number from one to 32] I get a [500], but if I set region_id=1 I'll get only a first page by default (on the url it is pagina=&), pages are up to 500; is there a command or parameter for retrieving every page (every possible value of pagina=), avoiding for loops? import requests url = "http://www.enciclovida.mx/explora-por-region/especies-por-grupo?utf8=%E2%9C%93&grupo_id=Plantas&region_id=&parent_id=&pagina=&nombre=" resp = requests.get(url, headers={'User-Agent':'Mozilla/5.0'}) data = resp.json()
has title: Scraping json content from a site ordered in pages
tagged with: python
has comment: http://stackoverflow.com/comment/85428094

http://stackoverflow.com/comment/85550066
comment on: http://stackoverflow.com/a/49272940
type: Comment
has text: Yeah...now it works fine but I want that the code should support urls without https:// or http://..... Anyways thanks for helping
score: 0
type: AnswerComment

http://stackoverflow.com/a/49223310
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85451490
score: 3
has comment: http://stackoverflow.com/comment/85451716
type: Answer
has comment: http://stackoverflow.com/comment/85452184
accepted answer of: http://stackoverflow.com/q/49197366
has body: I add here another answer, suitable to the added code. The answer is still np.fft.fft2(). Here's an example. I modified the code slightly. To verify that we need fft2 I discarded one of the blobs, and then we know that a single Gaussian blob should transform into a Gaussian blob (with a certain phase, that's not shown when plotting absolute value). I also decreased the standard deviation so that the frequency response will widen a little. Code: import numpy as np import matplotlib.pyplot as plt x, y = np.meshgrid(np.linspace(-1,1,100), np.linspace(-1,1,100)) d = np.sqrt(x**2+y**2) sigma, mu = .1, 0.0 g1 = np.exp(-( (d-mu)**2 / ( 2.0 * sigma**2 ) ) ) N = 300 positions = [ [150,100] ]#, [150,200] ] sz2 = [int(x/2) for x in g1.shape] F_2D = np.zeros([N,N]) for x0,y0 in positions: F_2D[ x0-sz2[0]: x0+sz2[0], y0-sz2[1]:y0+sz2[1] ] = g1 + 1j*0. result = np.fft.fftshift(np.fft.fft2(F_2D)) plt.subplot(211); plt.imshow(F_2D) plt.subplot(212); plt.imshow(np.absolute(result)) plt.title('$\sigma$=.1') plt.show() Result: To get back to the original problem, we need only change positions = [ [150,100] , [150,200] ] and sigma=.35 instead of sigma=.1.
upvote count: 3
answers question: http://stackoverflow.com/q/49197366
downvote count: 0
has comment: http://stackoverflow.com/comment/85451337

http://stackoverflow.com/comment/85411436
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49202690
has text: There's more than one python module that attempts to work with dbf files -- which one are you using?
type: Comment

http://stackoverflow.com/q/49254249
score: 1
accepted answer: http://stackoverflow.com/a/49276774
answer count: 1
tagged with: keras
tagged with: tensorflow
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49276774
has title: How to One input and Three output LSTM tensorflow
tagged with: python
tagged with: recurrent-neural-network
tagged with: lstm
type: Question
downvote count: 0
has body: I am trying to learn LSTM and i have one confusion , if i have a list of words like : vocabulary=['hello','how','are','you','tell','me','something','about','yourself'] Now i want to give one input : ex : input_data = ['hello'] and i want it should predict next three words : ex : output_data = ['how','are','you'] So i want to train LSTM by choosing randomly 4 words and then chunk that list of words as 1 as input and rest 3 as output. Let's take simple one example : ex : input_data = ['hello'] ex : output_data = ['how','are','you'] after converting them into one hot : final_input=[] for i in x_data: matrix = [0] * len(main_vocabulary) matrix[main_vocabulary.index(i)]=1 final_input.append(matrix) output=[main_vocabulary.index(i) for i in y_data] print(final_input) print(output) : [[1, 0, 0, 0, 0, 0, 0, 0, 0]] [1, 2, 3] Now my confusion is how to feed this format to LSTM ? Because i have read LSTM input and output vector shape should be same , is it True ? input_placeholder=tf.placeholder(tf.float32,[None,1,9]) output_placeholder=tf.placeholder(tf.int32,[None,3]) But i don't think this is correct , How to feed please suggest. And what would be number of num_units in rnn.BasicLSTMCell(num_units=?,state_is_tuple=True) what i am thinking yet that num_units should be same as column of data so here it should be 9 .
upvote count: 1

http://stackoverflow.com/q/49230967
accepted answer: http://stackoverflow.com/a/49231644
upvote count: 2
has title: 3D Line Drawing with selected point
tagged with: 3d
tagged with: line-drawing
tagged with: python
has comment: http://stackoverflow.com/comment/85465442
tagged with: interactive
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/85465801
tagged with: matplotlib
answer count: 1
downvote count: 0
has body: I am using matplotlib and I want to select point my 3D scatter graph and connect them with a line.I can read (X,Y,Z) values my but I can't find how can i connect with a line.Here is my code. Thanks in advance import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D #Coordinates of Grid Lines X_Grid=[0,4] #Joint Points X Y_Grid=[0,5] #Joint Points Y Z_Grid=[0,3,5]#Joint Points Z fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_xlabel('X Axis') ax.set_ylabel('Y Axis') ax.set_zlabel('Z Axis') ax.set_title('Select Point') X,Y,Z=list(),list(),list() for i in X_Grid: for j in Y_Grid: for k in Z_Grid: X.append(i) Y.append(j) Z.append(k) ax.scatter(X,Y,Z,marker="*",c="green",picker=5) def onpick(event): ind = event.ind[0] x, y, z = event.artist._offsets3d print((x[ind],y[ind],z[ind])) fig.canvas.mpl_connect('pick_event', onpick) plt.show()
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49231644

http://stackoverflow.com/comment/85582564
type: QuestionComment
has text: You're clearly thinking of this as a graph problem. But there is no graph in your question or comments. We need a [mcve].
type: Comment
comment on: http://stackoverflow.com/q/49271359
score: 0

http://stackoverflow.com/q/49205798
tagged with: http://stackoverflow.com/tag/csv
score: 1
tagged with: datetime
tagged with: python
type: Question
accepted answer: http://stackoverflow.com/a/49205848
has body: Pulling dates from a csv in Timestamp format (ex. 1504159200). I'm plugging these into a script suited for Y-m-d format. [The code is a massive LSTM script so hopefully the original lines and what I tried on them will suffice] startDate = 1504159200 endDate = 1519974000 Original lines without modifying... sd = datetime.strptime(startDate, '%Y-%m-%d') ed = datetime.strptime(endDate, '%Y-%m-%d') Traceback (most recent call last): File "stocks.py", line 91, in &lt;module&gt; p, n = Main(['last_vix_92_18.csv', '1504159200', '1519974000', 'D']) File "stocks.py", line 78, in Main P = sp.PredictDate(args[1], args[2], predPrd) File "/home/eagle/predict/dragon/pythonml-master/Stocks/StockPredictor.py", line 282, in PredictDate ts = DateRange(startDate, endDate, period)[::-1] File "/home/eagle/predict/dragon/pythonml-master/Stocks/StockPredictor.py", line 30, in DateRange sd = datetime.strptime(startDate, '%Y-%m-%d') File "/usr/lib/python3.5/_strptime.py", line 510, in _strptime_datetime tt, fraction = _strptime(data_string, format) File "/usr/lib/python3.5/_strptime.py", line 343, in _strptime (data_string, format)) ValueError: time data '1504159200' does not match format '%Y-%m-%d' I've tried modifying the code thusly with the following error below. sd = datetime(int(startDate)).timestamp() ed = datetime(int(endDate)).timestamp() Traceback (most recent call last): File "stocks.py", line 91, in &lt;module&gt; p, n = Main(['last_vix_92_18.csv', '1504159200', '1519974000', 'D']) File "stocks.py", line 78, in Main P = sp.PredictDate(args[1], args[2], predPrd) File "/home/eagle/predict/dragon/pythonml-master/Stocks/StockPredictor.py", line 284, in PredictDate ts = DateRange(startDate, endDate, period)[::-1] File "/home/eagle/predict/dragon/pythonml-master/Stocks/StockPredictor.py", line 31, in DateRange sd = datetime(int(startDate)).timestamp() TypeError: Required argument 'month' (pos 2) not found
has title: Trying to Modify a Script to Take Timestamp Date Format Instead of %Y-%m-%d Format [Python]
has answer: http://stackoverflow.com/a/49205848
downvote count: 0
answer count: 1
upvote count: 1
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/q/49194895
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85394562
answer count: 1
tagged with: python
has title: Map list of elements to category of element in pandas?
has answer: http://stackoverflow.com/a/49195030
favorite count: 0
score: 2
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85399120
downvote count: 0
tagged with: pandas
tagged with: dataframe
has body: I have been googling a lot, but I still can't find a quick way to do so. Say I have a column in my csv file: 1. C.Ronald 2. Conor McGregor 3. Lionel Messi 4. LeBron James 5. Derrick Rose 6. Tom Brady 7. ... 8. ... and so on, I want to replace those name as the following three categories through python: 1. Soccer player 2. MMA fighter 3. Soccer player 4. NBA player 5. NBA player 6. NFL plaer 7. ... 8. ... How can I replace 'C.Ronald','Lionel Messi' and those soccer player's name, in to a class at once, but not one by one, since I have a long column.
type: Question
upvote count: 2

http://stackoverflow.com/q/49278353
has body: I am trying to write a code for squaring the user input number in Python. I've created function my1() ... What I want to do is to make Python to take user input of a number and square it but if user added no value it gives a print statement and by default give the square of a default number for e.g 2 Here is what I've tried so far def my1(a=4): if my1() is None: print('You have not entered anything') else: b=a**2 print (b) my1(input("Enter a Number"))
has answer: http://stackoverflow.com/a/49278485
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49278537
downvote count: 0
linked to: http://stackoverflow.com/q/1549801
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/49278485
has title: Handling input data quality with checks & default value
favorite count: 0
has comment: http://stackoverflow.com/comment/85559253
has answer: http://stackoverflow.com/a/49278694
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49278512
has answer: http://stackoverflow.com/a/49278537
has comment: http://stackoverflow.com/comment/85559251
has comment: http://stackoverflow.com/comment/85559306
tagged with: python

http://stackoverflow.com/a/49153041
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49146849
has body: As noted by Alex, the website requests the data from http://www.etf.com/etf-finder-funds-api//-aum/0/3000/1, which checks the Referer header to see if you're allowed to see it. However, Alex is wrong in saying that you're unable to change the header. It is in fact very easy to send custom headers using requests: &gt;&gt;&gt; r = requests.get('http://www.etf.com/etf-finder-funds-api//-aum/0/3000/1', headers={'Referer': 'http://www.etf.com/etfanalytics/etf-finder'}) &gt;&gt;&gt; data = r.json() &gt;&gt;&gt; len(data) 2166 At this point, data is a dict containing all the data you need, pandas probably has a simple way of loading it into a dataframe.
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49146849

http://stackoverflow.com/comment/85443653
type: AnswerComment
comment on: http://stackoverflow.com/a/49208471
has text: using this df = pd.DataFrame(reduce(lambda x, y: x + y, list(data.values()])) I get SyntaxError: invalid syntax
type: Comment
score: 0

http://stackoverflow.com/a/49193391
type: AcceptedAnswer
downvote count: 0
has body: Two approaches leveraging broadcasting could be suggested. Approach #1 : d = np.sqrt(np.diag(A)) B = A/d[:,None] B /= d Approach #2 : B = A/(d[:,None]*d) # d same as used in Approach #1 Approach #1 has lesser memory overhead and as such I think would be faster.
score: 4
answers question: http://stackoverflow.com/q/49193238
type: Answer
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49193238

http://stackoverflow.com/comment/85439500
comment on: http://stackoverflow.com/a/49217324
type: Comment
score: 0
type: AnswerComment
has text: @SeanBreckenridge, the methods `findAll()`, `getText()` etc are **not** deprecated. bs4 has backward compatibility with both bs2 and bs3. In the [bs4 source code](https://github.com/getanewsletter/BeautifulSoup4/blob/master/bs4/element.py) there are lines like this -> `findAll = find_all # BS3`

http://stackoverflow.com/a/49273942
has comment: http://stackoverflow.com/comment/85551467
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85588274
has comment: http://stackoverflow.com/comment/85551769
has comment: http://stackoverflow.com/comment/85588361
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85588368
has comment: http://stackoverflow.com/comment/85551073
type: Answer
has body: I think you can use: first filter by isin and loc groupby and aggregate by agg with tuples of new columns names and functions add Percentage by divide by div and sum last if necessary sort_values by rfq_qty df_Done = df.loc[df['state'].isin(['Done', 'Tied Done']), ['Channel','state','rfq_qty']] #if want filter all values contains Done #df_Done = df[df['state'].str.contains('Done')] #if necessary filter out Channel == 0 #mask = (df['Channel'] != 0) &amp; df['state'].isin(['Done', 'Tied Done']) #df_Done = df.loc[mask, ['Channel','state','rfq_qty']] d = {('rfq_qty', 'sum'), ('Done_Trades','size')} df = df_Done.groupby('Channel')['rfq_qty'].agg(d).reset_index() df['Percentage'] = df['rfq_qty'].div(df['rfq_qty'].sum()) df = df.sort_values('rfq_qty') print (df) Channel Done_Trades rfq_qty Percentage 0 A 1 10 0.125 1 B 3 30 0.375 2 C 4 40 0.500
accepted answer of: http://stackoverflow.com/q/49272452
has comment: http://stackoverflow.com/comment/85552341
has comment: http://stackoverflow.com/comment/85551052
answers question: http://stackoverflow.com/q/49272452
has comment: http://stackoverflow.com/comment/85551601
has comment: http://stackoverflow.com/comment/85552485

http://stackoverflow.com/a/49189220
has body: This is only loosely related to Python, but more on HTTP sessions. HTTP was originaly designed as a non connected protocol. It was aimed at sending requests to various servers and collect elements. The need for tracking clients to allow flows of related requests was addressed by cookies. That's the reason why nowadays most of session implementations rely on cookies. The problems is that browsers normally share cookies among all of their windows. So it a session is cookie based, different windows of same browser will share it however it was established: that's what you are experiencing. In that case, you need to use different browsers to have different sessions from same client machine. But sessions can also be based on URL rewriting. Instead of being transported in a cookie, the session id it passed as a request parameter. I used to be more common in old days where many users disabled cookies, but as you can now hardly consult a website with disabled cookies, it is seldom used. But it does allow a single browser to have different sessions to the same server in different windows. Unfortunately,I do not know whether it is supported by flask.
type: Answer
has comment: http://stackoverflow.com/comment/85390317
score: 4
accepted answer of: http://stackoverflow.com/q/49188956
upvote count: 4
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49188956
has comment: http://stackoverflow.com/comment/85383778

http://stackoverflow.com/q/49178622
duplicate of: http://stackoverflow.com/q/41213346
favorite count: 0
has title: Adding key/legend to histogram
type: Question
has body: I have not been able to add a legend to my histogram, created using matplotlib.pyplot. Would appreciate some help/advice. The below dataset is junk data, but is an accurate example of the situation, two datasets, both in the same dataframe, seperated by a filter on a column. import numpy as np import matplotlib.pyplot as plt import pandas as pd import math import pyodbc import re data = [{ 'uid':1,'Region':'nebraska', 'metric1':24}, { 'uid':2,'Region':'nebraska', 'metric1':12}, { 'uid':3,'Region':'nebraska', 'metric1':23}, { 'uid':4,'Region':'nebraska', 'metric1':12}, { 'uid':1,'Region':'nebraska', 'metric1':24}, { 'uid':2,'Region':'nebraska', 'metric1':12}, { 'uid':3,'Region':'nebraska', 'metric1':23}, { 'uid':4,'Region':'nebraska', 'metric1':12}, { 'uid':1,'Region':'nebraska', 'metric1':24}, { 'uid':2,'Region':'nebraska', 'metric1':12}, { 'uid':3,'Region':'nebraska', 'metric1':23}, { 'uid':4,'Region':'nebraska', 'metric1':12}, { 'uid':1,'Region':'nebraska', 'metric1':24}, { 'uid':2,'Region':'nebraska', 'metric1':12}, { 'uid':3,'Region':'nebraska', 'metric1':23}, { 'uid':4,'Region':'nebraska', 'metric1':12}, { 'uid':29,'Region':'colorado', 'metric1':14}, { 'uid':30,'Region':'colorado', 'metric1':45}, { 'uid':30,'Region':'colorado', 'metric1':45}, { 'uid':30,'Region':'colorado', 'metric1':45}, { 'uid':31,'Region':'colorado', 'metric1':65}, { 'uid':32,'Region':'colorado', 'metric1':50} ] testDataset = pd.DataFrame(data) b = np.arange(0,100, 50) plt.hist(testDataset[testDataset['Region'] == 'nebraska']['metric1'], b,color = 'red') plt.xticks(rotation=90) plt.xticks(np.arange(0, 100, 10)) plt.yticks(np.arange(0, 100, 10)) plt.grid(zorder=0) plt.hist(testDataset[testDataset['Region'] == 'colorado']['metric1'], b,color = 'blue') plt.show()
type: UnansweredQuestion
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/49178768
upvote count: 3
score: 3
answer count: 2
downvote count: 0
linked to: http://stackoverflow.com/q/41213346
has answer: http://stackoverflow.com/a/49178771

http://stackoverflow.com/comment/85458829
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49227541
has text: You might want to try writing the simpler recursive version, without an accumulator, and then try inverting it to this version.
type: Comment

http://stackoverflow.com/comment/85266655
type: QuestionComment
score: 0
has text: Appreciate that. Wrote an answer.
type: Comment
comment on: http://stackoverflow.com/q/49130834

http://stackoverflow.com/a/49190039
answers question: http://stackoverflow.com/q/49189175
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49189175
score: 2
type: Answer
has comment: http://stackoverflow.com/comment/86818139
has body: You can use shift with groupby to create successors for each id and hence create a column representing sequences. Then, you can simply employ pd.value_counts within groups to count the number of sequences, as follows: Create data df = pd.DataFrame({'id': [1, 1, 1, 1, 2, 2, 2, 2], 'Act': ['A', 'B', 'A', 'A', 'B', 'B', 'A', 'B']}) print(df) Act id 0 A 1 1 B 1 2 A 1 3 A 1 4 B 2 5 B 2 6 A 2 7 B 2 Sequence counts within groups # shift `Act` within id groups to get successor df["Act Shifted"] = df.groupby("id").shift(-1) # concatenate predeccesor and successor to get sequence column df["Seq"] = df["Act"].str.cat(df["Act Shifted"], " - ") print(df) Act id Act Shifted Seq 0 A 1 B A - B 1 B 1 A B - A 2 A 1 A A - A 3 A 1 NaN NaN 4 B 2 B B - B 5 B 2 A B - A 6 A 2 B A - B 7 B 2 NaN NaN Now simply count within groups: # group by id and count sequences df.groupby("id")["Seq"].apply(pd.value_counts) id 1 A - A 1 A - B 1 B - A 1 2 B - B 1 A - B 1 B - A 1 Name: Seq, dtype: int64 Overall sequence counts If you want to get sequence counts irrespective of id, remove the groupby: df["Seq"].value_counts() A - B 2 B - A 2 B - B 1 A - A 1 Name: Seq, dtype: int64
upvote count: 2

http://stackoverflow.com/q/49216855
possible better answer: http://stackoverflow.com/a/49216925
upvote count: 2
linked to: http://stackoverflow.com/q/11322430
has comment: http://stackoverflow.com/comment/85437885
has answer: http://stackoverflow.com/a/49216925
accepted answer: http://stackoverflow.com/a/49217045
tagged with: python
tagged with: python-requests
has body: How do I make an inquiry from the Academic Articles list? using Python and Requests search for the name Maria Helena site: http://bibliotecadigital.fgv.br/ojs/index.php/abpt/search/search
has answer: http://stackoverflow.com/a/49217045
type: AnsweredQuestion
downvote count: 3
favorite count: 0
score: -1
has title: Python Requests - how use post method?
type: Question
has comment: http://stackoverflow.com/comment/85437820
answer count: 2

http://stackoverflow.com/comment/85484518
comment on: http://stackoverflow.com/q/49240434
score: 0
type: Comment
type: QuestionComment
has text: You really can't test for exceptions that were raised and handled. If you could, that would fire all over the place—in Python, everything from `hasattr` to simple `for` loops works by raising and handling exceptions.

http://stackoverflow.com/a/49133732
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85272435
upvote count: 2
downvote count: 0
has body: Beware: a decorator is applied at definition time and not at runtime. That means that when you could write is : @AddAge def GeneratePerson(name, lastname): ... That is enough to answer NO to your last question: it is not possible to pass the parameter to the decorator instead of the decorated function, unless you want it to be the same for all calls of the decorated function. But in Python 3 it is possible to add a parameter to the decorated function: def AddAge(param_name='age'): # define the new parameter param = inspect.Parameter(param_name, inspect.Parameter.POSITIONAL_OR_KEYWORD) def wrapper(f): sig = inspect.signature(f) params = list(sig.parameters.values()) params.append(param) # add the new parameter sig2 = sig.replace(parameters = params) # to a new signature def wrapped(*args, **kwargs): bound = sig2.bind(*args, **kwargs) # process the parameters args = bound.args # both positional kwargs = bound.kwargs # and keywords if param_name in kwargs: # extract the age age = kwargs[param_name] # either keyword del kwargs[param_name] else: args = list(args) # or positional age = args.pop() obj = f(*args, **kwargs) # call the original function obj.age = age # add the attribute return obj wrapped.__signature__ = sig2 # attach the new signature return wrapped return wrapper You can then use it that way &gt;&gt;&gt; f = AddAge()(GeneratePerson) &gt;&gt;&gt; p = f('John', 'Smith', 42) &gt;&gt;&gt; p.name 'John' &gt;&gt;&gt; p.lastname 'Smith' &gt;&gt;&gt; p.age 42 It can even support keywords in function call: &gt;&gt;&gt; p = f('John', age=42, lastname="Smith") will give expected result. The only limitation is that the original function shall not have a parameter named age. If it has, you must pass a different name to the decorator.
has comment: http://stackoverflow.com/comment/85272841
answers question: http://stackoverflow.com/q/49132405

http://stackoverflow.com/q/49254588
answer count: 2
type: UnansweredQuestion
tagged with: python
tagged with: psycopg2
has comment: http://stackoverflow.com/comment/93524758
tagged with: flask
score: 0
has answer: http://stackoverflow.com/a/49254651
has answer: http://stackoverflow.com/a/49800561
has body: cur = conn.cursor() result = cur.execute("SELECT * FROM users WHERE username = %s", [username]) if result &gt; 0: data = cur.fetchone() password = data['password'] if sha256_crypt.verify(password_given, password): app.logger.info('PASSWORD MATCHED') else: app.logger.info('PASSWORD Not MATCHED') this is the actual code am using. i think the error is coming from variable 'result', i want it to get the stored password as dictionary.
type: Question
has title: TypeError: unorderable types: NoneType() > int() retrieving from postgres database

http://stackoverflow.com/a/49147515
downvote count: 0
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85299696
type: Answer
accepted answer of: http://stackoverflow.com/q/49147276
answers question: http://stackoverflow.com/q/49147276
has body: You can use lookarounds while matching \n: (?&lt;=[a-zA-Z])\n(?=[a-zA-Z]) RegEx Demo Explanation: (?&lt;=[a-zA-Z]): Lookbehind to assert that we have a letter at previous position \n: Match newline (?=[a-zA-Z]): Lookahead to assert that we have a letter at next position Code: &gt;&gt;&gt; str = ("\n" ... "Lorem ipsum do\n" ... "lor sit amet \n") &gt;&gt;&gt; print re.sub(r"(?&lt;=[a-zA-Z])\n(?=[a-zA-Z])", '', str) Lorem ipsum dolor sit amet &gt;&gt;&gt;
type: AcceptedAnswer

http://stackoverflow.com/comment/85364691
type: QuestionComment
has text: This [answer](https://stackoverflow.com/a/29572789/355230) might help you.
comment on: http://stackoverflow.com/q/49177867
score: 1
type: Comment

http://stackoverflow.com/a/49230735
accepted answer of: http://stackoverflow.com/q/49230370
type: Answer
answers question: http://stackoverflow.com/q/49230370
has body: You can find your answer in the comments section of: Can I call a view from within another view? btw, yes you can create a method to validate user/department. below is the sample of how I have done in my app. A better approach I feel is to save such details in DB as a boolean flag and use django admin's capabilities to ease your work. def validate_details(request): user = request.GET['username'] user_details = User.objects.filter(name=user).values_list("name", "department", flat=True) # Call validation method defined in view is_ok = validate_user(user_details) if is_ok: return render_to_response("main/landing.html", {"user": user_details["name"],"department":user_details["department"]}, context_instance=RequestContext(request)) else: return render_to_response("main/landing.html", {"user":"NA","department":"NA"}, context_instance=RequestContext(request))
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/49204684
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49204811
favorite count: 0
has comment: http://stackoverflow.com/comment/85414880
has answer: http://stackoverflow.com/a/49204937
type: Question
has title: Classes: How to make it so that the user can input a dictionary into my class?
tagged with: typeerror
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85415016
has body: I need to edit my code so rather than creating the bag dictionary myself below, instead the user can input their own dictionary. A doc test of this would go as: &gt;&gt;&gt; bag = BeadBag({'green':44, 'blue':20, 'yellow':15, 'red':11, 'white':2, 'black':1}) &gt;&gt;&gt; bag.draw() 'yellow' &gt;&gt;&gt; bag.replace('yellow') The user would be inputting the dictionary into their call and I would no longer need "bag". Also I randomly keep getting TypeError: 'int' object is not subscriptable or TypeError: 'int' object is not iterable every now and then when I try running this code. The doc test that I am personally running just for looking over my work is: &gt;&gt;&gt;bag = BeadBag() &gt;&gt;&gt;bag.draw() 'black' &gt;&gt;&gt;bag.replace('yellow') {'red': [11], 'yellow': 23, 'green': [33], 'blue': [44], 'white': [55], 'black': 65} But it's not quite what I need it to be. import random class BeadBag(object): """ &gt;&gt;&gt; bag = BeadBag({'green':44, 'blue':20, 'yellow':15, 'red':11, 'white':2, 'black':1}) &gt;&gt;&gt; bag.draw() 'yellow' &gt;&gt;&gt; bag.replace('yellow') &gt;&gt;&gt; """ bag = {'red':[11], 'yellow':[22], 'green':[33], 'blue':[44], 'white':[55], 'black':[66]} def draw(self): words = [] for i in BeadBag.bag.keys(): words.append(i) rand = random.choice(words) minus = ((BeadBag.bag.get(rand))[0]-1) #subtracts one from each draw for key, value in BeadBag.bag.items(): BeadBag.bag[rand] = minus return rand def replace(self, color): cvalue = (BeadBag.bag[color]) for i in cvalue: val = int(i) add = val+1 for key, value in BeadBag.bag.items(): BeadBag.bag[color] = add return BeadBag.bag
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85414907
answer count: 4
tagged with: class
has answer: http://stackoverflow.com/a/49204815
upvote count: 2
has comment: http://stackoverflow.com/comment/85414940
has answer: http://stackoverflow.com/a/49204949

http://stackoverflow.com/comment/85429125
score: 0
has text: Great! Thanks for showing me the _source_. I _wanted_ to look for the source. I _thought_ I _could_ dig in to find it, but just couldn't get there.
type: AnswerComment
comment on: http://stackoverflow.com/a/49205251
type: Comment

http://stackoverflow.com/q/49245216
has body: I'm attempting to perform a bulk upsert with SqlAlchemy and Postgres in which all rows being upserted receive a unique set of values to update in the event there is a conflict. I would prefer to do this without a for loop so that I'm only executing one SQL statement overall. Is there a way to accomplish this? Here's what I currently have. This method works as intended when using the .on_update_do_nothing method. I'm wondering how to properly pass each set of values so that each record is updated with the proper information in the event of a conflict instead of generic values. As far as I am aware, attempting excluded data as suggested in similar question answers will not solve this problem, as set_ expects a dictionary of values, not a list. def bulkUpsert(self, items, unique_fields): """ Either inserts items into the table of supplied schema or does nothing. Requires items to be mapped prior to being passed to this method. """ try: statement = postgresql \ .insert(self.SCHEMA.__table__) \ .values(items) \ .on_conflict_do_update( index_elements = unique_fields, set_ = What to put here? ) self.SESSION.execute(statement) self.SESSION.commit() except SQLAlchemyError as err: print("Error with bulk insert: %s" % (err)) Currently, the items parameter is a list of dictionaries, which will work as intended when
answer count: 0
upvote count: 2
downvote count: 0
tagged with: sqlalchemy
favorite count: 0
type: Question
tagged with: postgresql
type: UnansweredQuestion
tagged with: python
has title: SqlAlchemy bulk upsert with unique `set_` values (Postgres)
score: 2

google-oauth
type: Tag
tag name: google-oauth
tags question: http://stackoverflow.com/q/49187463

http://stackoverflow.com/comment/85370835
comment on: http://stackoverflow.com/q/49182367
type: Comment
type: QuestionComment
has text: @abarnert : Thanks for the clarification. But reading each line at a time, will this not consume lots of time ? Instead I searching for some thing like: ( read chunk of 2KB.) or (the previous line <if 2KB lies in middle of line>)
score: 0

http://stackoverflow.com/comment/85415009
type: Comment
score: 0
type: QuestionComment
has text: [Here](http://numba.pydata.org/numba-doc/dev/reference/jit-compilation.html#vectorized-functions-ufuncs-and-dufuncs) is the documentation for `@numba.vectorize()` functions
comment on: http://stackoverflow.com/q/49204394

http://stackoverflow.com/comment/85463987
type: QuestionComment
comment on: http://stackoverflow.com/q/49230262
has text: Give me some time, I'm looking for a much faster non-regex solution.
score: 0
type: Comment

http://stackoverflow.com/q/49194556
score: 0
has title: task queue in celery
has body: I have a service that processes data. It is written in Python (Django) and uses Celery for making it asynchronous. Processing our data uses credits. You can also buy credits and this is triggered by a Stripe-webhook. Each action that involves credit changes is listed as a "job". I have 2 Celery tasks all adding a job to a certain JobId database. I use the "job" concept to keep track of which data is processed at which job. models.py: class JobId(models.Model): user = models.ForeignKey(User, blank=True, null=True, default=None) job_time = models.DateTimeField(auto_now_add=True) # current credit level credits = models.IntegerField(default=0, null=True, blank=True) # credit impact / delta of this job credit_delta = models.IntegerField(default=0, null=True, blank=True) tasks.py: task_1_buy_credits(user): # credit level of user is searched in jobs_database (the users last job) # adds one line in the JobId database with the users new credit balance task_2_use_credits(user,data): # upfront unknown amount of data get processed # credit level of user is searched in jobs_database (the users last job) # decide to process job completely or stop if credit level is insufficient My current issue is that when people start multiple jobs at a time, the previous job is not finished yet. As my final credit balance is not known yet I set it to zero to prevent new jobs from starting for now, while there might be credits left to do the job. A similar situation happens when credit levels are increased when a job is being processed at the same time. Basically, I need a kind of solution that allows to only run tasks in the same order they were created and after the previous one is finished. OR I need to have a real-time "user related credit level check" function that works across running tasks that are not finished yet. I can not run this synchronous on my Django environment as my timeout is 30 seconds due to the fact that this is a web application hosted on heroku.
answer count: 1
tagged with: celery
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49194743
tagged with: django
tagged with: python

http://stackoverflow.com/comment/85310566
score: 0
comment on: http://stackoverflow.com/q/49152901
has text: Can you add a sample of the html your are parsing? Specifically what does ` ` actually look like and can it contain more than 1 `` tag?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49204969
score: 0
has body: As the error message implies, sets cannot be nested. However, you can create a set wrapper to create a representation of nested sets: class SetWrapper: def __init__(self, *args): self.v = set() if not args else args def __repr__(self): return "{}({})".format(self.__class__.__name__, str(self)) def __str__(self): return '{'+', '.join(str(i) for i in self.v)+'}' def wrap_set(f): def wrapper(): return SetWrapper(*[i if type(i) not in [list, set] else SetWrapper(*i) for i in f()]) return wrapper @wrap_set def get_list(): return [[1,2],[4,5,6],[9],[]] print(get_list()) Output: SetWrapper({{1, 2}, {4, 5, 6}, {9}, {}})
answers question: http://stackoverflow.com/q/49204936
has comment: http://stackoverflow.com/comment/85415270
type: Answer

http://stackoverflow.com/comment/85324789
type: Comment
comment on: http://stackoverflow.com/a/49157310
score: 0
has text: It's hard for me to say, unless I see _index.html_ file. I have edited by response with the contents of the index file that I have used. Perhaps that could help.
type: AnswerComment

http://stackoverflow.com/a/49164876
type: Answer
has body: from django.db.models import Q def search(request): results = [] query = request.GET.get('q', None) if query: try: results = Articulo.objects.filter(Q(titulo__icontains=query) | Q(cuerpo_icontains=query)) except Articulo.DoesNotExist: pass return render_to_response('web/buscar.html',{"results": results, "query": query})
score: 0
has comment: http://stackoverflow.com/comment/85426551
answers question: http://stackoverflow.com/q/49163929

http://stackoverflow.com/q/49179179
has answer: http://stackoverflow.com/a/49180414
favorite count: 0
has comment: http://stackoverflow.com/comment/85365216
has comment: http://stackoverflow.com/comment/85366056
type: Question
tagged with: python
answer count: 1
accepted answer: http://stackoverflow.com/a/49180414
has title: turning a list from a loop iteration to a df in pyhon
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
has body: I have some file which I am running a loop over all file and doing some calculations. I would like to get a new df with the name of the files on the row side and the calculated value per each file in the correct row. the code is: results = [] file_name = '{}' for file in folder: df = pd.read_csv(file_name.format(file)) print("reading file ", file) results.append(df['old_calc'])#this is the data i want to save to the new df and I need it .sum() the above code doesn't work as expected as it is giving me: old calc old calc old calc old calc old calc old calc old calc 4 0.0 0.0 0.0 0.0 0.0 0.0 5 0.0 0.0 0.0 59.0 0.0 0.0 6 0.0 0.0 58.4 0.0 0.0 0.0 7 0.0 0.0 8.4 -79.1 0.0 0.0 8 0.0 0.0 120.9 0.0 0.0 0.0 The expected result will be a new df named results: file1 0 file2 0 file3 187.7 file4 20.1 file5 0 thanks for the help
has comment: http://stackoverflow.com/comment/85364641

http://stackoverflow.com/comment/85282434
score: 0
type: Comment
type: QuestionComment
has text: Note that these comprehensions do *not* match up the parens for you. For that, there is a straightforward increment/decrement counting algorithm that will do the job cleanly. If you get stuck, please post that as a separate question (but search first; I'm pretty sure there are at least two solutions already on SO).
comment on: http://stackoverflow.com/q/49138587

http://stackoverflow.com/comment/85282974
score: 0
type: AnswerComment
type: Comment
has text: @Fomalhaut-C yw:-) happy coding
comment on: http://stackoverflow.com/a/49138599

http://stackoverflow.com/a/49148126
score: 3
type: Answer
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49148036
has body: You can actually utilise the library getpass as follows: import getpass password = getpass.getpass("Enter your password: ") print(password) A general rule of thumb is to not show the number of characters in a person's password via the asterisks/dots shown, which is what getpass does.

http://stackoverflow.com/a/49157987
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49153583
score: 0
answers question: http://stackoverflow.com/q/49153583
type: Answer
has body: Your code is based on some very old Bluez API: The org.bluez.Service interface was removed many years ago. If you want to accomplish the same in modern linux with modern Bluez, take a look at the Profile API and how the example tool adds a service record.

http://stackoverflow.com/comment/85417629
comment on: http://stackoverflow.com/q/49205878
score: 2
has text: Possible duplicate of [How to split string without spaces into list of integers in Python?](https://stackoverflow.com/questions/29409273/how-to-split-string-without-spaces-into-list-of-integers-in-python)
type: QuestionComment
type: Comment

chemistry
type: Tag
tag name: chemistry
tags question: http://stackoverflow.com/q/49239475

http://stackoverflow.com/comment/85563808
score: 0
type: Comment
type: QuestionComment
has text: @abe-wong thanks for undoing it. I deleted my answer.
comment on: http://stackoverflow.com/q/49278571

http://stackoverflow.com/comment/85266743
has text: Your first argument to the `format` function is `i for i in range(1, len(dates))`, which is in fact a generator. You could put a `list()` around it, but that still wouldn't give you the expected result. You want a print for every date, so the `print` statement definitely needs to be inside the `for` loop (like in coldspeed's answer).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49130624
score: 0

mysql
tags question: http://stackoverflow.com/q/49235332
tags question: http://stackoverflow.com/q/49143160
tags question: http://stackoverflow.com/q/49244747
tags question: http://stackoverflow.com/q/49267511
tags question: http://stackoverflow.com/q/49147353
tags question: http://stackoverflow.com/q/49277003
tags question: http://stackoverflow.com/q/49157396
tags question: http://stackoverflow.com/q/49159623
tags question: http://stackoverflow.com/q/49252137
type: Tag
tags question: http://stackoverflow.com/q/49153530
tags question: http://stackoverflow.com/q/49211228
tags question: http://stackoverflow.com/q/49278555
tags question: http://stackoverflow.com/q/49163774
tags question: http://stackoverflow.com/q/49193680
tag name: mysql
tags question: http://stackoverflow.com/q/49192573
tags question: http://stackoverflow.com/q/49229570
tags question: http://stackoverflow.com/q/49144545
tags question: http://stackoverflow.com/q/49153709
tags question: http://stackoverflow.com/q/49150698
tags question: http://stackoverflow.com/q/49276375
tags question: http://stackoverflow.com/q/49144048
tags question: http://stackoverflow.com/q/49205375
tags question: http://stackoverflow.com/q/49218572
tags question: http://stackoverflow.com/q/49217919
tags question: http://stackoverflow.com/q/49262646
tags question: http://stackoverflow.com/q/49192695
tags question: http://stackoverflow.com/q/49133875

http://stackoverflow.com/comment/85485389
comment on: http://stackoverflow.com/q/49240582
score: 0
type: Comment
has text: I get `TimeoutException`. I think the new tab is just not recognized
type: QuestionComment

http://stackoverflow.com/q/49237550
tagged with: flask
type: Question
has body: I'm having issues making flask work. I'm a noob and still learning about Linux. I'm getting this (very intimidating looking)error after running: flask run root@DESKTOP-TV7O885:/mnt/c/Projects/app_1# flask run * Serving Flask app "application" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) [2018-03-12 14:10:00,550] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/mnt/c/Projects/app_1/application.py", line 7, in index return render_template("index.html") File "/usr/local/lib/python2.7/dist-packages/flask/templating.py", line 133, in render_template return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list), File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 869, in get_or_select_template return self.get_template(template_name_or_list, parent, globals) File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 830, in get_template return self._load_template(name, self.make_globals(globals)) File "/usr/local/lib/python2.7/dist-packages/jinja2/environment.py", line 804, in _load_template template = self.loader.load(self, name, globals) File "/usr/local/lib/python2.7/dist-packages/jinja2/loaders.py", line 113, in load source, filename, uptodate = self.get_source(environment, name) File "/usr/local/lib/python2.7/dist-packages/flask…
has answer: http://stackoverflow.com/a/49237824
tagged with: python
has title: Flask configuration Error
score: 0
linked to: http://stackoverflow.com/q/23327293
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/23327293
answer count: 1

http://stackoverflow.com/a/49144690
has comment: http://stackoverflow.com/comment/85294673
has comment: http://stackoverflow.com/comment/85294744
has comment: http://stackoverflow.com/comment/85294691
answers question: http://stackoverflow.com/q/49144632
accepted answer of: http://stackoverflow.com/q/49144632
has body: The main error here is that you are calling input_number1(), input_operator() and input_number2() after the function definition so they call once after the function is defined and their return value is ignored, then once again to actually store and calculate the result. And about the ValueError I can't seem to find where that might be, for me the code works fine after fixing the main problem. On what line does the problem happen?
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/85296098
has comment: http://stackoverflow.com/comment/85298615
score: 0

set
tags question: http://stackoverflow.com/q/49182242
tag name: set
tags question: http://stackoverflow.com/q/49255121
tags question: http://stackoverflow.com/q/49204936
tags question: http://stackoverflow.com/q/49223147
tags question: http://stackoverflow.com/q/49149218
tags question: http://stackoverflow.com/q/49185980
tags question: http://stackoverflow.com/q/49245739
type: Tag
tags question: http://stackoverflow.com/q/49210834
tags question: http://stackoverflow.com/q/49275383
tags question: http://stackoverflow.com/q/49181155

http://stackoverflow.com/comment/85271576
comment on: http://stackoverflow.com/q/49131708
type: Comment
type: QuestionComment
has text: Yeah, suit yourself. Only you can answer your question since we do not have all the data, and you have not shared the exact specs.
score: 0

http://stackoverflow.com/a/49270369
type: Answer
score: 0
has body: Minimum number of robots means longest path for each robot. To find the longest possible paths I propose the following: 1. From each of the N nodes (cities) find the longest possible path. (Finding longest path for each can be done by storing all paths: see here) 2. The longest path of the N found is the path of one robot 3. Remove the edges (roads) of that longest path so it will not be included in the following searches 4. Repeat 1-3 until all edges removed
answers question: http://stackoverflow.com/q/49208000

http://stackoverflow.com/q/49192968
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49218468
has body: I am trying to solve a similar problem like YOLO, except by the fact that my boxes are rotated. Thus I need to add a 6th parameter to account for theta/rotation. I only have one class. My tensors are 16x16x6 This implementation does not seem to work. My loss is always the same regardless of network architecture or epoch. After many changes I am deeply convinced my loss calculation is wrong def my_loss(y_true,y_pred): # 0,prob / 1,x /2,y/3,a/4,b/5,theta #params["w_l"]=[5.0,0.5] #m1=labels[...,5] &gt; 0 #m2=labels[...,5] &lt; 0 #labels[m1][...,5]/=360 #labels[m2][...,5]=(labels[m2][...,5]+360)/360 lambda_coord=y_true[...,0]*params["w_l"][0] lambda_noobj=-(y_true[...,0] -1.0)*params["w_l"][1] ly=K.sum(K.square(y_pred[...,1]-y_true[...,1])*lambda_coord) lx=K.sum(K.square(y_pred[...,2]-y_true[...,2])*lambda_coord) lt=K.sum(K.square(y_pred[...,5]-y_true[...,5])*lambda_coord) la=K.sum(K.square(K.sqrt(y_pred[...,3])-K.sqrt(y_true[...,3]))*lambda_coord) lb=K.sum(K.square(K.sqrt(y_pred[...,4])-K.sqrt(y_true[...,4]))*lambda_coord) lp=K.sum(K.square(y_true[...,0]-y_pred[...,0])*lambda_noobj) return ly+lx+lt+la+lb+lp My label array contains probability/y/x/a/b/theta. Loss coming from positives (coordinates/size/theta) are multiplied by a factor, as to reinforce their losses on the total loss, while the probability loss for Negatives is reduced by a factor as to lower their influence. Any advise of improvement or hind at what is wrong ? Thanks JC
tagged with: python
score: 0
answer count: 1
tagged with: loss-function
tagged with: keras
has title: YOLO custom loss using keras

http://stackoverflow.com/comment/85446428
score: 0
type: AnswerComment
has text: I get only the fields from `Foo` into the output, not those from `Bar`. The ouput looks like this, `[OrderedDict([('name', ' A '), ('city', 'B')]), .....`
comment on: http://stackoverflow.com/a/49221179
type: Comment

http://stackoverflow.com/q/49266014
tagged with: scipy
favorite count: 0
tagged with: distribution
has answer: http://stackoverflow.com/a/49957167
tagged with: seaborn
answer count: 2
has comment: http://stackoverflow.com/comment/85536566
tagged with: gaussian
has comment: http://stackoverflow.com/comment/85535643
has comment: http://stackoverflow.com/comment/86930385
has comment: http://stackoverflow.com/comment/85535475
has title: Why is it scipy.stats.gaussian_kde() slower than seaborn.kde_plot() for the same data?
downvote count: 1
has comment: http://stackoverflow.com/comment/85536506
type: Question
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49266901
upvote count: 5
has body: In python 3.7, I have this numpy array with shape=(2, 34900). This arrays is a list of coordinates where the index 0 represents the X axis and the index 1 represents the y axis. When I use seaborn.kde_plot() to make a visualization of the distribution of this data, I'm able to get the result in about 5-15 seconds when running on a i5 7th generation. But when I try to run the following piece of code: #Find the kernel for k = scipy.stats.kde.gaussian_kde(data, bw_method=.3) #Define the grid xi, yi = np.mgrid[0:1:2000*1j, 0:1:2000*1j] #apply the function zi = k(np.vstack([xi.flatten(), yi.flatten()])) which finds the gaussian kernel for this data and applies it to a grid I defined, it takes much more time. I wasn't able to run the full array but when running on a slice with the size of 140, it takes about 40 seconds to complete. The 140 sized slice does make an interesting result which I was able to visualize using plt.pcolormesh(). My question is what I am missing here. If I understood what is happening correctly, I'm using the scipy.stats.kde.gaussian_kde() to create an estimation of a function defined by the data. Then I'm applying the function to a 2D space and getting it's Z component as result. Then I'm plotting the Z component. But how can this process be any different from seaborn.kde_plot() that makes the code take so much longer. Scipy's implementation just goes through each point doing this: for i in range(self.n): diff = self.dataset[:, i, newaxis] - points tdiff = dot(self.inv_cov, diff) energy = sum(diff*tdiff,axis=0) / 2.0 result = result + exp(-energy)
tagged with: python
has answer: http://stackoverflow.com/a/49266901
score: 4
has comment: http://stackoverflow.com/comment/85537235
accepted answer: http://stackoverflow.com/a/49957167

http://stackoverflow.com/comment/85376192
type: Comment
has text: `biglist1` is defined where? Can you show a [mcve] please?
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49185209

http://stackoverflow.com/q/49224992
has body: I got a list of tuples after some calcualtions, which contains [(str, str, float), (...), ...] format: output: [('inputData_4', 'targetData_1', 0.09739792547374054), ('inputData_4', 'targetData_1', 0.09739792718209167), ('inputData_4', 'targetData_1', 0.09739793368940086), ('inputData_2', 'targetData_1', 0.10266894735114324), ('inputData_2', 'targetData_1', 0.1026689508485586), ('inputData_2', 'targetData_1', 0.10873575415245394), ('inputData_3', 'targetData_1', 0.1464233452565107), ('inputData_3', 'targetData_1', 0.14642335418508975), ('inputData_3', 'targetData_1', 0.14642336077619336), ('inputData_1', 'targetData_1', 0.1561837827131314), ('inputData_1', 'targetData_1', 0.15618378709179737), ('inputData_1', 'targetData_1', 0.15618379092496212)] The list is sorted using float as key-valuesorted(meanScores, key=lambda tup: tup[2]) and as you see, every tuple is repeated three times. How I can extract only three tupels (if the list contains at least three tupels) with smallest float values from the whole list and without repeating it? Thank you! EDIT The order of repeated tupels can be also listed differently like: output: [('inputData_4', 'targetData_1', 0.09739792547374054), ('inputData_2', 'targetData_1', 0.1026689508485586), ('inputData_4', 'targetData_1', 0.09739793368940086), ('inputData_2', 'targetData_1', 0.10266894735114324), ('inputData_2', 'targetData_1', 0.10873575415245394), ('inputData_4', 'targetData_1', 0.09739792718209167), ...]
has comment: http://stackoverflow.com/comment/85453646
has title: Extract n-tupels from a list of tupels in python
answer count: 1
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85454214
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85453781
has answer: http://stackoverflow.com/a/49225960
has comment: http://stackoverflow.com/comment/85453982
tagged with: python
score: -1
upvote count: 0

http://stackoverflow.com/comment/85264181
type: Comment
comment on: http://stackoverflow.com/a/49129374
type: AnswerComment
has text: That sounds like a lot of work. I will stick with vector graphics for the time being. Hopefully, this issue is addressed in the near future. Thank you.
score: 0

http://stackoverflow.com/comment/124440176
type: Comment
has text: This solution does not answer the question. It only addresses the part of the question that the author already knows how to solve, but in a worse way (`split` already returns a list)
comment on: http://stackoverflow.com/a/70374891
type: AnswerComment
score: 0

http://stackoverflow.com/q/49182304
downvote count: 0
has title: Escaping a sed expression to execute over ssh from Python
has comment: http://stackoverflow.com/comment/85370437
answer count: 1
has comment: http://stackoverflow.com/comment/85370561
has body: I have a file on a remote server that needs to have a line updated in it. I am trying to do the update via python but appear to be having a character escape issue. The line in the file I am trying to update is: BEGRCVDDATE=02/01/2018 00:00 am The line of code in python script I am using to try and make the update: os.popen('ssh %s sed -i s/'BEGRCVDDATE=[0-9][0-9]\/[0-9][0-9]\/[0-9][0-9][0-9][0-9] [0-9][0-9]:[0-9][0-9] [a-z][a-z]'/'BEGRCVDDATE=%s'/ %s' % (ip, rcvdate, file_path)) The above code is throwing the following error: sed: -e expression #1, char 37: unknown option to `s' I am however able to run the sed command outside of the python script which leads me to believe this is a character escaping issue. Below works outside of the python script. ssh &lt;ip&gt; "sed -i s/'BEGRCVDDATE=[0-9][0-9]\/[0-9][0-9]\/[0-9][0-9][0-9][0-9] [0-9][0-9]:[0-9][0-9] [a-z][a-z]'/'BEGRCVDDATE=BEGRCVDDATE=03\\/08\\/2018 00:00 pm'/ /tmp/test.txt" I have tried various combinations of quotes and back-slashes to try and get around the issue I am seeing without success. If anyone can help me resolve the issue I am seeing it would be much appreciated. Note: due to python version in my environment os.popen is being using instead of subprocess.
accepted answer: http://stackoverflow.com/a/49182523
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85370363
upvote count: 1
has comment: http://stackoverflow.com/comment/85370688
score: 1
has comment: http://stackoverflow.com/comment/85370565
tagged with: python
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49182523
has comment: http://stackoverflow.com/comment/85370666
has comment: http://stackoverflow.com/comment/85370767
tagged with: bash

http://stackoverflow.com/a/49193476
has comment: http://stackoverflow.com/comment/86022428
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85392233
has comment: http://stackoverflow.com/comment/85392135
has body: In place of print write that line to CSV import numpy as np tester=['id', '0c9d534a-5af4-4fa5-8cd7-668432775317', 'name', 'test company UK Sandbox', 'account', 'test company - Pilot', 'account_id', '704fbc55-0565-496f-94e6-2e0c95b98327', 'ea_project_id', '0c9d534a-5af4-4fa5-8cd7-668432775317', 'ea_account_id', '704fbc55-0565-496f-94e6-2e0c95b98327', 'project_ppc_to_date', '26.22', 'trailing_week_ppc', '0', 'image_path', 'Blank', 'start_date', '2015-06-01', 'id', '3c47d67b-d2b5-494e-8c37-0552dfb1449a', 'name', 'XXMA0069 - TEST', 'account', 'test company - Pilot', 'account_id', '704fbc55-0565-496f-94e6-2e0c95b98327', 'ea_project_id', '3c47d67b-d2b5-494e-8c37-0552dfb1449a', 'ea_account_id', '704fbc55-0565-496f-94e6-2e0c95b98327', 'project_ppc_to_date', '65.79', 'trailing_week_ppc', '0', 'image_path', '\\/api\\/v1\\/projects\\/3c47d67b-d2b5-494e-8c37-0552dfb1449a\\/image', 'start_date', '2015-10-05', 'id', 'ae326656-0523-4c8f-894d-18d6f615c4d4', 'name', 'XXMA006', 'account', 'test company', 'account_id', '704fbc55-0565-496f-94e6-2e0c95b98327', 'ea_project_id', 'ae326656-0523-4c8f-894d-18d6f615c4d4', 'ea_account_id', '704fbc55-0565-496f-94e6-2e0c95b98327', 'project_ppc_to_date', '45.41', 'trailing_week_ppc', '33.33', 'image_path', 'Blank', 'start_date', '2015-10-05', 'id', '944036a2-0aaf-42bf-851b-9b0ced44df45', 'name', 'XXMA0076 - TEST', 'account', 'test company - Pilot', 'account_id', '704fbc55-0565-496f-94e6-2e0c95b98327', 'ea_project_id', '944036a2-0aaf-42bf-851b-9b0ced44df45', 'ea_account_id', '704fbc55-0565-496f-94e6-2e0c95b98327', 'project_ppc_to_date', '72.04', 'trailing_week_ppc', '23.08', 'image_path', '\\/api\\/v1\\/projects\\/944036a2-0aaf-42bf-851b-9b0ced44df45\\/image', 'start_date', '2016-10-24', 'id', '11fa1215-0b4a-4437-9c5e-31dbe9599b52', 'name', 'XXMA0082 - QEHB PFP Project', 'account', 'test company - Pilot', 'account_id', '704fbc55-0565-496f-94e6-2e0c95b98327', 'ea_project_id', '11fa1215-0b4a-4437-9c5e-31dbe9599b52', 'ea_account_id', '704fbc55-0565-4…
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49193096

http://stackoverflow.com/a/49164372
has body: data = ['owner'] means data is a list contains one string owner but not means it is a dictionary contains one key owner(correct one should be something like data={"owner": None}). So when you access it like data["owner"], you are trying to use it like a dictionary, but it is a list. And that's why you get error: list indices must be integers, not str.
has comment: http://stackoverflow.com/comment/85334297
downvote count: 2
upvote count: 1
answers question: http://stackoverflow.com/q/49164181
has comment: http://stackoverflow.com/comment/85334423
type: Answer
score: -1

http://stackoverflow.com/comment/85502384
has text: You may want to call out (er, no pun intended) that you're *calling* the functions in the `if f()` line, since that change is pretty subtle and there are other changes, like skipping the `range` that might distract from the important one.
comment on: http://stackoverflow.com/a/49249462
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85515222
type: QuestionComment
has text: In case you're looking for a practical solution (and not just debugging) you can just define the function as: ``to_bin =lambda x: "{0:b}".format(x)`` https://stackoverflow.com/questions/699866/python-int-to-binary
comment on: http://stackoverflow.com/q/49256063
score: 0
type: Comment

http://stackoverflow.com/q/49163417
upvote count: 4
score: 3
tagged with: google-places-api
tagged with: google-maps
answer count: 0
tagged with: google-api
has body: I'm using this package to run Google Places API on Python. I'm running the following code: from googleplaces import GooglePlaces, types, lang key='XXXXXXX' google_places = GooglePlaces(key) query_result = google_places.nearby_search( location='London, England', keyword='Fish and Chips', radius=20000, types=[types.TYPE_FOOD]) print(query_result) However when I do that, I get this error: { "error_message" : "This API project is not authorized to use this API. Please ensure this API is activated in the Google Developers Console: https://console.developers.google.com/apis/api/geocoding_backend?project=_", "results" : [], "status" : "REQUEST_DENIED" } However my API is enabled and everything seems cool, as you can see below: Can someone help here?
downvote count: 1
favorite count: 0
has title: My Google-Places API Key is activated but not working
has comment: http://stackoverflow.com/comment/85382611
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85354564
tagged with: python
has comment: http://stackoverflow.com/comment/85361349
tagged with: google-maps-api-3

http://stackoverflow.com/comment/85315552
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49155472
has text: I guess you could do `for key in b: if key not in a: a[key] = b[key]`

http://stackoverflow.com/comment/85281156
has text: **Table=Table.assign(Field3=np.where((Table.Field1=='J')&(Table.Field2.astype(str).str[0:5].isin(['JLP10', 'ABCD '])),3, np.where(Table.Field1=='J',2,1)))** in this case [0:5] would be 'ABCD ' but that seems to be an invalid character
type: AnswerComment
comment on: http://stackoverflow.com/a/49137865
score: 0
type: Comment

http://stackoverflow.com/comment/86183869
has text: @YanKhonski From my perspective, only net_read_timeout needs to be adjusted in my.cnf-ini to allow more time to read the packet. Shutdown/restart when permitted.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49153530
score: 0

http://stackoverflow.com/comment/85614647
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49302004
has text: and: `circles = pd.DataFrame({'circle': {0: 1.0, 1: 2.0, 2: 3.0, 3: 4.0, 4: 5.0, 5: 6.0, 6: 7.0, 7: 8.0}, 'time': {0: 1.0, 1: 2.0, 2: 3.0, 3: 4.0, 4: 5.0, 5: 6.0, 6: 7.0, 7: 8.0}, 'x': {0: 235, 1: 236, 2: 245, 3: 215, 4: 287, 5: 394, 6: 132, 7: 104}, 'y': {0: 133, 1: 133, 2: 425, 3: 325, 4: 203, 5: 394, 6: 104, 7: 258}})`

http://stackoverflow.com/q/49181653
tagged with: pandas
answer count: 1
has answer: http://stackoverflow.com/a/49182033
has comment: http://stackoverflow.com/comment/85368910
type: Question
has body: I'm learning about time series and am trying to predict closing stock price for the next two weeks, given the data I already have (about a year). I've created 7 lag features using Pandas shift, so I have features t-7, t-6, ..., t-1 and the current day's closing stock price for my whole DataFrame, df. I've made a test_df which is just the last two weeks of data. test_df has the true values for each of its row's lagged features. I want to mimic predicting future values by limiting myself to values from my training set (everything in df before the last two weeks) and my predictions. So I was going to do something like: # for each row in test_df # prediction = model.predict(row) # row["t"] = prediction I think this is close, but it doesn't fix other lagged features like t-1, t-2, ..., t-7. I need to do this: row 2, t = prediction for row 1 row 2, t-1 = t for row 1 ... row 2, t-i = t-i+1 for row 1 And I would repeat this for all rows in my test_df. I could do this by writing my own function, but I'm wondering if there's a way to take advantage of Pandas to do this more easily. Edit for clarity: Suppose I'm looking at my first test row. I don't have the closing_price, so I use my model to predict based on the lagged features. Before prediction, my df looks like this: closing_price t-1 t-2 t-3 t-4 t-5 0 None 7 6 5 4 3 Suppose my prediction for closing_price is 15. Then my updated DataFrame should look like this: closing_price t-1 t-2 t-3 t-4 t-5 0 15.0 7.0 6.0 5.0 4.0 3.0 1 NaN 15.0 7.0 6.0 5.0 4.0 Thanks!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85368986
has title: Pandas: Timeseries using predictions as ground truth
linked to: http://stackoverflow.com/q/13842088
tagged with: python
has comment: http://stackoverflow.com/comment/85369179
score: 0
has comment: http://stackoverflow.com/comment/85370638

http://stackoverflow.com/comment/85288068
score: 0
type: AnswerComment
has text: Sorry, I don't really understand what you mean. Could you be more specific? Often when I try to write down a problem that I walk into, as if I was explaining it to someone else, it helps me get new ideas on how to solve it.
comment on: http://stackoverflow.com/a/49138406
type: Comment

http://stackoverflow.com/a/49144327
answers question: http://stackoverflow.com/q/49123636
score: 2
upvote count: 2
downvote count: 0
has body: This should work. I've tried to make it generic. You might have to make some minor adjustments. Let me know if you don't understand any part. def checkValidity(tlist): tmpVar = '' for i in range(len(tlist)): if tlist[i] in set("hello"): tmpVar += tlist[i] return(tmpVar == 'hello') mStr = "he.llo hehellbo hellox hell.o hello helloxy abhell.oyz" mWord = "hello" mlen = len(mStr) wordLen = len(mWord)+1 i=0 print ("given str = ", mStr) while i&lt;mlen: tmpList = [] if mStr[i] == 'h': for j in range(wordLen): tmpList.append(mStr[i+j]) validFlag = checkValidity(tmpList) if validFlag: print("Match starting at index: ",i, ':', mStr[i:i+wordLen]) i += wordLen else: i += 1 else: i += 1
type: Answer

http://stackoverflow.com/a/49190302
accepted answer of: http://stackoverflow.com/q/49190278
upvote count: 2
answers question: http://stackoverflow.com/q/49190278
type: Answer
has comment: http://stackoverflow.com/comment/85396088
score: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85392004
has comment: http://stackoverflow.com/comment/85429883
has body: Slicing is your friend - pd.DataFrame(results[1::2], index=results[::2], columns=['col']) col 2017-04-03.csv 108.0 2017-04-04.csv -12.0 Even indexed elements form the index, and odd indexed elements form the column values.

http://stackoverflow.com/q/49257106
tagged with: django
tagged with: python
type: AnsweredQuestion
answer count: 2
has title: Django Error While Creating Pages
downvote count: 0
upvote count: 1
score: 1
possible better answer: http://stackoverflow.com/a/49270697
has answer: http://stackoverflow.com/a/49257190
favorite count: 0
has body: I encountered this issue while creating a page in tango_with_django_project. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/rango/category//add_page/ Using the URLconf defined in tango_with_django_project.urls, Django tried these URL patterns, in this order: admin/ ^rango/ ^$ [name='index'] ^rango/ about/$ [name='about'] ^rango/ ^add_category/$ [name='add_category'] ^rango/ ^category/(?P<category_name_url>\w+)/$ [name='category'] ^rango/ ^category/(?P<category_name_url>\w+)$/add_page/$ [name='add_page'] ^media\/(?P<path>.*)$ The current path, rango/category//add_page/, didn't match any of these. Please have a look at my files. The following is my views.py. def add_page(request, category_name_url): context = RequestContext(request) category_name = decode_url(category_name_url) if request.method == 'POST': form = PageForm(request.POST) if form.is_valid(): page = form.save(commit=False) try: cat = Category.objects.get(name=category_name) page.category = cat except Category.DoesNotExist: return render_to_response('rango/add_category.html', {}, context) page.views = 0 page.save() return category(request, category_name_url) else: print (form.errors) else: form = PageForm() return render_to_response( 'rango/add_page.html', {'category_name_url': category_name_url, 'category_name': category_name, 'form': form}, context) This is my urls.py from django.conf.urls import url from rango import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'about/$', views.about, name='about'), url(r'^add_category/$', views.add_category, name='add_category'), url(r'^category/(?P<category_name_url>\w+)/$', views.category, name='category'), url(r'^category/(?P<category_name_url>\w+)$/add_page/$', views.add_page, name='add_page'), ] This is my add_page.html Rango Add a Page to {{category.name}} <form id="pageI encountered this issue while creating a page in tango_with_django_project. Page not found (404) Request Method: GET Request URL: http://127.0.0.…
type: Question
has answer: http://stackoverflow.com/a/49270697
accepted answer: http://stackoverflow.com/a/49257190

http://stackoverflow.com/comment/85405739
has text: That comment doesn't seem related to this question. I recommend that you ask on the other question you recently asked, which seems more related. You might also consider editing your original question to include more details like "how do I check to see if it's safe to call compute" rather than engaging in a conversation in the comments.
type: Comment
comment on: http://stackoverflow.com/a/49199361
type: AnswerComment
score: 1

http://stackoverflow.com/a/49136968
answers question: http://stackoverflow.com/q/49136512
score: 0
has body: Try adding a conditional check to see if you've already found that userid before: for review in soup.find_all("div", {"class": "reviewContainer"}): userid_found = [] for review2 in review.findAll(True, {'id':True}): if len(review2) &gt; 0: userid = review2['id'] if userid not in userid_found: userid_found.append(userid) print(userid) else: userid = "N/A" print(userid)
type: Answer

http://stackoverflow.com/a/49149247
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49148997
downvote count: 0
has comment: http://stackoverflow.com/comment/85330855
has comment: http://stackoverflow.com/comment/85317692
type: Answer
answers question: http://stackoverflow.com/q/49148997
has comment: http://stackoverflow.com/comment/85304604
has body: Threads automatically finish when they finish their function. (You do usually want to keep the thread objects around and join them somewhere, but that’s not relevant to your problem here.) So, if you want them to finish after each task, why did you put a while True: loop inside the function? Just that take out and everything will work as you requested. It can be useful to have threads that run an infinite loop until the queue is done (and then break/return), but that’s a different design. For that design, you’d just want to start 10 threads at startup, rather than start a new batch of threads for each request. (Although in that case, you’re just building a bog-standard thread pool, so it may be easier to use the already-existing one in the stdlib—or the slightly higher-level concurrent.futures.ThreadPoolExecutor.) Finally, if what you want is really a new pool of 10 threads for each batch of requests, you can do that. It’s basically all the complexity of both alternatives, without any advantages over either, but it’s doable. Just as in the persistent thread pool, you’ll need to change the thread function to exit when the queue is done. And you’ll probably need to keep all 10 threads in a list and join them all after joining the queue. But that should work.
score: 2

http://stackoverflow.com/q/49165788
has answer: http://stackoverflow.com/a/49166717
type: AnsweredQuestion
has title: Multiple join paths in SQLAlchemy
score: 1
tagged with: orm
tagged with: python
tagged with: sqlalchemy
has body: I try to test the code example on SQLAlchemy documentation about handling multiple join paths. However after I create a customer object, both relationship attributes are None. I wonder how to properly handle multiple join paths? Do I need to create a relationship in Address class too? When do I need to use back_populates? Handling Multiple Join Paths from sqlalchemy import create_engine from sqlalchemy import Integer, ForeignKey, String, Column from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship Base = declarative_base() class Customer(Base): __tablename__ = 'customer' id = Column(Integer, primary_key=True) name = Column(String) billing_address_id = Column(Integer, ForeignKey("address.id")) shipping_address_id = Column(Integer, ForeignKey("address.id")) billing_address = relationship("Address", foreign_keys=[billing_address_id]) shipping_address = relationship("Address", foreign_keys=[shipping_address_id]) class Address(Base): __tablename__ = 'address' id = Column(Integer, primary_key=True) street = Column(String) city = Column(String) state = Column(String) zip = Column(String) engine = create_engine('sqlite:///Testing.db') Base.metadata.create_all(engine) a1 = Address(street="a street", city="a city", state="A", zip="12345") a2 = Address(street="b street", city="b city", state="B", zip="1233") c1 = Customer(name="Jack") print(c1.billing_address)
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49166717
answer count: 1
downvote count: 0
upvote count: 1

relative-path
type: Tag
tag name: relative-path
tags question: http://stackoverflow.com/q/49226626

http://stackoverflow.com/q/49227541
accepted answer: http://stackoverflow.com/a/49227659
answer count: 1
downvote count: 0
has body: I'm having trouble computing the path from the root to a specified node in a binary tree (this is specifically about a Python solution to this problem). Here's an example. Given the binary tree below, if I specify the node whose value is 4, I want to return [1, 2, 4]. If I specify the node whose value is 5, I want to return [1, 2, 5]. 1 / \ 2 3 / \ 4 5 Here's my attemped solution. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def path(root, k, l=[]): if not root: return [] if root.val == k: return l # Pre-order traversal: Visit root, then left, then right. l.append(root.val) path(root.left, k, l) path(root.right, k, l) return l Now if I run this &gt;&gt;&gt; a = TreeNode(1) &gt;&gt;&gt; b = TreeNode(2) &gt;&gt;&gt; c = TreeNode(3) &gt;&gt;&gt; d = TreeNode(4) &gt;&gt;&gt; e = TreeNode(5) &gt;&gt;&gt; a.left = b &gt;&gt;&gt; a.right = c &gt;&gt;&gt; b.left = d &gt;&gt;&gt; b.right = e &gt;&gt;&gt; path(a, 4) # should be [1, 2, 4] [1, 2, 5, 3] You can see that I don't get the expected. I'm sure it has to do with my traversal algorithm, but I can't figure out where I'm going wrong. Any help is greatly appreciated.
has title: Find Path to Specified Node in Binary Tree (Python)
favorite count: 0
tagged with: binary-tree
type: Question
upvote count: 4
tagged with: tree-traversal
has comment: http://stackoverflow.com/comment/85458829
tagged with: python
tagged with: depth-first-search
has answer: http://stackoverflow.com/a/49227659
score: 4
type: AnsweredQuestion

http://stackoverflow.com/q/49134634
has title: How to draw circle in basemap or add artiste
has comment: http://stackoverflow.com/comment/85274354
has comment: http://stackoverflow.com/comment/85274918
has answer: http://stackoverflow.com/a/49135298
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85275160
answer count: 2
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85274775
possible better answer: http://stackoverflow.com/a/49135298
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49135419
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85274980
tagged with: python
has answer: http://stackoverflow.com/a/49135419
has body: I want to know how can i plot a circle with Basemap using latitude and longitude. import matplotlib.pyplot as plt fig,ax = plt.subplots() ax.axis([0,10,0,10]) circle1 = plt.Circle((5, 5), 2, color='black',fill=False) x = ax.add_artist(circle1) plt.show() I want to do the same but with x,y,radius as lon lat in my basemap graph from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt m = Basemap(projection="mill", #miller est une projection connu llcrnrlat =0,#lower left corner latitude llcrnrlon =0, urcrnrlat =10, #upper right lat urcrnrlon =10, resolution = "l") #c croud par defaut, l low , h high , f full m.drawcoastlines() #dessiner les lignes m.drawcountries() m.drawstates() m.drawcounties(color="b") #m.fillcontinents() #colorier les payes #m.etopo() x,y=m(5,5) m.plot(x,y,"o") plt.show()
has comment: http://stackoverflow.com/comment/85274620
tagged with: matplotlib-basemap

http://stackoverflow.com/a/49190272
has comment: http://stackoverflow.com/comment/85386161
score: 1
answers question: http://stackoverflow.com/q/49190091
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has body: First get counts per groups by groupby with size and unstack, last join to second DataFrame: df1 = pd.DataFrame({'Company Name':list('aabcac'), 'Ethnicity':['American'] * 3 + ['Mexican'] * 3}) df1 = df1.groupby(['Company Name', 'Ethnicity']).size().unstack(fill_value=0) #slowier alternative #df1 = pd.crosstab(df1['Company Name'], df1['Ethnicity']) print (df1) Ethnicity American Mexican Company Name a 2 1 b 1 0 c 0 2 df2 = pd.DataFrame({'Company Name':list('abc')}) print (df2) Company Name 0 a 1 b 2 c df3 = df2.join(df1, on=['Company Name']) print (df3) Company Name American Mexican 0 a 2 1 1 b 1 0 2 c 0 2 EDIT: You need replace unit by 0 and convert to floats: print (df) Name sale 0 A 100M 1 B 200M 2 C 5M 3 D 40M 4 E 10B 5 F 2B d = {'M': '0'*6, 'B': '0'*9} df['a'] = df['sale'].replace(d, regex=True).astype(float).sort_values(ascending=False) print (df) Name sale a 0 A 100M 1.000000e+08 1 B 200M 2.000000e+08 2 C 5M 5.000000e+06 3 D 40M 4.000000e+07 4 E 10B 1.000000e+10 5 F 2B 2.000000e+09
accepted answer of: http://stackoverflow.com/q/49190091

http://stackoverflow.com/q/49139506
has title: (Django) Cannot update custom profile
upvote count: 0
type: UnansweredQuestion
has body: So I'm trying to update the user's info in an extended update, but it worked before I added the rest, but now it won't work I've tried going back still nothing. So it does send the post but it cannot validate it. Html &lt;form action="{% url 'userprofileupdate' logged_in_user.pk %}" method="POST"&gt; {% csrf_token %} https://pastebin.com/vMw6AEai (only Pastebin because of its a lot of code) Views.py @login_required def userprofileupdate(request, user_pk): if request.method == 'POST': form = UpdateProfileForm(request.POST, instance=request.user) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.extendeduser.nickname = form.cleaned_data.get('username') user.extendeduser.postal_code = form.cleaned_data.get('postal_code') user.extendeduser.phone_number = form.cleaned_data.get('phone_number') user.extendeduser.emergency_number = form.cleaned_data.get('emergency_number') user.extendeduser.birthdate = form.cleaned_data.get('birthdate') user.extendeduser.languages = form.cleaned_data.get('languages') user.extendeduser.drivers_licence = form.cleaned_data.get('drivers_licence') user.extendeduser.tshirt = form.cleaned_data.get('tshirt') user.extendeduser.special_considerations = form.cleaned_data.get('special_considerations') user.save() messages.success(request, "Your profile has been updated!") return redirect('usersettings', user_pk=request.user.pk) messages.error(request, 'Error: please update your settings if you want to update them') return redirect('usersettings', user_pk=request.user.pk) forms.py class UpdateProfileForm(forms.ModelForm): postal_code = forms.CharField(max_length=10, required=True) phone_number = forms.CharField(max_length=16, required=True) emergency_number = forms.CharField(max_length=16, required=True) birthdate = forms.DateField(required=False) languages = forms.MultipleChoiceField(required=False) drivers_licence = forms.MultipleChoiceField(required=False) tshirt = forms.ChoiceField(r…
has comment: http://stackoverflow.com/comment/85285096
tagged with: django
has answer: http://stackoverflow.com/a/49140335
has answer: http://stackoverflow.com/a/49172662
tagged with: django-views
answer count: 3
has answer: http://stackoverflow.com/a/49140105
downvote count: 1
tagged with: django-models
tagged with: python
has comment: http://stackoverflow.com/comment/85285773
score: -1
tagged with: django-forms
favorite count: 0
type: Question

bash
tags question: http://stackoverflow.com/q/49208779
tags question: http://stackoverflow.com/q/49222556
tags question: http://stackoverflow.com/q/49157570
tags question: http://stackoverflow.com/q/49246442
tags question: http://stackoverflow.com/q/49150036
tags question: http://stackoverflow.com/q/49203657
tags question: http://stackoverflow.com/q/49255634
tags question: http://stackoverflow.com/q/49201028
tags question: http://stackoverflow.com/q/49182304
type: Tag
tags question: http://stackoverflow.com/q/49191379
tags question: http://stackoverflow.com/q/49141025
tags question: http://stackoverflow.com/q/49232844
tags question: http://stackoverflow.com/q/49276552
tags question: http://stackoverflow.com/q/49241079
tags question: http://stackoverflow.com/q/49244779
tags question: http://stackoverflow.com/q/49204114
tags question: http://stackoverflow.com/q/49245355
tags question: http://stackoverflow.com/q/49176894
tags question: http://stackoverflow.com/q/49267233
tags question: http://stackoverflow.com/q/49147770
tags question: http://stackoverflow.com/q/49148281
tags question: http://stackoverflow.com/q/49142366
tag name: bash
tags question: http://stackoverflow.com/q/49242870
tags question: http://stackoverflow.com/q/49260693
tags question: http://stackoverflow.com/q/49140575
tags question: http://stackoverflow.com/q/49157243
tags question: http://stackoverflow.com/q/49223985
tags question: http://stackoverflow.com/q/49132360

http://stackoverflow.com/q/49242877
type: UnansweredQuestion
has body: I'm updating null line items in specific columns of a large csv file (~5GB) in the following way. Convert csv file to Pandas Dataframe If the required column in the dataframe has nulls, update it with specific values based on the values in a different column of the dataframe. Eg : In the following code, I'm checking if 'center' column has null values, if yes, update it with '0070' for all line items that have account column value as 'DNA' or 'BBA'. if df['center'].isnull().any().any() == True: df.loc[df.account.str.startswith('DNA') | df.account.str.startswith('BBA'), 'center'] = "0070" I'm obtaining the desired result by implementing the above, however since there are over 10 columns to check and update, this method is taking about 4-5 minutes to run on the entire dataset (~5GB). Is there a better way to improve code efficiency?
upvote count: 1
has title: Efficient way to update columns in csv file in Python
downvote count: 1
favorite count: 0
type: Question
tagged with: pandas
has comment: http://stackoverflow.com/comment/85490451
has comment: http://stackoverflow.com/comment/85493543
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85489786
score: 0
has comment: http://stackoverflow.com/comment/85490446
answer count: 0
has comment: http://stackoverflow.com/comment/85489574

http://stackoverflow.com/a/49274774
has body: The approach I present here is an awk one. In which I will make the following assumptions : The header-line Name (Roll no) ... Gender could appear multiple times The list under the header-line has a fixed field-width, but the fieldwidth is unknown. I assume this from the line with California in it, as that word only has a single space behind it. After each header-line, the fieldwidths can change. In awk we can set a fixed field width using the internal variable FIELDWIDTHS: FIELDWIDTHS # A space-separated list of columns that tells gawk how to split input with fixed columnar boundaries. Starting in version 4.2, each field width may optionally be preceded by a colon-separated value specifying the number of characters to skip before the field starts. Assigning a value to FIELDWIDTHS overrides the use of FS and FPAT for field splitting. See Constant Size for more information. note: this is a gawk extension To determine the FIELDWIDTHS variable, we will make use of match and RSTART: RSTART The start index in characters of the substring that is matched by the match() function (see String Functions). RSTART is set by invoking the match() function. Its value is the position of the string where the matched substring starts, or zero if no match was found. Thus this gives us already the following (note OFS is set to | to demonstrate the correct working behaviour) awk 'BEGIN{OFS="|"} /^[- A-Z]*$/{next} # skips only caps lines /Other records might/{next} # skips the last line /^Name.*$/{ # find header line match($0,"Location");i2=RSTART; match($0,"Section"); i3=RSTART; match($0,"Rank"); i4=RSTART; match($0,"Gender"); i5=RSTART; FIELDWIDTHS= i2-1" "i3-i2" "i4-i3" "i5-i4" 6" $0=$0 # reprocess header line # print header line only the first time if (v==0) {print $1,$2,$3,$4,$5} v++; next } {print $1,$2,$3,$4,$5}' This already outputs Name (Roll no) # |Location |Section |Rank (MARKS) |Gender Anna (+) |USA |A1 |First (100) |Female (04) |California |V|| Bob (-) |USA |A2 |First (99) |M…
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49271464
answers question: http://stackoverflow.com/q/49271464
type: Answer

http://stackoverflow.com/comment/85338419
type: QuestionComment
score: 0
has text: refer this > https://stackoverflow.com/questions/18552846/no-web-processes-running-django-in-heroku
type: Comment
comment on: http://stackoverflow.com/q/49166561

http://stackoverflow.com/comment/85464546
comment on: http://stackoverflow.com/q/49230489
score: 0
type: Comment
type: QuestionComment
has text: that i understood from the error, but i need to see it, maybe the error lies there

http://stackoverflow.com/a/49261841
type: Answer
score: 0
has body: If you prefer to doing group by by yourself, below is one option (not perfect solution). It uses one dict named index_cache to store the occurrences count of one key. Then leverage this dict to get the expected value when loop. import re test = ['A1,B2,C3,66','A1,B2,C3,00','A2, B2, C3, 77','A3, B3, C4, 44','A4, B4, C5, 11','A4, B4, C5, 12','A4, B4, C5, 13'] index_cache = {} #store all occurrences count for each key def prepare(data): formatted = re.split(',\s*', data.strip()) index_cache['-'.join(formatted[:3])] = 0 # init the count to 0 return formatted test1 = list(map(prepare, test)) for item in test1: index_cache['-'.join(item[:3])] += 1 item.append(index_cache['-'.join(item[:3])]) print (test1) Output: [['A1', 'B2', 'C3', '66', 1], ['A1', 'B2', 'C3', '00', 2], ['A2', 'B2', 'C3', '77', 1], ['A3', 'B3', 'C4', '44', 1], ['A4', 'B4', 'C5', '11', 1], ['A4', 'B4', 'C5', '12', 2], ['A4', 'B4', 'C5', '13', 3]] [Finished in 0.209s]
answers question: http://stackoverflow.com/q/49261197

http://stackoverflow.com/comment/85503712
type: AnswerComment
comment on: http://stackoverflow.com/a/49249769
has text: @CoXier Oops, those were supposed to be keyword arguments, not members of a dict; fixed. But anyway, I said that version is clumsy, and it's obviously a lot more verbose (and easy to get wrong, as I keep proving) than just using `format_map`, so why not do that?
type: Comment
score: 0

http://stackoverflow.com/q/49153115
has comment: http://stackoverflow.com/comment/85537299
score: 0
tagged with: spotipy
has body: I am writing a script using Spotipy that adds tracks to a Spotify playlist. I am using an example code from Github. import pprint import sys import spotipy import spotipy.util as util if len(sys.argv) &gt; 3: username = sys.argv[1] playlist_id = sys.argv[2] track_ids = sys.argv[3:] else: print("Usage: %s username playlist_id track_id ..." % (sys.argv[0],)) sys.exit() scope = 'playlist-modify-public' token = util.prompt_for_user_token(username, scope) if token: sp = spotipy.Spotify(auth=token) sp.trace = False results = sp.user_playlist_add_tracks(username, playlist_id, track_ids) print(results) else: print("Can't get token for", username) It works fine, the track is actually added, but I need to refresh the browser to be able to play it. Is it possible to update the playlist on the fly, while it is playing so that there is no need to interrupt the music?
tagged with: spotify
has title: Spotify: Playlist is not refreshed after adding a track via API
has comment: http://stackoverflow.com/comment/85310619
type: Question
has comment: http://stackoverflow.com/comment/85310777
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85543659

http://stackoverflow.com/comment/85491738
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49243303
has text: thank you! do you mind explaining this? formatted = "({0})-{1}-{2}".format(raw[:3], raw[3:6], raw[-4:])?

http://stackoverflow.com/comment/85536727
comment on: http://stackoverflow.com/a/49265939
score: 0
type: Comment
type: AnswerComment
has text: I don't think you can avoid it with the additional constraint about not adding code outside the docstring. You could also refactor this to be a deterministic function that takes the source of randomness as a parameter. `def get_now(now): return now()`

http://stackoverflow.com/comment/85364123
has text: Can you be more specific as to exactly when a new plot needs to be generated? What do you mean by appending to `figure(1)`? FYI `plt.show()` will display all figures.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49178618

http://stackoverflow.com/comment/85480281
type: Comment
score: 0
type: AnswerComment
has text: Unfortunately this solution gives duplicate outputs if list of tupel is long.
comment on: http://stackoverflow.com/a/49225960

http://stackoverflow.com/comment/85380910
type: Comment
type: QuestionComment
has text: This is related to superpixels and to max-trees. [Here is a recent paper about a Python toolbox for max-trees](https://www.sciencedirect.com/science/article/pii/S2352711017300079).
comment on: http://stackoverflow.com/q/49184710
score: 0

http://stackoverflow.com/comment/85459597
score: 0
type: AnswerComment
has text: So then its as simple as performing a database query for your proxy and plugging that in to the above code. What exactly are you having trouble with?
comment on: http://stackoverflow.com/a/49228010
type: Comment

http://stackoverflow.com/comment/106085761
has text: Using scikit-learn API might be necessary for compatibility reasons, and tis does not address the issue of unexpected keyword argument 'eval_metric' in fit method of the XGBClassifier object.
type: AnswerComment
score: 4
comment on: http://stackoverflow.com/a/49218608
type: Comment

http://stackoverflow.com/a/49253535
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85589675
upvote count: 1
has body: From pysnmp prospective you surely can: ... g = setCmd(SnmpEngine(), CommunityData('admin'), UdpTransportTarget((Device_IP, 161)), ContextData(), ObjectType(ObjectIdentity(main_Status_OID), Integer32(main_Status))), ObjectType(ObjectIdentity(Server_IP_OID), IpAddress(Server_IP))), ObjectType(ObjectIdentity(Status_OID), Integer32(Status)) ) next(g) Hopefully, your SNMP agent supports that as well.
accepted answer of: http://stackoverflow.com/q/49231101
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85543007
answers question: http://stackoverflow.com/q/49231101

http://stackoverflow.com/q/49171625
has comment: http://stackoverflow.com/comment/85348337
score: 2
tagged with: django-class-based-views
has title: Django form is still full after sign up
has answer: http://stackoverflow.com/a/49175275
has body: I have an app in django 1.11. Below is the view with the form where the user can sign up for the event, after saving he gets a message about the details - on the same page, at the same url. But, after saving the form is completed and after pressing F5 the next saving is performed. How can I avoid this? I think something with the form_valid method is wrong. class EventDetailView(DetailView, CreateView): model = models.Event form_class = forms.ParticipantForm context_object_name = 'event' template_name = 'events/event_detail.html' def get_success_url(self): return reverse('events:detail', kwargs={'slug': self.kwargs['slug'], 'pk': self.kwargs['pk']}) def form_valid(self, form): self.object = form.save() context = self.get_context_data() context['registered_event'] = context['event'] return self.render_to_response(context)
tagged with: forms
type: Question
tagged with: view
answer count: 2
has answer: http://stackoverflow.com/a/49171684
upvote count: 2
type: UnansweredQuestion
downvote count: 0
tagged with: django
tagged with: python
favorite count: 0

http://stackoverflow.com/a/50689104
type: Answer
has body: I put a navbar on each page of the app. I add it to the layout. like this: layout = html.Div(children=[ html.Nav(className = "nav nav-pills", children=[ html.A('App1', className="nav-item nav-link btn", href='/apps/App1'), html.A('App2', className="nav-item nav-link active btn", href='/apps/App2') ])... This is one of the children of the main div in my layout. Classes above are from bootstrap.css The Dash HTML components are all listed here. I just figured this out myself today, so I am still refining the css.
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/49265608
downvote count: 0

http://stackoverflow.com/a/49246079
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49245807
downvote count: 0
type: Answer
score: 4
type: AcceptedAnswer
has body: I found the solution here. canvas.yview_moveto( 1 ) appears to do nothing because I only call it once during setup. For the 'auto' scrolling to work, I need to call it each time the text grows.
answers question: http://stackoverflow.com/q/49245807

http://stackoverflow.com/a/49182387
type: AcceptedAnswer
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/49182288
type: Answer
has body: With reindex df_1['D']=df_2.reindex(df_1.index,method='nearest') df_1 Out[184]: A B C D 2017-01-01 00:01:00 1 4 7 ON 2017-01-01 00:02:00 2 5 8 ON 2017-01-02 00:01:00 3 6 9 OFF
answers question: http://stackoverflow.com/q/49182288
upvote count: 3

http://stackoverflow.com/q/49181480
linked to: http://stackoverflow.com/q/3675318
favorite count: 0
possible better answer: http://stackoverflow.com/a/49181610
type: AnsweredQuestion
has title: Replace ending of words with a new ending in python dataframe
has answer: http://stackoverflow.com/a/49181610
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49181979
score: 3
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49181797
type: Question
has answer: http://stackoverflow.com/a/49181797
upvote count: 3
has body: I have a Dataframe full of french words, endings and new endings. I want to create a 4th column with the alternative to the word as such: word |ending|new ending|what i want| -------------------------------------- placer |cer |ceras |placeras | placer |cer |cerait |placerait | placer |cer |ceront |placeront | finir |ir |iras |finiras | So it's basically to replace, in column 1, what's equivalent in column 2, by what I have in column 3. Any ideas ?
downvote count: 0
tagged with: string
tagged with: text-mining

http://stackoverflow.com/a/58071119
answers question: http://stackoverflow.com/q/49123439
has comment: http://stackoverflow.com/comment/118477920
downvote count: 0
upvote count: 12
score: 12
has comment: http://stackoverflow.com/comment/102573567
has comment: http://stackoverflow.com/comment/110595160
type: Answer
has body: Following the excellent answer from @falsetru, I wrote out a quick generalization in the form of a decorator. import os from multiprocessing import Process def detachify(func): """Decorate a function so that its calls are async in a detached process. Usage ----- .. code:: import time @detachify def f(message): time.sleep(5) print(message) f('Async and detached!!!') """ # create a process fork and run the function def forkify(*args, **kwargs): if os.fork() != 0: return func(*args, **kwargs) # wrapper to run the forkified function def wrapper(*args, **kwargs): proc = Process(target=lambda: forkify(*args, **kwargs)) proc.start() proc.join() return return wrapper Usage (copied from docstring): import time @detachify def f(message): time.sleep(5) print(message) f('Async and detached!!!') Or if you like, def f(message): time.sleep(5) print(message) detachify(f)('Async and detached!!!')

http://stackoverflow.com/comment/85291219
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49142826
type: Comment
has text: Assuming R can load the entire file, then the file size isn't really the big issue, but rather how you answer your questions.

http://stackoverflow.com/comment/85522459
has text: You can just use `f.seek(0)` to reset the file pointer in stead of reopening the file.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49259470
score: 1

http://stackoverflow.com/q/49266877
has answer: http://stackoverflow.com/a/49267109
tagged with: apache
has title: python flask apache import
accepted answer: http://stackoverflow.com/a/49267109
type: Question
tagged with: python
tagged with: flask
type: AnsweredQuestion
upvote count: 0
downvote count: 2
tagged with: mod-wsgi
answer count: 1
favorite count: 0
has body: hello i want to run a flask app on apache2 virtualhost with mod_wsgi please see gist i can import the module from python if im in /srv/http/dashboard and use python command and then from SonntagDashboard import app https://gist.github.com/anonymous/0a22904852172526394f3da9c3feed8b running python3.6 and apache 2.4 on manjaro (arch) linux
score: -2

http://stackoverflow.com/comment/89145508
has text: soo true, buffer will always have finite size, the issue that was putting in it loop was not allowing me to read from where last recv()left.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49192701
type: Comment

http://stackoverflow.com/comment/85446089
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49221230
type: Comment
has text: I tried to make it more clear

http://stackoverflow.com/a/49240110
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49239916
has body: This should help: import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) trainX = a.reshape(1, 2, 3) # [[[1 2 3] [4 5 6]]]
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49267891
downvote count: 0
has body: Your datetimes are, for some odd reason, encoded into a float, using a rule that looks something like this: year * 1e6 + month * 1e4 + day * 1e2 + hour So, you can decode it by just reversing that arithmetic. It might be cleaner to convert to an int first, to avoid any rounding issues. So, something like this: ymdh = int(f) y, mdh = divmod(ymdh, 1000000) m, dh = divmod(mdh, 1000) d, h = divmod(dh, 10) You can, of course, make that more concise, but I wanted to make it as easy to understand as possible. This has the (questionable) advantage that you can do it across the entire array at once: ymdh = np.astype(f, np.int) y, mdh = divmod(ymdh, 1000000) m, dh = divmod(mdh, 1000) d, h = divmod(dh, 10) At the end, you've got four separate y, m, d, and h arrays; you can stack them up, or convert them into an array of structs, or just zip them to feed one by one to a normal Python function like datetime.datetime. The other alternative is to convert it to a string and then use the same string date-parsing code you've found in other answers. The only trick here is that the numbers are in scientific format, so you have a few extra characters to get rid of. Something like this: s = str(f).translate({c: None for c in '.E+'}) And now you've just got digits YYYYMMDDHH, which are easy.
accepted answer of: http://stackoverflow.com/q/49267837
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49267837
has comment: http://stackoverflow.com/comment/85539323
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/a/49213754
answers question: http://stackoverflow.com/q/49212905
has comment: http://stackoverflow.com/comment/85535129
has comment: http://stackoverflow.com/comment/85522236
has body: You have to split 201803 in to year and month.Then you can query it using below query TestModel.objects.filter(date__year=2018,date__month=03) Here is the documentation link.
type: Answer
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49212905
score: 3
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/a/60105390
has body: Assuming your structure is no more than 10 deep: [article_list depth:10] Put this in your root article.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49166496

http://stackoverflow.com/comment/85463929
score: 1
has text: As a side note: When using WIndows paths as literal strings, you should always use raw strings, like `r'F:\Brass\*.aif'` instead of plain strings, lik `'F:\Brass\*.aif'`. In your case, it just happens to be true that none of the backslash-sequences like `'\S'` are special escapes, and in Python (but not in many other languages) that means everything just works. But as soon as you add some more paths, you're going to hit one that is a special escape, and that's never fun to debug. If you start off with raw strings, the problem never comes up.
type: Comment
comment on: http://stackoverflow.com/q/49229666
type: QuestionComment

http://stackoverflow.com/comment/85357057
comment on: http://stackoverflow.com/a/49163070
has text: @Parseltongue No problem. Good luck with your project. :-)
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85269685
score: 0
comment on: http://stackoverflow.com/q/49132360
type: Comment
type: QuestionComment
has text: @matteo, if I delete the first line, nothing happens when I Execute. Can you tell me more about your second solution ?

http://stackoverflow.com/comment/85322391
comment on: http://stackoverflow.com/a/49158389
type: Comment
has text: While this code may answer the question, providing additional context regarding how and why it solves the problem would improve the answer's long-term value.
score: 2
type: AnswerComment

http://stackoverflow.com/q/49172824
has answer: http://stackoverflow.com/a/49173003
tagged with: python-datetime
tagged with: datetime
tagged with: python
score: 4
upvote count: 4
type: AnsweredQuestion
answer count: 2
tagged with: pandas
downvote count: 0
accepted answer: http://stackoverflow.com/a/49172855
linked to: http://stackoverflow.com/q/35052691
has title: Pandas how to filter DataFrame on time period
favorite count: 0
has answer: http://stackoverflow.com/a/49172855
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49173003
has body: I have a file with the below table: Name AvailableDate totalRemaining 0 X3321 2018-03-14 13:00:00 200 1 X3321 2018-03-14 14:00:00 200 2 X3321 2018-03-14 15:00:00 200 3 X3321 2018-03-14 16:00:00 200 4 X3321 2018-03-14 17:00:00 193 I wanted to return a DataFrame with all the records in a specific time period regardless of the actual date. I followed the example here: filter pandas dataframe by time but when I execute the below: ## setup import pandas as pd import numpy as np ### Step 2 ### Check available slots file2 = r'C:\Users\user\Desktop\Files\data.xlsx' slots = pd.read_excel(file2,na_values='') ## filter the preferred ones slots['nextAvailableDate'] = pd.to_datetime((slots['nextAvailableDate'])) slots['times'] = pd.to_datetime((slots['nextAvailableDate'])) slots = slots[slots['times'].between('21:00:00', '02:00:00')] This returns empty DataFrame as well as this solution: slots = slots[slots['times'].dt.strftime('%H:%M:%S').between('21:00:00', '02:00:00')] Is there a way to do it correctly without creating a columns for time separately? How I should approach this problem please? My goal: Name AvailableDate totalRemaining 0 X3321 2018-03-14 21:00:00 200 1 X3321 2018-03-14 22:00:00 200 2 X3321 2018-03-14 23:00:00 200 3 X3321 2018-03-14 00:00:00 200 4 X3321 2018-03-14 01:00:00 193 for every day that appears in the data set.

http://stackoverflow.com/comment/85517727
score: 2
comment on: http://stackoverflow.com/q/49257222
type: Comment
type: QuestionComment
has text: Did you try `self.value=sim.strip()` ?

http://stackoverflow.com/comment/85537159
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49266583
has text: Thank you, exactly what I needed!
score: 0

http://stackoverflow.com/a/49239470
upvote count: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49238992
downvote count: 0
has comment: http://stackoverflow.com/comment/85483398
accepted answer of: http://stackoverflow.com/q/49238992
type: Answer
score: 4
has body: You can utilize a deque for this and specify its maxlen to n: from collections import deque def tail(iterable, n): if n &lt; 0: return [] else: return deque(iterable, n) wrap the return in a list call to get the result back as a list if needed. The deque does not create an intermediate list out of the iterator thereby keeping the space complexity down.

http://stackoverflow.com/q/49150187
tagged with: python
has comment: http://stackoverflow.com/comment/85375086
answer count: 1
has comment: http://stackoverflow.com/comment/85305108
favorite count: 0
has comment: http://stackoverflow.com/comment/85305074
type: Question
tagged with: pandas
score: 3
tagged with: datetime
has title: How to keep dtype when converting a dataframe into a numpy array?
tagged with: datetime64
has comment: http://stackoverflow.com/comment/85308571
tagged with: numpy
has comment: http://stackoverflow.com/comment/85304634
accepted answer: http://stackoverflow.com/a/49155554
type: AnsweredQuestion
upvote count: 3
has answer: http://stackoverflow.com/a/49155554
has body: I have a dataframe and want to convert it into a numpy array to plot its values. The dataframe looks like this: &gt;&gt;&gt; df_ohlc open high low close Date 2018-03-07 03:35:00 62.189999 62.189999 62.169998 62.180000 2018-03-07 03:36:00 62.180000 62.180000 62.160000 62.180000 2018-03-07 03:37:00 62.169998 62.220001 62.169998 62.209999 2018-03-07 03:38:00 62.220001 62.220001 62.189999 62.200001 ... [480 rows x 4 columns] &gt;&gt;&gt; df_ohlc.index DatetimeIndex(['2018-03-07 03:35:00', '2018-03-07 03:36:00', '2018-03-07 03:37:00', '2018-03-07 03:38:00', '2018-03-07 03:39:00', '2018-03-07 03:40:00', '2018-03-07 03:41:00', '2018-03-07 03:42:00', '2018-03-07 03:43:00', '2018-03-07 03:44:00', ... '2018-03-07 11:25:00', '2018-03-07 11:26:00', '2018-03-07 11:27:00', '2018-03-07 11:28:00', '2018-03-07 11:29:00', '2018-03-07 11:30:00', '2018-03-07 11:31:00', '2018-03-07 11:32:00', '2018-03-07 11:33:00', '2018-03-07 11:34:00'], dtype='datetime64[ns]', name='Date', length=480, freq='T') &gt;&gt;&gt; df_ohlc.index[0] Timestamp('2018-03-07 03:35:00', freq='T') # and why is it Timestamp when it said ```dtype=datetime64[ns]```` right before? But when I try to convert it, the index type(Date column) changes from datetime64[ns] to Timestamp. &gt;&gt;&gt; df_ohlc.reset_index().values array([[Timestamp('2018-03-07 03:35:00'), 62.189998626708984, 62.189998626708984, 62.16999816894531, 62.18000030517578], [Timestamp('2018-03-07 03:36:00'), 62.18000030517578, 62.18000030517578, 62.15999984741211, 62.18000030517578], [Timestamp('2018-03-07 03:37:00'), 62.16999816894531, 62.220001220703125, 62.16999816894531, 62.209999084472656], ..., [Timestamp('2018-03-07 11:32:00'), 61.939998626708984, 61.95000076293945, 61.93000030517578, 61.93000030517578], [Timestamp('2018-03-07 11:33:00'), 61.93000030517578, 61.939998626708984, 61.900001525878906, 61.90999984741211], [Timestamp('2018-03-07 11:34:00'), 61.90999984741211, 61.91999816894531, 61.900001525878906, 61.91999816894531]], dtype=object) Why do…
downvote count: 0

http://stackoverflow.com/comment/85554973
type: QuestionComment
comment on: http://stackoverflow.com/q/49255141
score: 0
has text: Thanks again, it appears that C=256 is being set by the final convolutional layer in the critic network. But now if I change it to 48 such that the previous matrix multiplication ought to work, I get the error in the next comment. The critic and generator .summaries are above.
type: Comment

http://stackoverflow.com/comment/115680747
type: Comment
has text: Will this work if the worker/slave lambda is invoked in a loop so that multiple instances are running concurrently? Could I use the same client to invoke a lambda multiple times asynchronously, or would i need to dynamically create boto3 clients to do so?
comment on: http://stackoverflow.com/a/50034121
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85542424
type: QuestionComment
has text: try `x=dark_IV["Dark IV:V"].values.tolist()` `y=dark_IV["Dark IV:I"].values.tolist()`
comment on: http://stackoverflow.com/q/49269631
score: 0
type: Comment

http://stackoverflow.com/a/49185162
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49185032
type: Answer
has body: You can use numpy select instead of np.where cond = [df['x'].between(df['lbound'], df['rbound']), (df['x'] &lt; df['lbound']) , df['x'] &gt; df['rbound'] ] output = [ 'middle', 'left', 'right'] df['area'] = np.select(cond, output, default=np.nan) lbound rbound x area 0 -1 1 0 middle 1 5 7 1 left 2 0 1 2 right
score: 2

http://stackoverflow.com/q/49147996
possible better answer: http://stackoverflow.com/a/49148066
downvote count: 0
accepted answer: http://stackoverflow.com/a/49148056
has title: Explode column of list to multiple rows
has answer: http://stackoverflow.com/a/49148066
has answer: http://stackoverflow.com/a/49148056
has comment: http://stackoverflow.com/comment/85314900
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85308428
linked to: http://stackoverflow.com/q/38203352
upvote count: 8
has body: I want to expand the list in a certain column (in the example column_x) to multiple rows. So df = pd.DataFrame({'column_a': ['a_1', 'a_2'], 'column_b': ['b_1', 'b_2'], 'column_x': [['c_1', 'c_2'], ['d_1', 'd_2']] }) shall be transformed from column_a column_b column_x 0 a_1 b_1 [c_1, c_2] 1 a_2 b_2 [d_1, d_2] to column_a column_b column_x 0 a_1 b_1 c_1 1 a_1 b_1 c_2 2 a_2 b_2 d_1 3 a_2 b_2 d_2 The code I have so far does exactly this, and it does it fast. lens = [len(item) for item in df['column_x']] pd.DataFrame( {"column_a" : np.repeat(df['column_a'].values, lens), "column_b" : np.repeat(df['column_b'].values, lens), "column_x" : np.concatenate(df['column_x'].values)}) However, I have lots of columns. Is there a neat and elegant solution for repeating the whole data frame without specifying each column again?
tagged with: dataframe
tagged with: python
score: 8
type: AnsweredQuestion
tagged with: list
answer count: 2
tagged with: pandas

pygame
tags question: http://stackoverflow.com/q/49147413
tags question: http://stackoverflow.com/q/49234606
tag name: pygame
tags question: http://stackoverflow.com/q/49237363
tags question: http://stackoverflow.com/q/49264272
tags question: http://stackoverflow.com/q/49214690
tags question: http://stackoverflow.com/q/49210083
tags question: http://stackoverflow.com/q/49208378
tags question: http://stackoverflow.com/q/49163666
tags question: http://stackoverflow.com/q/49175584
tags question: http://stackoverflow.com/q/49139855
tags question: http://stackoverflow.com/q/49209139
tags question: http://stackoverflow.com/q/49258019
tags question: http://stackoverflow.com/q/49221315
tags question: http://stackoverflow.com/q/49128041
tags question: http://stackoverflow.com/q/49238123
tags question: http://stackoverflow.com/q/49203133
tags question: http://stackoverflow.com/q/49185370
tags question: http://stackoverflow.com/q/49224336
tags question: http://stackoverflow.com/q/49165454
tags question: http://stackoverflow.com/q/49248838
tags question: http://stackoverflow.com/q/49246689
tags question: http://stackoverflow.com/q/49243612
tags question: http://stackoverflow.com/q/49165440
tags question: http://stackoverflow.com/q/49138561
tags question: http://stackoverflow.com/q/49212051
tags question: http://stackoverflow.com/q/49211084
tags question: http://stackoverflow.com/q/49227851
type: Tag

math
tags question: http://stackoverflow.com/q/49202497
tags question: http://stackoverflow.com/q/49219603
tags question: http://stackoverflow.com/q/49156075
tags question: http://stackoverflow.com/q/49121458
tags question: http://stackoverflow.com/q/49223294
type: Tag
tags question: http://stackoverflow.com/q/49126090
tags question: http://stackoverflow.com/q/49184033
tags question: http://stackoverflow.com/q/49228144
tags question: http://stackoverflow.com/q/49205577
tags question: http://stackoverflow.com/q/49227843
tags question: http://stackoverflow.com/q/49200609
tag name: math
tags question: http://stackoverflow.com/q/49166156

http://stackoverflow.com/q/49180178
tagged with: python
type: AnsweredQuestion
tagged with: pandas
tagged with: pivot
score: 3
upvote count: 3
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has body: I'm new to python/pandas. I'm trying to transpose rows to columns.Apologies for any misunderstanding input_df(pic) output_df(pic) input_df: Date Project Processes Time_in_sec Time_measures ----------------------------------------------------------------------- 7/6/2017 FE eBanking .aspx 157 Average Response Time 9/2/2017 PCB eBanking Frontpage.fi 227 Call per hour 1/23/2017 ICC Acct Transfer.dc 28 Average Response Time 1/24/2017 PCB Transaction .com 0 Number of calls 1/23/2017 ICC eBanking Logon.no 0 Number of calls output_df: Date Project Processes Average Response Time Call per hour Number of calls ----------------------------------------------------------------------------- 7/6/2017 FE eBanking .aspx 157 9/2/2017 PCB eBanking Frontpage.fi 227 1/24/2017 PCB Transaction .com 0 1/23/2017 ICC Acct Transfer.dc 28 1/23/2017 ICC eBanking Logon.no 0 I tried the below code and got only 3 Columns 'Average Response Time','Call per hour' 'Number of calls' in the output below_code's_output. But I'm confused how to get all the necessary 6 columns. Could you please help? output_df = input_df.pivot(columns = 'Time_measures', values= 'Time_in_sec')
accepted answer: http://stackoverflow.com/a/49180235
has answer: http://stackoverflow.com/a/49180235
has title: Python / Pandas - Pivot on multidimensional data
tagged with: reshape

http://stackoverflow.com/a/49161940
has comment: http://stackoverflow.com/comment/85333819
has comment: http://stackoverflow.com/comment/85332831
downvote count: 0
upvote count: 4
answers question: http://stackoverflow.com/q/49161783
type: Answer
has body: The returned row you are printing is a pyodbc.Row object, similar to a Python tuple, with all values returned by the query. For the first element in the pyodbc.Row, try print(row[0]). If you had more than one value returned in the row, it might appear as: &gt;&gt;&gt; print(row) ('29.99', '19.99', '0.99') Then these values could be addressed as row[0], row[1], and row[2].
score: 4

http://stackoverflow.com/q/49268359
has comment: http://stackoverflow.com/comment/85540170
downvote count: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49269813
has answer: http://stackoverflow.com/a/54717411
has title: Scrape Google Quick Answer Box in Python
tagged with: web-scraping
tagged with: python
tagged with: python-requests
has body: I am very new to Python programming and I am trying to make a simple application. What I'm trying to do is search for a text on Google and return the links, my program does this fine. The other thing is if Google has the quick answer like in the photo below, I want to grab it, and this is where my problem lies. I tried searching online and found very few topics in which none of the codes work. Google Quick box answer: By examining the code of many pages I noticed that the answer is always in a class called _XWk but in Python when I get the code of the page and search for this class it doesn't find it. I tried so many ways of scraping the page in Python, but it never gets this class and I think the code it gets is less than the code the browser shows me when I open page source code. Class _XWk: Code: import requests, lxml from bs4 import BeautifulSoup url = 'https://www.google.com/search?q=when%20was%20trump%20born' h = {"User-Agent":"Chrome/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36"} r = requests.get(url, headers=h).text soup = BeautifulSoup(r,'lxml') soup.find_all("div", class_="_xwk") print (soup) Any help is appreciated.
score: 4
possible better answer: http://stackoverflow.com/a/66986773
accepted answer: http://stackoverflow.com/a/49269813
linked to: http://stackoverflow.com/q/31798009
has answer: http://stackoverflow.com/a/66986773
type: AnsweredQuestion
answer count: 3
upvote count: 5

http://stackoverflow.com/comment/85540382
has text: Exactly. `scipy.signal.correlate` should do the same job without rotating each kernel.... or you can rotate the kernel yourself and let `convolve` undo the rotation. Either way... but this is the correct answer. Have a vote from me. I was about to write the answer and you beat me to it.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49268494

http://stackoverflow.com/a/59622352
answers question: http://stackoverflow.com/q/49157120
score: 1
has body: replace "base_name" to "basename"
downvote count: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/85321749
type: Comment
type: AnswerComment
has text: The thing is that the script1.py logic is much complicate than the one shown here. That's why I didn't want to put the logic into a function, but you are right, that must be the best solution. Thanks!
comment on: http://stackoverflow.com/a/49158187
score: 0

http://stackoverflow.com/comment/85461310
has text: Basically, I thought if you want to use a function from a module, you have to mention the name of the module before the function.
type: Comment
comment on: http://stackoverflow.com/a/49227687
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85386892
score: 0
type: Comment
has text: You may update the `prefix` field before get the next sequence number
type: QuestionComment
comment on: http://stackoverflow.com/q/49187779

http://stackoverflow.com/comment/85325127
has text: You think like this: `finalList = list() for i in range(len(flag)): if flag[i] == 1: finalList.append(d[i]) `
type: Comment
comment on: http://stackoverflow.com/a/49158290
type: AnswerComment
score: 0

http://stackoverflow.com/q/49273858
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49274196
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/49274196
tagged with: django-rest-framework
score: 8
favorite count: 0
type: Question
upvote count: 8
tagged with: django
tagged with: javascript
has title: How can axios get the status code in .catch()?
tagged with: python
tagged with: axios
has body: In the Axios document: axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); }); we know we can catch the error in the .catch() method. But when I use the Django-Rest-Framework as the backend API provider. it only provide the data, there is no status in it: You see the error: {username: ["A user with that username already exists."]} but in the browser, we can know the status code: Before asking this question, I have read How can I get the status code from an http error in Axios? this post. But the post seems different with mine. EDIT-1 In my Django-Rest-Framework project: the view: class UserCreateAPIView(CreateAPIView): serializer_class = UserCreateSerializer permission_classes = [AllowAny] queryset = User.objects.all() the serializer: class UserCreateSerializer(ModelSerializer): """ user register """ class Meta: model = User fields = [ 'username', 'wechat_num', 'password', ] extra_kwargs = { "password":{"write_only":True} } def create(self, validated_data): username=validated_data.pop('username') wechat_num = validated_data.pop('wechat_num') password=validated_data.pop('password') user_obj = User( username=username, wechat_num=wechat_num, ) user_obj.set_password(password) user_obj.save() group=getOrCreateGroupByName(USER_GROUP_CHOICES.User) user_obj.groups.add(group) return validated_data
linked to: http://stackoverflow.com/q/39153080

http://stackoverflow.com/a/49231797
answers question: http://stackoverflow.com/q/49230658
type: AcceptedAnswer
downvote count: 1
type: Answer
has body: I finally figured out and surprisingly the answer is a simple one. Answer: I just have to pass the style attribute parameter containing the customized style names that I want to use to the other classes that needs to use those style names. In my script, the attribute parameter that needs to be passed is self.style. Hope this answer helps others with the same need. #!/usr/bin/python3 # -*- coding: utf-8 -*- # tkinter modules import tkinter as tk import tkinter.ttk as ttk import tkinter.font as tkFont class App(ttk.Frame): def __init__(self, parent=None, *args, **options): # Extract key and value from **options using Python3 "pop" function: # pop(key[, default]) self.style = options.pop('style',ttk.Style()) self.bg0 = options.pop('background1','light grey') self.bg1 = options.pop('background2','grey') self.fg0 = options.pop('fg_link','black') self.fg1 = options.pop('fg_text','white') self.font = options.pop('font',tkFont.Font(family='Nimbus Roman No9 L', size='10', weight='normal')) # Initialise App Frame ttk.Frame.__init__(self, parent, style='self.TFrame') self.__setFont() self.__setStyle() self.__createPages(parent) def __setFont(self): """Set the fonts to be used to build the App GUI.""" self.fontTitle = self.font.copy() self.fontTitle.config(size='30') self.font.config(size='13') def __setStyle(self): """Customise ttk styles""" ## LoginPanel styles self.style.configure('self.TFrame', background='pink') self.style.configure('page.TFrame', background=self.bg0) self.style.configure('press.TButton', font=self.fontTitle, background=self.bg1, foreground=self.fg0, relief='raised') def __createPages(self, parent): """Create Login and NewUser pages.""" self._frames = {} for F in (Page1, Page2): page_name = F.__name__ frame = F(parent=self, style=self.style) #pass style attribute self._frames[page_name] = frame frame.grid(row=0, column=0, sticky="nsew") self.showFrame("Page1") parent.rowconfigure(0, weight=1) parent.columnconfigure(0, weight=1) def showFrame(self, page_nam…
score: -1
accepted answer of: http://stackoverflow.com/q/49230658
upvote count: 0

simplex-noise
type: Tag
tags question: http://stackoverflow.com/q/49207354
tag name: simplex-noise

http://stackoverflow.com/comment/85394021
comment on: http://stackoverflow.com/a/49183669
has text: please use `inplace=True` if you don't want a copy. Please read the [documentation](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.set_names.html)
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49194234
type: AcceptedAnswer
downvote count: 0
score: 6
type: Answer
accepted answer of: http://stackoverflow.com/q/49194107
upvote count: 6
answers question: http://stackoverflow.com/q/49194107
has body: &gt;&gt;&gt; listofpeople = [{'Jack': ['Blue', 'Red', 'Green']}, {'Barry': ['Red', 'Green', 'Orange']}] &gt;&gt;&gt; [i for i, d in enumerate(listofpeople) if "Jack" in d.keys()] [0]

http://stackoverflow.com/comment/85284753
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49139661
score: 0
has text: OP just needs to test `if len(my_history) > 1 and len(their_history) > 1` once.

http://stackoverflow.com/a/49195507
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
has body: You can try something like this in your dataset, using cumsum. m=7 df_test['mid_month_id'] = m+(df.day_of_month == 14).cumsum() print(m + (df.day_of_month == 14).cumsum()) Output: 0 7 1 7 2 8 3 8 4 8 5 8 6 9 7 9 Name: day_of_month, dtype: int32
answers question: http://stackoverflow.com/q/49195188
has comment: http://stackoverflow.com/comment/85396930
type: Answer
accepted answer of: http://stackoverflow.com/q/49195188

ngrok
tag name: ngrok
tags question: http://stackoverflow.com/q/49129451
type: Tag

http://stackoverflow.com/q/49211607
has answer: http://stackoverflow.com/a/49211706
has answer: http://stackoverflow.com/a/49211623
has title: Python Equivalent of MATLAB's colon operator
tagged with: vector
type: UnansweredQuestion
has body: In MATLAB I can create monotonically spaced vectors as in the examples below using the :, colon, operator. How can I do this in Python in a similarly concise manner? &gt;&gt; x=1:10 x = 1 2 3 4 5 6 7 8 9 10 or &gt;&gt; x=0:2:10 x = 0 2 4 6 8 10
tagged with: python
score: 4
upvote count: 4
tagged with: matlab
has comment: http://stackoverflow.com/comment/85528893
has comment: http://stackoverflow.com/comment/85427717
answer count: 3
downvote count: 0
has answer: http://stackoverflow.com/a/49211825
has comment: http://stackoverflow.com/comment/85526464
favorite count: 0
type: Question

http://stackoverflow.com/q/49148036
type: Question
has body: Is there a way I can hide a password in python shell?, like showing dots. This is for an input for a login in a python program. getpass shows this: Warning (from warnings module): File "C:\Python34\lib\getpass.py", line 101 return fallback_getpass(prompt, stream) GetPassWarning: Can not control echo on the terminal. Warning: Password input may be echoed. Enter your password: hammad hammad The password is visible, and I have my own python script for getting a user name and then the password, using a database to check if account exists.
answer count: 3
score: 1
downvote count: 1
has answer: http://stackoverflow.com/a/51519534
favorite count: 0
has answer: http://stackoverflow.com/a/49148126
upvote count: 2
tagged with: python
type: UnansweredQuestion
has title: Python, hiding password in the shell
tagged with: passwords
has answer: http://stackoverflow.com/a/49148100

http://stackoverflow.com/q/49134141
has comment: http://stackoverflow.com/comment/85275073
accepted answer: http://stackoverflow.com/a/49141154
score: 1
has answer: http://stackoverflow.com/a/49141154
tagged with: python
has title: How do I reference an object property in a method call in Jinja2?
type: AnsweredQuestion
tagged with: flask-wtforms
downvote count: 0
answer count: 1
upvote count: 1
tagged with: flask
tagged with: jinja2
has body: I am trying to render a form in a flask app using jinja2 and flask-wtf, but am having trouble figuring out how to handle adding a generated argument for onclick that contains a property as part of it's argument. You can see in the form label section I have onclick set to call a javascript function and pass the name property of the current loop object and this works as intended. However when I am in the form field section, I need to pass onclick to the loop object as a key word argument, and need to make the argument of my argument the object name property. This doesn't work. Here is a shortened example: {% for entry_field in form %} {{ entry_field.label() }} {{ entry_field(onclick="jsFunction({{entry_field.name}})}} {% endfor %} Here is a full example: {{ form.csrf_token }} {% for entry_field in form %} {% if entry_field != form.csrf_token %} {{ entry_field.label(class="col-sm-3 col-form-label") }} {{ entry_field(class_="form-control", onclick="showNotes('{{entry_field.name}}')") }} {% for error in entry_field.errors %}{{ error }}{% endfor %} {% endif %} {% endfor %} Greatly appreciate any help!
has comment: http://stackoverflow.com/comment/85273479
favorite count: 0
type: Question

http://stackoverflow.com/comment/85492002
has text: How are you appending the new item? Are you calling `append`? Calling `append` would behave very differently from performing the assignment `list_1 = ["apples", "apricots", "oranges", "berries"]`.
comment on: http://stackoverflow.com/q/49244003
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49193097
tagged with: python-requests
favorite count: 0
has body: I am a newbie to Python. I am trying to write a Python script to get some JSON data. The Linux shell command is as below and it works perfectly when fired form shell:- curl -H "X-ApiKeys: accessKey={accessKey}; secretKey={secretKey}" https://example.com/example/api/v1/example/list Below is the Python script as far as I have reached till now and got stuck and absolutely no idea what to do next. import requests import ConfigParser import json Config = ConfigParser.ConfigParser() Config.read('C:/Users/admin/source/repos/MyProject/MyProject/config.ini') Username = Config.get('credentials', 'Username') Password = Config.get('credentials', 'Password')
type: AnsweredQuestion
has title: Get request with Access and Secret Key
has comment: http://stackoverflow.com/comment/85396531
has comment: http://stackoverflow.com/comment/85390925
has answer: http://stackoverflow.com/a/49197126
tagged with: python
has comment: http://stackoverflow.com/comment/85398539
type: Question
score: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49197126
tagged with: api
answer count: 1
downvote count: 0

geotagging
tag name: geotagging
tags question: http://stackoverflow.com/q/49126700
type: Tag

http://stackoverflow.com/comment/85294003
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49138692
has text: Possible duplicate of [What's the advantage of a trailing underscore in Python naming?](https://stackoverflow.com/questions/21075208/whats-the-advantage-of-a-trailing-underscore-in-python-naming)

http://stackoverflow.com/comment/85466022
score: 0
comment on: http://stackoverflow.com/q/49231322
has text: You can use a virtualenv.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49131605
has comment: http://stackoverflow.com/comment/134322708
has comment: http://stackoverflow.com/comment/135066985
answers question: http://stackoverflow.com/q/49131578
has comment: http://stackoverflow.com/comment/134315957
has body: Just use or for equivalent logic: path = output_directory or '.'
score: 7
type: Answer
upvote count: 11
has comment: http://stackoverflow.com/comment/135119985
downvote count: 4

http://stackoverflow.com/comment/85526514
type: Comment
comment on: http://stackoverflow.com/a/49261381
score: 0
type: AnswerComment
has text: Thanks not exactly what I needed but was able to amend it to get what I needed.

http://stackoverflow.com/comment/85539451
comment on: http://stackoverflow.com/a/49268022
score: 1
type: Comment
type: AnswerComment
has text: `my_list` is defined in the scope of the `print_list()` function, however it is empty. If it was not defined, there would be an error.

http://stackoverflow.com/q/49219050
accepted answer: http://stackoverflow.com/a/49219176
answer count: 1
has answer: http://stackoverflow.com/a/49219176
type: Question
tagged with: gunicorn
tagged with: python
tagged with: flask
has title: Docker+Gunicorn+Flask, I don't understand why my setup is not working
has body: I'm trying to build a simple application with flask and I've decided to also use gunicorn and docker. At the moment I have this configuration: &gt; app &gt; myapp __init__.py index.html docker-compose.yml Dockerfile My docker-compose.yml: version: '2' services: web: build: . volumes: - .:/app command: /usr/local/bin/gunicorn -b :8000 myapp:app working_dir: /app My __init__.py: import os from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run() This minimal configuration works and I'm able to access my application and get my index page. What I don't like is having my app created inside the __init__.py so I would like to move the app creation inside an app.py file. The new structure will be: &gt; app &gt; myapp __init__.py app.py index.html docker-compose.yml Dockerfile app.py will have the content of the old __init__.py file and the new __init__.py file would be empty. This doesn't work. I get an error Failed to find application: 'myapp' and I don't understand why. Any idea about this?
tagged with: docker
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85441778
tagged with: docker-compose
has comment: http://stackoverflow.com/comment/85441796

http://stackoverflow.com/comment/85382681
type: QuestionComment
has text: Relevant part of HTML is needed to answer your question. To be honest I don't understand your question, what result are you looking for, are there any problems with your code, is there an exception thrown?
comment on: http://stackoverflow.com/q/49188515
score: 0
type: Comment

http://stackoverflow.com/comment/85445422
comment on: http://stackoverflow.com/q/49220973
type: Comment
type: QuestionComment
score: 2
has text: That's because there is no variable `Choice` in the `main()` function. Assign to one, perhaps from the return value of the `choice()` function. Names in other functions are just local to that function: `Choice = choice()`.

http://stackoverflow.com/q/49224385
has comment: http://stackoverflow.com/comment/85455806
has title: Django-Rest: Serialising ListField() - '_TaggableManager' object is not iterable
has body: My goal is to add tags to a post. I'm using latest taggit (Requirement: Django-Taggit https://github.com/alex/django-taggit ) and DRF. Goal: To pop tags only from posted request. For each tag in the post request to call post.tags.add("tag1","tag2") to add these tags to the model. Currently, my post serialiser is: class PostSerializer(serializers.ModelSerializer): tags = serializers.ListField( child=serializers.CharField(min_length=0, max_length=30) ) ... def create(self, validated_data): pub.set_trace() tags_data = validated_data.pop('tags') # Need to pop tags only # to_be_tagged, validated_data = self._pop_tags(validated_data) images_data = self.context.get('view').request.FILES post = Post.objects.create(**validated_data) post.tags.add(*tags_data) for image_data in images_data.values(): PostImage.objects.create(post=post, image=image_data) return post When I send a post request with the following data: data = { 'title': 'First Post', ... 'tags':'["tag1"]'} I get an error: Exception Value: '_TaggableManager' object is not iterable I also tried sending 'tags':'one, two, three' and simply one Edit - PDB output: Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. &gt; /Users/gr/Desktop/PycharmProjects/godo/api/serializers.py(112)create() -&gt; tags_data = validated_data.pop('tags') (Pdb) tags_data *** NameError: name 'tags_data' is not defined (Pdb) Models.py from taggit.managers import TaggableManager class Post(models.Model): objects = LocationManager() # to sort by distance tags = TaggableManager() created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=False) description = models.TextField(max_length=500, blank=False) def __str__(self): return '{}'.format(self.title)
has comment: http://stackoverflow.com/comment/85455855
has comment: http://stackoverflow.com/comment/85455843
has answer: http://stackoverflow.com/a/49224874
linked to: http://stackoverflow.com/q/4959499
has comment: http://stackoverflow.com/comment/85456003
has comment: http://stackoverflow.com/comment/85455820
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85455763
has comment: http://stackoverflow.com/comment/85455869
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85455957
tagged with: django
upvote count: 1
tagged with: python
score: 1
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/85455919

http://stackoverflow.com/q/49123277
score: 1
tagged with: python
tagged with: regex
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85252091
tagged with: text-parsing
type: UnansweredQuestion
has body: I am trying to parse the following text Input: value1 @ M Temperature 1.30 ohmm @ 74 00 degF value2 Q M. Temperature 1 70 ohmm @ 74.00 degF value3 @ m Temperature 110 ohmm @ 74.00 degF Expected Output: value1 = 1.30 value1 temp = 74.00 degF etc I was able to extract the text from the file but having issues making the variances in the OCR output dynamically parseable. So when it appears as 'Temp' it still pulls the expected value among other things. import re with open('C:\Users\NthDS1\Documents\samp.txt', 'r') as f: data = list() group = dict() for key, value in re.findall(r'(.*)Temperature\s*([\dE+-.]+)', f.read()): if key in group: data.append(group) group = dict() group[key] = value data.append(group) print data
downvote count: 0
upvote count: 1
has title: Python Regex Parsing from OCR result
has answer: http://stackoverflow.com/a/49123330
has answer: http://stackoverflow.com/a/49123534

http://stackoverflow.com/comment/85498154
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49245828
has text: I ran the code removing the `else` part and it is printing the price. Even with the else part, it prints the price, just in between many `NOT FOUND`s.
score: 1

http://stackoverflow.com/q/49262362
tagged with: arrays
downvote count: 0
upvote count: 1
has title: How to build a numpy array with np.nan as the first item
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49262652
has answer: http://stackoverflow.com/a/49262533
accepted answer: http://stackoverflow.com/a/49262533
score: 1
tagged with: python
tagged with: nan
type: Question
tagged with: numpy
has body: So I'm trying to find out if there is a way to do this similar to having a for loop inside of the np.array. A simple example is set is below. Normal method: &gt;&gt;&gt; np.array([ ... (x, x + 2) ... for x in range(10) ... if x%2 == 0]) array([[ 0, 2], [ 2, 4], [ 4, 6], [ 6, 8], [ 8, 10]]) The output that I would like to achieve would be: array([[np.nan, np.nan], [ 0, 2], [ 2, 4], [ 4, 6], [ 6, 8], [ 8, 10]]) What I have tried with no success is: &gt;&gt;&gt; np.array([ ... (np.nan, np.nan), ... (x, x+2) ... for x in range(10) ... if x%2 == 0]) As well as: &gt;&gt;&gt; np.array( ... [np.nan, np.nan], ... [(x, x+2) ... for x in range(10) ... if x%2 == 0]) I would like to do this without concatenation of hstack. Any help is much appreciated.
possible better answer: http://stackoverflow.com/a/49262652
answer count: 2

http://stackoverflow.com/a/49210813
has comment: http://stackoverflow.com/comment/85426301
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/113789760
has body: If you don't care about efficiency, use scipy: import scipy, scipy.ndimage def nb_vals(matrix, indices): matrix = scipy.array(matrix) indices = tuple(scipy.transpose(scipy.atleast_2d(indices))) arr_shape = scipy.shape(matrix) dist = scipy.ones(arr_shape) dist[indices] = 0 dist = scipy.ndimage.distance_transform_cdt(dist, metric='chessboard') nb_indices = scipy.transpose(scipy.nonzero(dist == 1)) return [matrix[tuple(ind)] for ind in nb_indices] e.g. &gt;&gt;&gt; matrix=[[1,2,3,4], ... [5,6,7,8], ... [9,10,11,12]] &gt;&gt;&gt; &gt;&gt;&gt; nb_vals(matrix, [1,1]) [1,2,3,5,7,9,10,11] This is dimension agnostic (works for an arbitrary number of dimensions for the input "matrix") and handles an arbitrary number of indices which you may wish to find neighbours around. &gt;&gt;&gt; arr_shape = (2,3,4,5) &gt;&gt;&gt; testMatrix = scipy.array(scipy.random.random(arr_shape)*10, dtype=int) &gt;&gt;&gt; print(testMatrix) [[[[7 0 0 1 9] [9 5 8 5 8] [4 0 0 8 0] [1 9 1 3 2]] [[9 2 3 3 5] [2 3 3 7 9] [6 5 6 6 2] [9 1 1 0 0]] [[8 8 5 7 9] [9 0 7 7 6] [3 8 7 6 4] [8 7 5 5 9]]] [[[8 9 2 0 0] [8 3 5 5 2] [4 0 1 0 3] [1 0 9 1 3]] [[6 9 2 5 2] [2 7 5 5 3] [6 7 2 9 5] [4 2 7 3 1]] [[1 7 7 7 6] [5 1 4 1 0] [3 9 4 9 7] [7 7 6 6 7]]]] &gt;&gt;&gt; nb_vals(testMatrix, [1,2,2,3]) [3, 7, 9, 6, 6, 2, 1, 0, 0, 7, 7, 6, 7, 6, 4, 5, 5, 9, 5, 5, 3, 2, 9, 5, 7, 3, 1, 4, 1, 0, 4, 7, 6, 6, 7] This solution uses a chessboard-type chamfer transform on an image-like binary array mask, where 1 is equal to a white pixel on the mask and 0 is equal to a black pixel (background) to the mask. The chamfer transform calculates the chessboard distance of all white pixels to the background; all pixel locations with a distance calculated as 1 are the neighbours, and the values at these locations on the input array are returned.
has comment: http://stackoverflow.com/comment/85426886
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/85426743
answers question: http://stackoverflow.com/q/49210506
accepted answer of: http://stackoverflow.com/q/49210506
has comment: http://stackoverflow.com/comment/85446530
has comment: http://stackoverflow.com/comment/85426244
has comment: http://stackoverflow.com/comment/113789909
upvote count: 3

http://stackoverflow.com/a/49147022
downvote count: 1
has body: In this case you could use bs4. from bs4 import BeautifulSoup as bs XML = ''' <?xml version="1.0" encoding..... ''' bs=bs(XML) urlset_tag = bs.find_all('urlset') ##out: list with one element --> [<urlset xmlns="http://www.si....] link = urlset_tag[0].find_all('loc') ##out: [ http://www.example.com/ ] link_str=str(link[0].text) ##out:'http://www.example.com/' If you hace more tags urlset, you should go through a loop because the list length will be greater than one: links=[] for link in urlset_tag: links.append(str(link.find_all('loc')[0].text))
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49145354
upvote count: 2

http://stackoverflow.com/q/49199296
tagged with: recursion
type: AnsweredQuestion
upvote count: 0
has title: Is changing a variable in a recursive call considered mutation
downvote count: 3
has comment: http://stackoverflow.com/comment/85403925
answer count: 1
favorite count: 0
type: Question
has body: My goal is to sum a list without using mutation. def noMutObj(lst,pointer=0, result=0): if pointer == len(lst): return result newResult = result + lst[pointer] return noMutObj(lst, pointer+1, newResult) Would we consider pointer mutating as we take a step into the recursion, or does mutation apply only to a variable changing in a iterative loop?
has comment: http://stackoverflow.com/comment/85403621
has answer: http://stackoverflow.com/a/49199415
accepted answer: http://stackoverflow.com/a/49199415
tagged with: sum
score: -3
tagged with: python
tagged with: mutation
tagged with: mutable

http://stackoverflow.com/comment/85437820
comment on: http://stackoverflow.com/q/49216855
type: Comment
type: QuestionComment
score: 2
has text: Can you show us what you have done so far? Also, did you read the documentation for requests?

http://stackoverflow.com/q/49225844
type: Question
has body: i recently started learning python and my friend from work who is a programmer gave me a simple challenge to write a "guess the number" style game. So i came up with something as follows: import random print("Hello, welcome to GUESS THE NUMBER game") run = True def again(): global run playagain = str(input("Would you like to play again? Type y/n for yes or no: ")) if playagain == "y": run = True elif playagain == "n": run = False while run: guess = int(input("Guess the number between 1 and 10: ")) num1 = random.randint(1, 10) if guess == num1: print("CONGRATULATIONS, YOU HAVE GUESSED THE NUMBER, THE ANSWER WAS " + str(num1)) again() elif guess &gt; num1: print("Too high, go lower!") elif guess &lt; num1: print("Too small, go higher!") My problem is that after the user has chosen to play again, the numbers sometimes dont register and go out of whack. For example you input 5 and it says too low, but if you input 6 it says too high! I don't seem to be dealing in float numbers so they should be whole, any ideas where i went wrong? Thanks in advance and very excited to learn more on the subject
has comment: http://stackoverflow.com/comment/85455363
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49225878
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49225896
answer count: 2
has comment: http://stackoverflow.com/comment/85455398
has comment: http://stackoverflow.com/comment/85455544
upvote count: 0
has title: Python "Guess The Number" game giving unexpected results
downvote count: 1
favorite count: 0

http://stackoverflow.com/comment/85544485
comment on: http://stackoverflow.com/a/49270201
score: 0
type: AnswerComment
type: Comment
has text: The first argument of instance methods is a reference e to the object to which it is bound. It is, however implicit when you call it. Instead of adding none as the first argument add self on the function definition.

http://stackoverflow.com/a/49245319
answers question: http://stackoverflow.com/q/49245271
has body: You can use applyfunc to apply a function to every element: B.applyfunc(lambda x : x % 3)
downvote count: 0
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49245271
type: Answer

http://stackoverflow.com/q/49175406
answer count: 4
tagged with: jupyter-notebook
has title: Jupyter Notebook: (OperationalError('disk I/O error',))
accepted answer: http://stackoverflow.com/a/49180789
score: 5
downvote count: 0
linked to: http://stackoverflow.com/q/21352285
has answer: http://stackoverflow.com/a/77127407
favorite count: 0
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49180789
upvote count: 5
has answer: http://stackoverflow.com/a/59889198
has comment: http://stackoverflow.com/comment/85356666
has body: I'm getting the following error on running an existing Jupyter Notebook file The history saving thread hit an unexpected error (OperationalError('disk I/O error',)).History will not be written to the database. Never the less, the remaining code in the notebook executes properly after that. However, when I'm trying to create a new notebook file this error is not letting me create it and I get the following error: Error while saving file: python_notebook_ollie/Untitled2.ipynb disk I/O error Traceback (most recent call last): File "/work/ollie/muali/miniconda3/lib/python3.6/site-packages/notebook/services/contents/filemanager.py", line 421, in save self.check_and_sign(nb, path) File "/work/ollie/muali/miniconda3/lib/python3.6/site-packages/notebook/services/contents/manager.py", line 440, in check_and_sign self.notary.sign(nb) File "/work/ollie/muali/miniconda3/lib/python3.6/site-packages/nbformat/sign.py", line 449, in sign self.store.store_signature(signature, self.algorithm) File "/work/ollie/muali/miniconda3/lib/python3.6/site-packages/nbformat/sign.py", line 207, in store_signature if not self.check_signature(digest, algorithm): File "/work/ollie/muali/miniconda3/lib/python3.6/site-packages/nbformat/sign.py", line 241, in check_signature self.db.commit() sqlite3.OperationalError: disk I/O error [W 15:08:48.093 NotebookApp] Unexpected error while saving file: python_notebook_ollie/Untitled2.ipynb disk I/O error [E 15:08:48.094 NotebookApp] { "Host": "localhost:15695", "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0", "Accept": "application/json, text/javascript, */*; q=0.01", "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate", "Referer": "http://localhost:15695/notebooks/python_notebook_ollie/Traj_case_study.ipynb", "Content-Type": "application/json", "X-Xsrftoken": "2|96ae1fed|bde68f8333dd4b46b900b02246747fa4|1520496687", "X-Requested-With": "XMLHttpRequest", "Content-Length": "19", "Cookie": "_xsrf=…
linked to: http://stackoverflow.com/q/19606275
tagged with: python
has answer: http://stackoverflow.com/a/65035555
possible better answer: http://stackoverflow.com/a/65035555

stereo-3d
tags question: http://stackoverflow.com/q/49191221
type: Tag
tag name: stereo-3d

join
type: Tag
tags question: http://stackoverflow.com/q/49201814
tags question: http://stackoverflow.com/q/49202420
tag name: join
tags question: http://stackoverflow.com/q/49189529
tags question: http://stackoverflow.com/q/49223937
tags question: http://stackoverflow.com/q/49206879
tags question: http://stackoverflow.com/q/49262327
tags question: http://stackoverflow.com/q/49196767

http://stackoverflow.com/comment/85533314
type: Comment
type: QuestionComment
has text: Keys from different models don't interfere with each other. They just count from 1 to N independently. You're just introducing confusion and it might byte you in the future
score: 0
comment on: http://stackoverflow.com/q/49264618

http://stackoverflow.com/comment/85545211
type: QuestionComment
has text: i figured it out, the variable lnk created within the function is treated as a local variable
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49270454

http://stackoverflow.com/q/49144964
tagged with: python
accepted answer: http://stackoverflow.com/a/49145034
tagged with: append
has answer: http://stackoverflow.com/a/49145141
answer count: 4
linked to: http://stackoverflow.com/q/11205254
score: 2
has answer: http://stackoverflow.com/a/49145034
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49178468
possible better answer: http://stackoverflow.com/a/49144992
upvote count: 2
duplicate of: http://stackoverflow.com/q/11205254
downvote count: 0
has title: Appending to list - None result
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85294973
has body: Data: lis_t = [['q', 'w', 'e'],['r', 't', 'y']] Expected Outcome: lis_t = [['q', 'w', 'e', 'u'],['r', 't', 'y']] problem description: I am trying to append to the list above however not able to append the same as it somehow results in none. Please help me understand what am I doing wrong. Code written: lis_t = [['q', 'w', 'e'],['r', 't', 'y']] lis_t[0] = lis_t[0].append('u') print(lis_t[0]) print(lis_t) output: None [None, ['r', 't', 'y']]
has answer: http://stackoverflow.com/a/49144992

http://stackoverflow.com/comment/85337351
type: QuestionComment
score: 0
has text: Although your dict construction doesn't throw any syntax errors, a Python dict can have only ONE value per key, because Python doesn't allow duplicate keys as said by @VikasDamodar above. Maybe what you need is to have a list for the desired key: `{'acer.nak': ['kaui.nak', 'maui.nak', 'nihau.nak']}`
type: Comment
comment on: http://stackoverflow.com/q/49165932

http://stackoverflow.com/comment/85398510
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49196457
has text: do you really mean the `string`-module, or the internal `str` type?

http://stackoverflow.com/q/49261459
has comment: http://stackoverflow.com/comment/85526557
linked to: http://stackoverflow.com/q/405516
tagged with: iteration
has answer: http://stackoverflow.com/a/49261865
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49261962
upvote count: 0
type: UnansweredQuestion
score: -4
has body: I have a dictionary example as: dictionary = {Bay1: [False,False,True], Bay2: [True,True,True], Bay3: [True,True,False], Bay4: [False,False,False] } What I'm trying to do is to go through the dictionary by checking each bay (Bay1, Bay2...) to see which one has an array where everything inside it is False. For that example, I want it to return 'Bay4'. Secondly, I want to be able to check to see which is False and which is True in each bay by using loops. In other words, you can imagine that True represents being 'Booked' and False represents being free or 'Not booked'. I want to be able to check that for each bay and present it to the user in a good and easily readable format.
tagged with: python
tagged with: dictionary
has title: Iterating through a dictionary and a list within
answer count: 2
downvote count: 4

http://stackoverflow.com/q/49169303
tagged with: recursion
has comment: http://stackoverflow.com/comment/85343899
tagged with: python
has answer: http://stackoverflow.com/a/49169438
has body: I wanted to making this code work to find out the fibonacci series with recursion but i don't understand why my code fails to do that class fib: #fibonacci series a = 0 b = 0 c = 0 count = 0 def __init__(self, a , b,count): self.a=a self.b=b self.count=count; def fibb(self, a , b,count): if(self.count &gt; count): return; else: if(self.count == 0): print a print b self.count = self.count + 1 print " counting : ", self.count self.c = self.a + self.b self.a = self.b self.b = self.c #print self.a , ", ",self.b return fibb(self.a,self.b,count) else: print b self.count = self.count + 1 print " counting : ", self.count self.c = self.a + self.b self.a = self.b self.b = self.c #print self.a , ", ",self.b return fibb(self.a,self.b,count) fib1 = fib(1,2,0) # creating object fib1.fibb(1,1,10) # calling function My Output: Traceback (most recent call last): File "jdoodle.py", line 36, in fib1.fibb(1,1,10) # calling function File "jdoodle.py", line 24, in fibb return fibb(self.a,self.b,count) NameError: global name 'fibb' is not defined Command exited with non-zero status 1
has comment: http://stackoverflow.com/comment/85343903
type: Question
score: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85343741
has title: recursion function to find fibonnaci series
answer count: 1
has comment: http://stackoverflow.com/comment/85343790

http://stackoverflow.com/comment/85520601
score: 1
type: Comment
type: QuestionComment
has text: You are passing `i ([True, False, False])` to `get_neighbors` as `a` and then passing `a ([True, False, False])` to `find_neighbor_indices` as `i`, therefore `i` is a list
comment on: http://stackoverflow.com/q/49258716

http://stackoverflow.com/a/49182998
has body: Create the function: def my_func(x): result = (a[0]*a[1] for a in x) return sum(result) Call the function: x = [(70.9, 1, 24.8), (15.4, 2, 70.5), (30.0, 3, 34.6), (25.0, 4, 68.4), (45.00, 5, 99.0)] my_func(x) Result will be 516.7
answers question: http://stackoverflow.com/q/49182901
upvote count: 4
type: Answer
score: 4
accepted answer of: http://stackoverflow.com/q/49182901
type: AcceptedAnswer
downvote count: 0

timeit
tag name: timeit
type: Tag
tags question: http://stackoverflow.com/q/49241161
tags question: http://stackoverflow.com/q/49249276
tags question: http://stackoverflow.com/q/49201735

http://stackoverflow.com/comment/85370723
comment on: http://stackoverflow.com/a/49178146
type: Comment
has text: I'm not much more advanced than yourself. Pandas is a world unto itself, and it takes some getting used to, but if you're working with number crunching like this, it's worth it. You might want to look more closely at GeoPandas to see if it has functionality in which to express this more elegantly.
type: AnswerComment
score: 1

http://stackoverflow.com/comment/85408924
type: Comment
type: QuestionComment
score: 0
has text: I thought I wouldn't copy the 279000 lines of data into here, hence the link. I understand your suspicion due to the rather generic name. I cannot really reduce it in a meaningful way as the whole point of my problem is related to the denseness of the data. I'll try to see if I can strip a small part that contains just a small part of the line. If you look at my code, you'll see exactly how to open and read it, using numpy.genfromtxt. As for the minimal verifiable example, I imagined that's exactly what I provided. I stripped away all the parts of my code that are not necessary.
comment on: http://stackoverflow.com/q/49201540

http://stackoverflow.com/q/49154677
tagged with: python
has comment: http://stackoverflow.com/comment/85315768
tagged with: module
answer count: 0
score: 0
tagged with: function
has comment: http://stackoverflow.com/comment/85315015
type: Question
has body: I am trying to build a function with netmiko (ssh session manager based on paramiko) and import it as a module. Here the function that I want import: import sys, socket, getpass from netmiko import ConnectHandler def sshHost(hostname): username = raw_input("Username: ") password = getpass.getpass() hostIp = socket.gethostbyname(hostname) sshSession = ConnectHandler(device_type = 'juniper', ip = hostIp, username = username, password = password) versionHostname = sshSession.send_command("show version | match Hostname:") print "Session established with ",versionHostname.strip(), "IP: ", hostIp return sshSession so, that function work as expected if I run sshHost(sys.argv[1]) however, when I import that as external module , the script times-out #!/usr/bin/env python import sys from netmiko import ConnectHandler from sshHostModuleJUNOS import sshHost def showVersion(host): out = host.send_command("show version") print out showVersion(sshHost(sys.argv[1])) I am quite sure something is wrong in the way I use the sshHost module but I cannot figure out what error paramiko.ssh_exception.SSHException: No existing session
has title: python import module time out
type: UnansweredQuestion

http://stackoverflow.com/a/49218761
has comment: http://stackoverflow.com/comment/85443495
has body: module a exec('from some_module import *') module b import importlib a=importlib.import_module('module a') for i in dir(a): if not i.startswith('_'): exec('{0}=a.{0}'.format(i)) print(SOME_VARIABLE);
has comment: http://stackoverflow.com/comment/85443191
has comment: http://stackoverflow.com/comment/85441505
downvote count: 0
has comment: http://stackoverflow.com/comment/85441342
has comment: http://stackoverflow.com/comment/85443094
answers question: http://stackoverflow.com/q/49218676
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/comment/85498225
has text: Add `(?:\[\.\]|\.)` instead of `\.`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49247258
type: Comment

http://stackoverflow.com/comment/85503868
type: QuestionComment
type: Comment
has text: Probably with a view where dtype was uint8 or U1 or something
score: 0
comment on: http://stackoverflow.com/q/49250239

http://stackoverflow.com/comment/85407853
type: AnswerComment
comment on: http://stackoverflow.com/a/49201350
score: 0
has text: @jpp If I omit the column accessor, it will replicate the counts for each column in the dataframe (I just need one, I could pick any of them ;) )
type: Comment

http://stackoverflow.com/comment/85549044
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49267726
has text: Does the bug just affect Python? Or was this a bug introduced on the Java side, at some point? (The example in the book was done in R, and was done with H2O 3.10, IIRC.)
type: Comment

http://stackoverflow.com/comment/85541124
has text: yes I did @LorenzoPeña
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49268864
score: 0

http://stackoverflow.com/q/49269343
has comment: http://stackoverflow.com/comment/85542361
favorite count: 0
has comment: http://stackoverflow.com/comment/85549765
tagged with: cron
tagged with: python
has title: how to use background scheduler with an flask + gunicorn app
score: 4
type: Question
upvote count: 4
tagged with: gunicorn
has body: I have one scheduler to send message periodically in my flask app. For gunicorn, I defined 10 sync workers and the app create 10 schedulers and send the same message 10 times. Is there any way to only send one message? The code for flask app: def send_msg(): # here we send msg @app.before_first_request def activate_job(): scheduler = BackgroundScheduler() scheduler.add_job(send_msg, 'interval', minutes=5) scheduler.start() atexit.register(lamda: scheduler.shutdown())
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85541957
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50835568
tagged with: scheduler
tagged with: flask

http://stackoverflow.com/comment/92382870
comment on: http://stackoverflow.com/a/49239827
has text: So, just so I'm understanding this correctly, are you reading a sql query into a df and pushing that into a Google sheet? If so that's bloody awesome will give it a shot!
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49159457
upvote count: 2
has comment: http://stackoverflow.com/comment/85324458
has body: how about this ?: def fibonacci(n, a=0, b=1): if a &gt;= n : return [a] return [a] + fibonacci(n,b,a+b) [EDIT] Here's how it works: The function progressively builds an array by adding one element [a] to the result of the next call to itself. The first line allows it to stop when the target is reached. Without it, the second line of the function would keep calling itself and there would never be a result coming back from the recursion. Because the parameters of a function are local to each call, the value of a and b in the second call are different from the previous ones. If we follow the logic for fibonacci(7), we get: 1) fibonacci(n=7, a=0, b=1) ==> will return [0] + fibonacci(7,1,1). 2) fibonacci(n=7, a=1, b=1) ==> will return [1] + fibonacci(7,1,2). 3) fibonacci(n=7, a=1, b=2) ==> will return [1] + fibonacci(7,2,3). 4) fibonacci(n=7, a=2, b=3) ==> will return [2] + fibonacci(7,3,5). 5) fibonacci(n=7, a=3, b=5) ==> will return [3] + fibonacci(7,5,8). 6) fibonacci(n=7, a=5, b=8) ==> will return [5] + fibonacci(7,8,13). 7) fibonacci(n=7, a=8, b=13) ==> 8 >= 7 so the first line returns [8] At that point there are no more recursive calls (the first line returns without calling the function again) and the return values start coming back up. 7) returns [8] 6) returns [5,8] 5) returns [3,5,8] 4) returns [2,3,5,8] 3) returns [1,2,3,5,8] 2) returns [1,1,2,3,5,8] 1) returns [0,1,1,2,3,5,8] One way to think about recursive functions is to look only at the incremental work to be done on the result that would be produced by a prior parameter value. Most of the time this part of the logic applies backwards (i.e computing the end result based on a previous one). For example, a factorial can be thought of as the multiplication of a number with the factorial of the previous number. This gives you the equivalent of the second line. Once you have that down, all you need to decide is the condition that makes the recursion stop. Usually this corresponds to the smallest/simplest use c…
answers question: http://stackoverflow.com/q/49158987
has comment: http://stackoverflow.com/comment/85325831
has comment: http://stackoverflow.com/comment/85324820
has comment: http://stackoverflow.com/comment/85327388
has comment: http://stackoverflow.com/comment/85324552
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85324217
type: Answer
has comment: http://stackoverflow.com/comment/85324333

http://stackoverflow.com/comment/85469750
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49232866
has text: Please reread and then create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)

http://stackoverflow.com/comment/85450722
type: Comment
has text: @hpaulj: You are awesome. Thank you :-)
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49223511

http://stackoverflow.com/a/49268133
has comment: http://stackoverflow.com/comment/85560930
has comment: http://stackoverflow.com/comment/85556022
downvote count: 4
has comment: http://stackoverflow.com/comment/85540286
has comment: http://stackoverflow.com/comment/85541989
type: AcceptedAnswer
score: 1
has comment: http://stackoverflow.com/comment/85541558
has comment: http://stackoverflow.com/comment/99683769
accepted answer of: http://stackoverflow.com/q/49267999
upvote count: 5
answers question: http://stackoverflow.com/q/49267999
type: Answer
has body: The problem is the directory path of the file is not read properly. Use raw strings to pass it as argument and it should work. carregar_uml(r'H:\7 - Script\teste.csv', variaveis)

http://stackoverflow.com/q/49171095
type: Question
accepted answer: http://stackoverflow.com/a/49171308
tagged with: oop
has comment: http://stackoverflow.com/comment/85347419
has comment: http://stackoverflow.com/comment/85347322
has body: i have a python class called student.py that have attributes and methods but the problem is that when i try to get the grade of the student the function doesn't work as it should and just display the the printing result that contain the name and the grade without the letter the second task i need to get the average of all grades of the student where this function take as arguments list of grades[] student.py class student(): def __init__(self,name,age, grade): self.stdName=name self.stdAge = age self.stdGrade = grade def getName(self): return self.stdName def setName(self,Name): self.stdName = Name def getAge(self): return self.stdAge def setAge(self, Age): self.stdAge = Age def getGrade(self): print("the student {0}, have a grade {1}".format(self.stdName,self.stdGrade)) if self.stdGrade &gt;=90: return "A" elif self.stdGrade &gt;=80: return "B" elif self.stdGrade &gt;=60: return"C" else: return"F" return self.stdName,self.stdGrade def setGrade(self,Grade): self.stdGrade = Grade std1 = student("georges", 17, 80) std1.getGrade()
tagged with: python
score: -1
has title: what is the error in the getGrade() function in student.py
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49171308
upvote count: 0
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85347253
favorite count: 0

http://stackoverflow.com/q/49226716
has title: Query dictionary based on a criteria and skip values that are missing
type: Question
has answer: http://stackoverflow.com/a/49227411
tagged with: removing-whitespace
has answer: http://stackoverflow.com/a/49226739
possible better answer: http://stackoverflow.com/a/49226786
accepted answer: http://stackoverflow.com/a/49226739
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
score: 0
answer count: 3
has body: data = [ {'firstname': 'Tom ', 'lastname': 'Frank', 'title': 'Mr', 'education': 'B.Sc'},{'firstname': 'Anne ', 'middlename': 'David', 'lastname': 'Frank', 'title': 'Doctor', 'education': 'Ph.D'} , {'firstname': 'Ben ', 'lastname': 'William', 'title': 'Mr'} ] I want to query the list of dictionaries based on the key 'education'. If the person's detail does not have this key the entire dictionary will be passed over.The desired output is [(' Mr Tom Frank', 'B.Sc'), ('Doctor Anne David Frank', 'Ph.D') ] My attempt would have an extra space between Tom and Frank as in Mr Tom Frank as well as between Anne and David . Here is the actual output [('Mr Tom Frank', 'B.Sc'), ('Doctor Anne David Frank', 'Ph.D')] I would like to avoid this if possible. Here is the code I have written. I apologize if the code does not seem to be readable enough and I am ready to take any comments. def qualified_applicants(data): full_name_education=[ ] keys = ['title','firstname','middlename','lastname'] for record in data: #check to see if 'education' is one of the key if 'education' in record.keys(): full_name=[' '.join([record.get(key,'') for key in keys])] # make a tuple of education and full names full_name_education.append(tuple(full_name+[record['education']])) return full_name_education
has answer: http://stackoverflow.com/a/49226786

http://stackoverflow.com/comment/85505525
comment on: http://stackoverflow.com/q/49249664
score: 0
type: Comment
has text: what about using `serializer` and create instances using a custom `.create()` method ?
type: QuestionComment

http://stackoverflow.com/comment/85447780
type: Comment
comment on: http://stackoverflow.com/q/49221539
type: QuestionComment
score: 0
has text: "Scapy is a [...] interactive packet manipulation program and library." I'm not sure that this will help me...

http://stackoverflow.com/comment/85494391
score: 0
comment on: http://stackoverflow.com/q/49245157
type: Comment
type: QuestionComment
has text: not necessarily, but the numbers are always same digits, either all double digits, or all triple digits, or [4123,4223,4567] etc....

http://stackoverflow.com/a/75597759
type: Answer
score: 0
has body: I kept having a problem impelmenting Hannu's code: results = [] for q in range(1, 10): res = p.apply_async(gwork, args=(q,)) results.append(res) p.close() p.join() for r in results: print (r.get()) The problem is that when the loop hits the first r.get() with an exception the whole program exits because it's not handled properly. I've seen this method posted many times in almost the same way but always resulted in the same problem. I ended up wrapping the r.get() in a TRY/EXCEPT block and that allowed the program to handle all the exceptions in the list and continue on as designed. from multiprocessing.pool import Pool import traceback results = [] pool = Pool(32) process_schedule_data = pool.apply_async(TSMDataProcessor().process_schedule_data, args=("Schedule",)) # a bunch more calls like the one above but to different methods of the same class pool.close() pool.join() for r in results: try: r.get() except BaseException: logger.error(f"data processor exception: {traceback.format_exc()}")
answers question: http://stackoverflow.com/q/49174419

databricks
tag name: databricks
type: Tag
tags question: http://stackoverflow.com/q/49160329

http://stackoverflow.com/a/49179559
type: Answer
answers question: http://stackoverflow.com/q/49178979
score: 2
upvote count: 2
has body: The problem as shown is printing a character that isn't supported by your code page (cp850). You can manipulate Unicode strings just fine...it's just a problem of display. Python 3.6+ solves this issue by bypassing code pages and printing using Windows Unicode APIs: Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; print('\u1e03') ḃ If you can't switch to a later version of Python, can you switch to an IDE that supports UTF-8? Example using PythonWin from the pywin32 module (I have Python 2.7 installed). PythonWin 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. &gt;&gt;&gt; print(u'\u1e03') ḃ
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49178979

http://stackoverflow.com/q/49152812
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85310120
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85326631
has comment: http://stackoverflow.com/comment/85310102
has answer: http://stackoverflow.com/a/49152983
score: 0
has body: I'm struggling to figure out how to organize things here. I'm building a race game. There are players and race courses. Player have attributes like name, age, etc. Race courses also have a set of attributes, including difficulty. One thing I want to do is, when a player runs a course their energy level drops based on difficulty of the course. What I'm confused about is, because difficulty is an attribute of the course, and energy level is an attribute of the player, how can I affect the two? Take the code for example... class Player(): energy_level = 0 def __init__(self, name, ability) self.name = name self.ability = ability def run(self): #code to run course here, reduces energy level when running course. Energy level is reduced based on player ability class Course(): def __init__(self, name, difficulty) self.name = name self.difficulty = difficulty player1 = Player("Bob", 90) course1 = Course("Advanced Track", 15) Maybe I am going about this all wrong? Does course need to be a class? Thanks for any input.
has comment: http://stackoverflow.com/comment/85326397
has comment: http://stackoverflow.com/comment/85310486
has answer: http://stackoverflow.com/a/49152956
has title: How to organize my code. Classes, functions, etc?
upvote count: 1
linked to: http://stackoverflow.com/q/3277367
downvote count: 1
has comment: http://stackoverflow.com/comment/85316612

http://stackoverflow.com/comment/85387702
has text: Let me guess: The path of the current working directory has a space in it. Or some other character that needs to be escaped.
comment on: http://stackoverflow.com/q/49191329
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49240707
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/85485049
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85485121
has comment: http://stackoverflow.com/comment/85485428
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/85485379
answer count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/85485100
has title: Float to Currency retain format to add
has comment: http://stackoverflow.com/comment/85485163
has comment: http://stackoverflow.com/comment/85494054
has body: I have a pandas dataframe with a lot of % and currency columns coming in from a sql table as float datatypes. I'm doing the below to convert it to currency format. I am appending this data to an excel spreadsheet with openpyxl. while the output is showing currently with cost as $123, $100 etc, it possibly converts to string thus losing the ability to sum the values after generating the data. How can I make the data display the $ before cost yet retain its ability to sum the values? (df['Cost']).apply(lambda x: '${:,.2f}'.format(x)) The dataframe I am attempting to append to excel is very large and wide. About 480 columns and 30K rows - data is mixed. Strings, Currency, % and plain old float. Not sure if I can specify it by cell. So was hoping to handle it in the dataframe and output it. Also read that number formats are strings in openpyxl so that would not help in this case Any other ideas/options for me? Thanks in advance.

http://stackoverflow.com/a/49165011
type: Answer
answers question: http://stackoverflow.com/q/49164516
has body: You have 3 while loops, only the last includes your incrementor, and your incrementor should be yr += 1 (which is short for yr = yr = 1) not just yr+1. You will also need to change your approach, because you are wanting to iterate over the years as well as over the rows. I would suggest keeping a dictionary of years, and the vhu, ohu and thu data for each year. The end result might look like `{'2008': {'vhu': 1, 'ohu': 5, 'thu': 6}, '2009': ...}.
score: 0

http://stackoverflow.com/comment/85312362
type: QuestionComment
comment on: http://stackoverflow.com/q/49131680
score: 0
has text: What you're asking for is beyond what JSON Schema is for. You'll have to hook into the validator as per the FAQ link in my previous comment. The normal use for JSON Schema is never to modify the instance. Does that all make sense to you?
type: Comment

http://stackoverflow.com/comment/85351134
type: AnswerComment
comment on: http://stackoverflow.com/a/49172869
score: 1
type: Comment
has text: @jpp Thank you. I fixed that now.

http://stackoverflow.com/q/49206353
upvote count: 1
score: 1
tagged with: python
has body: I have a text file with data that I want to read in Python. The file following data: nodCoord = 0 0 0 0.5 0 1 0.5 0 0.5 1 1 0 1 0.5 1 1 1.5 0 1.5 1 2 0 2 0.5 2 1 # Element data: element type, material, connectivities elCon = QUAD8 1 1 4 6 7 8 5 3 2 Now I have to read the "nodCoord =" line and all the lines below it which are starting with numbers into an array of numbers, say "coordinates", but I don't know how many lines there will be. How can I do it?
has answer: http://stackoverflow.com/a/49206408
favorite count: 0
type: Question
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
answer count: 1
tagged with: arrays
tagged with: file
has title: Reading multiple lines from a File in Python

http://stackoverflow.com/comment/85470184
comment on: http://stackoverflow.com/a/49231231
type: Comment
has text: Thank you! I found that the calendar module of python is also a good choice.
score: 0
type: AnswerComment

http://stackoverflow.com/a/49257131
score: 2
accepted answer of: http://stackoverflow.com/q/49257094
has comment: http://stackoverflow.com/comment/85517713
type: Answer
upvote count: 2
downvote count: 0
has body: You need numpy.isnan() and boolean indexing. &gt;&gt;&gt; A[np.isnan(B)] = np.nan &gt;&gt;&gt; B[np.isnan(A)] = np.nan
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49257094

http://stackoverflow.com/a/49505461
has body: In case it is of help to others, for completion, I will outline the steps that I took. After re-installing Anaconda and losing access to my previous virtualenv for web development, I abandoned virtualenv and moved my web development work to my Conda environments. Basically, I needed to (re)source the necessary paths. My steps were the following: Note: the "..." in paths are my username on MacOS. Create a new conda environment called "webdev", having python=2 Downloaded the google-cloud-sdk and moved (manually) the entire folder to the "webdev" bin folder like: /Users/.../anaconda/envs/webdev/bin/google-cloud-sdk cd to that folder and run: ./install.sh Make sure PATHs in nano .bash_profile are linked. On terminal: $ cd $ nano .bash_profile Enter the following paths (first one should be there from Anaconda): export PATH=$HOME/anaconda/bin:$PATH export PATH=/Users/.../anaconda/envs/webdev/bin/google-cloud-sdk/completion.bash.inc:$PATH export PATH=/Users/.../anaconda/envs/webdev/bin/google-cloud-sdk/path.bash.inc:$PATH export PATH=/Users/.../anaconda/envs/webdev/bin/google-cloud-sdk/bin:$PATH Re-start the terminal. Enter the two commands in the terminal: source /Users/.../anaconda/envs/webdev/bin/google-cloud-sdk/completion.bash.inc source /Users/.../anaconda/envs/webdev/bin/google-cloud-sdk/path.bash.inc After that this command should work: dev_appserver.py ./
answers question: http://stackoverflow.com/q/49167829
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49167829
type: Answer

http://stackoverflow.com/comment/85539744
comment on: http://stackoverflow.com/a/49268184
type: Comment
score: 2
has text: Your summary (saying "for [...] standard container types [...] equality is used") contradicts your quote from the docs. Membership tests for built-ins use *both* identity *and* value equality tests, testing identity first, then equality if the identity test fails.
type: AnswerComment

http://stackoverflow.com/comment/85528344
comment on: http://stackoverflow.com/a/49262195
type: Comment
score: 0
type: AnswerComment
has text: Thanks for the answer. I am checking it. But what is df? df1?

http://stackoverflow.com/q/49256752
has comment: http://stackoverflow.com/comment/85518968
tagged with: python
tagged with: bounds
has comment: http://stackoverflow.com/comment/85517846
type: Question
has body: I'm starting in python and I'm trying to solve a problem that Fmincon solves in Matlab. Basically, my problem has 12 variables, and a list of 2000 values is created (linearly) and my objective is to maximize the largest value of this list. In addition, the problem has a linear constraint. I have tried, without success, using scipy but in all the free-gradient solvers or approximate gradient that I tried, it is not possible to insert linear constraints. I've also tried using cvxopt, but I did not find any free-gradient solver or approximate gradient. In addition, I would not like to use tools like Genetic Algorithm, PSO, Harmony Search, etc. I would like to use a free-gradient solver or approximate gradient that is possible to insert linear constraints, like Fmincon in Matlab. This is my objective function: import numpy as np def max_receita(X, f, CONSTANTE_CVAR): # f is a matrix with 2000 rows and 12 columns # CONSTANTE_CVAR is a matrix with 2000 rows and 12 columns NSERIES = len(f) REC = np.zeros(NSERIES) X = np.transpose(X) CONST_ANUAL = np.sum(CONSTANTE_CVAR,1) for i in range(NSERIES): REC[i] = np.dot(f[i],X) + CONST_ANUAL[i] return -max(REC) There are 12 variables represented by the vector X with 12 elements and this vector must have sum equal 1. That's my constraint. Beside this, each variable has a different bound. So the solver must allow to insert bounds. The vector X (all the 12 variables), with the inputs f and CONST_CVAR, creates the vector REC (1x2000) and my objective is to maximize the biggest value of the vector REC. In this way, I need a solver that allows: Free-gradient or approximate gradient Linear constraints Non linear function Bounds Python Could anyone suggest any solver?
tagged with: black-box
tagged with: nonlinear-optimization
has comment: http://stackoverflow.com/comment/85523295
has comment: http://stackoverflow.com/comment/85519128
answer count: 0
has comment: http://stackoverflow.com/comment/85516793
has comment: http://stackoverflow.com/comment/85516550
type: UnansweredQuestion
has title: Minimize a non linear and differentiable black-box function, with linear constraints. - Python
tagged with: constraints
score: 0
has comment: http://stackoverflow.com/comment/85523438

http://stackoverflow.com/comment/85377532
type: Comment
type: QuestionComment
score: 0
has text: As the error hints, `i['Photos']` is a list (of dictionaries), not a dictionary. In your sample data, there are multiple photos associated with both users.
comment on: http://stackoverflow.com/q/49185974

http://stackoverflow.com/q/49176651
has comment: http://stackoverflow.com/comment/85363544
upvote count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49179311
has body: Assume I have an 3d (10x3) np.array : orgArr = [[ 30.1678 -173.569 725.724 ] [ 29.9895 -173.34 725.76 ] [ 29.9411 -173.111 725.768 ] [ 29.9306 -173.016 725.98 ] [ 29.6754 -172.621 725.795 ] [ 29.5277 -172.274 725.903 ] [ 29.585 -171.978 726.111 ] [ 29.4114 -171.507 726.188 ] [ 29.3951 -170.947 726.173 ] [ 29.3577 -170.196 726.384 ]] For each column I generate rondom numbers, between min and max values of individual columns eg, for the first col: # Find min/max colXMin = np.min(orgArr[:, 0]) colXMax = np.max(orgArr[:, 0]) # Generate random number between min/max size = 12 addRandomToColX = self.create_random_floats(colXMin, colXMax, size) # Sort the random numbers sortRandomColX= sorted(addRandomToColX, reverse= True) print('sortRandomColX:', sortRandomColX) # Do same for cols y and z ... # Create 3d array finally randomArr = np.array([sortRandomColX, sortRandomColY, sortRandomColZ]).T print('randomArr:', randomArr) def create_random_floats(low, high, size): return [random.uniform(low, high) for _ in range(size)] So I get 12x3 array, which is sorted according given order. col x decreases, but y and z increases: randomArr: [[ 30.16564103 -173.45321119 725.74404996] [ 30.03986524 -173.17110927 725.84951132] [ 29.97088507 -173.15435901 725.85341553] [ 29.79273295 -172.76247176 725.97347288] [ 29.53294671 -170.90169722 726.27944054] [ 29.53182418 -170.88261603 726.34089036] [ 29.52163245 -170.72931883 726.34411865] [ 29.50194557 -170.71866152 726.34946239] [ 29.45834997 -170.68671434 726.36413176] [ 29.4426014 -170.57381107 726.37110357] [ 29.43702889 -170.40826716 726.45476367] [ 29.3621429 -169.77240546 726.51968671]] How can I insert/mix my orgArr in randomArr data again randomly and distribute over the whole size? I mean not in the begin or end in randomArr. Otherwise the sorted order of the indivudial columns are broken.
tagged with: python
has comment: http://stackoverflow.com/comment/85363244
score: 2
type: AnsweredQuestion
has title: Insert original data into randomly generated data in python
accepted answer: http://stackoverflow.com/a/49179311
answer count: 1
has comment: http://stackoverflow.com/comment/85363845
has comment: http://stackoverflow.com/comment/85363467
favorite count: 0
has comment: http://stackoverflow.com/comment/85362202
type: Question
tagged with: numpy
tagged with: python-3.x

http://stackoverflow.com/comment/85395856
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49195267
type: QuestionComment
has text: What do you mean with "race condition between my subprocess and the output"? How does this race condition manifest itself?

http://stackoverflow.com/q/49219469
has body: let say I have a list of lists [[a1, a2, a3], [b1, b2], [c1, c2, c3, c4]] The number of lists in the list is not known in advance. I want to have all combinations of elements from the different list, so [a1, b1, c1], [a1, b1, c2], ..., [a3, b2, c4] but if there common elements in the different list, all these combinations need to be deleted. So if for example, a1 = c2, then the combinations [a1, b1, c2], [a1, b2, c2] need to be deleted in the resulting list. To get all possible combinations, you can use the answer on All possible permutations of a set of lists in Python, but can you automaticaly delete all combinations with common elements?
linked to: http://stackoverflow.com/q/42924045
tagged with: python
linked to: http://stackoverflow.com/q/2853212
accepted answer: http://stackoverflow.com/a/49219534
type: AnsweredQuestion
has title: all combination in list of lists without duplicates in python
has answer: http://stackoverflow.com/a/49219534
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/67109767
possible better answer: http://stackoverflow.com/a/49219518
has answer: http://stackoverflow.com/a/49219518
type: Question

heap-memory
tag name: heap-memory
type: Tag
tags question: http://stackoverflow.com/q/49238981

http://stackoverflow.com/a/77127407
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49175406
has body: This might solve the issue pip cache purge

http://stackoverflow.com/q/49143035
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85291908
has answer: http://stackoverflow.com/a/49143132
tagged with: python
upvote count: 6
has body: Is there a more pythonic way of doing the following: def mysteryFunction( it, fun, val ): out = [] for x in it: y,val = fun(x,val) out.append(y) return out,val where it is iterable, fun is a function that takes two inputs and returns two outputs, and val is an initial value that gets "transformed" by each call to fun? I am asking because I use map, zip, filter, reduce and list-comprehension on a regular basis, but I cannot express the previous function as a combination of those, and this is something that has come up several times now. Am I missing a hidden idiom, or is this just too niche to deserve one? A concrete example is to calculate a duration in terms of (year, week, day, hour, minute, second) from a certain amount of seconds: fac = (365*24*3600, 7*24*3600, 24*3600, 3600, 60, 1) dur,rem = mysteryFunction( fac, lambda x,y: divmod(y,x), 234567 ) where dur is the duration tuple and rem corresponds to the final remainder (either zero or decimal here, depending on the type of the initial value). This is not just cherry-picked, there are many other examples, such as: fixed-step methods to integrate differential equations (iterable steps, stepper function, initial state); simulating a bounded random walk; tree processing across depth without recursion; etc.
accepted answer: http://stackoverflow.com/a/49143132
type: AnsweredQuestion
answer count: 1
downvote count: 0
has title: Pythonic cumulative map
score: 6
favorite count: 0

http://stackoverflow.com/q/49252880
has answer: http://stackoverflow.com/a/72849012
has body: I am trying to click on an element but getting the error: Element is not clickable at point (x,y.5) because another element obscures it. I have already tried moving to that element first and then clicking and also changing the co-ordinates by minimizing the window and then clicking, but both methods failed. The possible duplicate question has answers which I have already tried and none of them worked for me. Also, the same code is working on a different PC. How to resolve it?
answer count: 10
tagged with: python
has answer: http://stackoverflow.com/a/63157469
has title: Element is not clickable at point (x,y.5) because another element obscures it
upvote count: 22
has answer: http://stackoverflow.com/a/76655199
has answer: http://stackoverflow.com/a/78886150
has answer: http://stackoverflow.com/a/49261182
tagged with: selenium-webdriver
has answer: http://stackoverflow.com/a/76689328
type: Question
has answer: http://stackoverflow.com/a/76293545
has answer: http://stackoverflow.com/a/74786245
has comment: http://stackoverflow.com/comment/85611911
downvote count: 0
tagged with: selenium
has comment: http://stackoverflow.com/comment/85512749
has answer: http://stackoverflow.com/a/65402896
possible better answer: http://stackoverflow.com/a/63157469
has comment: http://stackoverflow.com/comment/85515324
score: 22
favorite count: 0
accepted answer: http://stackoverflow.com/a/49261182
linked to: http://stackoverflow.com/q/44724185
has answer: http://stackoverflow.com/a/68574224
type: AnsweredQuestion

http://stackoverflow.com/a/49264232
has body: Try storing the text boxes in an array when you create them. Then use the array to access them. Here is an example: import Tkinter as tk class MyApplication(tk.Frame): arr = [] def __init__(self, master=None): tk.Frame.__init__(self, master) self.pack() self.createWidgets() def addTextBox(self,event): newtext = tk.Entry(self) self.arr.append(newtext) newtext.pack() def getValues(self,event): for i in range(len(self.arr)): print self.arr[i].get() def createWidgets(self): self.btnAdd = tk.Button(self) self.btnAdd["text"] = "Add" self.btnAdd.bind("&lt;Button-1&gt;", self.addTextBox) self.btnAdd.pack() self.btnGet = tk.Button(self) self.btnGet["text"] = "Get" self.btnGet.bind("&lt;Button-1&gt;", self.getValues) self.btnGet.pack() # main root = tk.Tk() root.minsize(width=325, height=325) root.maxsize(width=325, height=325) app = MyApplication(master=root) app.mainloop()
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85559285
has comment: http://stackoverflow.com/comment/85549510
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85556560
answers question: http://stackoverflow.com/q/49263301
has comment: http://stackoverflow.com/comment/85558747

http://stackoverflow.com/a/49271087
has body: I found the formula without the recursion. The test went through fine. def shapeArea(n): if n&gt;=10**4 or n&lt;1: return False return (n**2+(n-1)**2)
score: 32
type: Answer
accepted answer of: http://stackoverflow.com/q/49270277
upvote count: 34
has comment: http://stackoverflow.com/comment/125775196
has comment: http://stackoverflow.com/comment/116999605
type: AcceptedAnswer
downvote count: 2
answers question: http://stackoverflow.com/q/49270277
has comment: http://stackoverflow.com/comment/111017764

http://stackoverflow.com/a/49182508
has comment: http://stackoverflow.com/comment/85370884
score: 3
has comment: http://stackoverflow.com/comment/85370863
has body: I don't believe you can control the size parameter when you pass a list/vector of values for the mean and std. Instead, you can iterate over each pair and then concatenate: np.concatenate( [np.random.normal(m, s, 100) for m, s in zip(mu, sigma)] ) This gives you a (400, ) array. If you want a (4, 100) array instead, call np.array instead of np.concatenate.
upvote count: 3
has comment: http://stackoverflow.com/comment/85370677
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49182440
accepted answer of: http://stackoverflow.com/q/49182440
has comment: http://stackoverflow.com/comment/85370751
type: Answer

http://stackoverflow.com/comment/85448590
score: 0
has text: this worked! thank you! I can marked this as answered/closed if you add this comment as an answer.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49221412

http://stackoverflow.com/comment/85440800
comment on: http://stackoverflow.com/a/49218379
type: AnswerComment
has text: Do you think top counts? `df['city'].value_counts().head(2).index` ?
score: 0
type: Comment

http://stackoverflow.com/a/49195098
downvote count: 0
has comment: http://stackoverflow.com/comment/85397201
answers question: http://stackoverflow.com/q/49194368
has comment: http://stackoverflow.com/comment/85395175
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49194368
has body: OK, This is a bit confusing, to be honest. Several issues I see: First, DataFrame.apply a function to each column should look more like: df.apply(lambda x: mark(x), axis=1) so that you actually loop through each row. Second, DataFrame.apply creates a copy Series for each row (in your case); thus, the changes are not applied to df but to the new row value. If you want to change df, you need to (a) make sure that mark returns something and (b) to assign it to something else: def mark(row): columns = get_columns_to_alter(row['Text']) if len(columns) &gt; 0: row[columns] = True return row new_df = df.apply(lambda x: mark(x), axis=1) Something like this should do what you expect.
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49261593
has comment: http://stackoverflow.com/comment/85527165
answer count: 2
has comment: http://stackoverflow.com/comment/85527335
has answer: http://stackoverflow.com/a/49263611
has comment: http://stackoverflow.com/comment/85529948
has comment: http://stackoverflow.com/comment/85526862
has comment: http://stackoverflow.com/comment/85527222
has comment: http://stackoverflow.com/comment/85529888
has comment: http://stackoverflow.com/comment/85528710
has body: The code i'm writing calculates the sum of divisors of all numbers up to a specified limit. I tried writing it in three ways, two using numpy and one using the array module. N = 10**5 def func2(N,a): for f in range(2, N//2+1): for i in range(f*2, N+1, f): a[i] += f def func3(N,sod): for div in range(2,N//2 +1): sod[2*div::div]+=div the timing results (using timeit) are: %timeit func2(N,sod) %timeit func3(N,a) 1 loop, best of 3: 801 ms per loop 1 loop, best of 3: 703 ms per loop And the results really go against my intuition, I would expect that the version with only one for loop would be faster then the version with two for loops and wouldn't expect there to be such a big difference between numpy and the array module. So, what am I missing?
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85529169
upvote count: 0
type: UnansweredQuestion
score: -2
downvote count: 2
has title: why does numpy slicing seem slower than plain for loops and the array module
tagged with: arrays
has comment: http://stackoverflow.com/comment/85527921
has answer: http://stackoverflow.com/a/49262004
tagged with: python
has comment: http://stackoverflow.com/comment/85528945
has comment: http://stackoverflow.com/comment/85528031

http://stackoverflow.com/a/70760934
answers question: http://stackoverflow.com/q/49248551
downvote count: 0
score: 3
upvote count: 3
type: Answer
has body: I'm aware the question is somewhat old, but just in case someone needs the solution I was looking for: If you want to keep the keys of the outer dict without having them as a value in the inner dict, the following code produces a list of tuples (key, dict) for every inner dict. >>> dic_of_dics = {1: {"a": "A"}, 2: {"b": "B"}, 3: {"c": "C"}} >>> [(k,v) for k, v in dic_of_dics.items()] [(1, {'a': 'A'}), (2, {'b': 'B'}), (3, {'c': 'C'})] I used it to define a networkx graph through the add_nodes_from() function from a dict of dicts produced by the to_dict('index') function from pandas and it worked like a charm.

http://stackoverflow.com/comment/85373842
has text: I've seen the `'try: ...except'` in a lot of code and need to read up on it. Catching the errors and making my code more robust is my next step before I move on to anything else.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49183882
score: 0

http://stackoverflow.com/a/52913464
upvote count: 9
type: Answer
score: 9
answers question: http://stackoverflow.com/q/49165220
has comment: http://stackoverflow.com/comment/119771281
downvote count: 0
has body: Here are all the possible types: var_int = 15 #@param {type:"integer"} var_float = 0.36 #@param {type:"number"} var_bool = False #@param {type:"boolean"} var_date = "2018-10-21" #@param {type:"date"} var_str = "str" #@param {type:"string"} var_raw = "raw" #@param {type:"raw"} var_slider = 39 #@param {type:"slider", min:0, max:100, step:1} var_enum = "val1" #@param ["val1", "val2", "val3"] The types are pretty self-explanatory.

http://stackoverflow.com/comment/85465072
has text: that was it, It is working.. thank you so much for that
score: 0
comment on: http://stackoverflow.com/q/49230489
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85262546
type: Comment
comment on: http://stackoverflow.com/q/49127070
type: QuestionComment
score: 0
has text: Can you try the example from the doc ? >>> G=nx.Graph() >>> G.add_nodes_from([0,1],color='red') >>> G.add_nodes_from([2,3],color='blue') >>> G.add_edges_from([(0,1),(2,3)]) >>> print(nx.attribute_assortativity_coefficient(G,'color'))

http://stackoverflow.com/q/49263903
tagged with: python
has comment: http://stackoverflow.com/comment/85531784
has comment: http://stackoverflow.com/comment/85531609
has answer: http://stackoverflow.com/a/49264155
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85533230
answer count: 2
has comment: http://stackoverflow.com/comment/85531406
has comment: http://stackoverflow.com/comment/85531561
has body: Problem statement: I am trying to read lines from my data and and output both the forward and reverse orientation by passing my list to a function. To solve what I am trying to do, I have to pipe the function-name as string. I am making a mock test below that replicates my original problem in a simple way. my_str = 'abcdef\nijklmn\nstuv\n' my_str = my_str.rstrip('\n').split('\n') for lines in my_str: print(lines) line_list = list(lines) # I want to read both forward and reverse orientation using a function "(def orient_my_str():" # the reason to pass this into another function is because I have lots of data crunching to do in each orientation (not shown here). # but, below process typically resolves what I am trying to achieve line_rev = orient_my_str(line_list, orientation='reversed') line_fwd = orient_my_str(line_list, orientation='') print('list in reverse orientation :', line_rev) print('list in forward orientation :', line_fwd) print() # I am only want to make one function not two, because if I make two functions .. # .. I will have to copy a large amount of code below the for-loop. # there should be a way to fix this problem (calling function using string name when required and not). def orient_my_str(line, orientation): my_output = '' for item in eval(orientation)(line): my_output += item print(my_output) return my_output # But, this only works for reverse orientation. I know the issue is with passing "eval('')(line)" but was hoping it would work. I tried to fix my code using ideas from these links, Use a string to call function in Python Calling a function of a module by using its name (a string) python function call with variable but I cannot seem to work it out.
accepted answer: http://stackoverflow.com/a/49265142
tagged with: function
upvote count: 0
has comment: http://stackoverflow.com/comment/85533478
has comment: http://stackoverflow.com/comment/85531964
has title: How to call a function when using its name as string?
has answer: http://stackoverflow.com/a/49265142
has comment: http://stackoverflow.com/comment/85532092
has comment: http://stackoverflow.com/comment/85531479
possible better answer: http://stackoverflow.com/a/49264155
favorite count: 0
has comment: http://stackoverflow.com/comment/85532563
linked to: http://stackoverflow.com/q/3061
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85532933
score: -5
linked to: http://stackoverflow.com/q/4131864
tagged with: reverse
linked to: http://stackoverflow.com/q/4431216
has comment: http://stackoverflow.com/comment/85531870
has comment: http://stackoverflow.com/comment/85532588
downvote count: 5

http://stackoverflow.com/q/49188279
upvote count: 1
has comment: http://stackoverflow.com/comment/85384037
has comment: http://stackoverflow.com/comment/85383767
tagged with: opencv
type: AnsweredQuestion
has body: I am currently try to adjust the resolution of the video by opencv, according to my research, cap.set is the method to do so. thus, I write the code below: cap = cv2.VideoCapture('IMG_2957.MOV') for i in range(19): print (""+str(i)+" "+str(cap.get(i))) cap.set(3,160) #Width cap.set(4,120) #Height for i in range(19): print (""+str(i)+" "+str(cap.get(i))) very surprise, the value of "CV_CAP_PROP_FRAME_WIDTH" and "CV_CAP_PROP_FRAME_HEIGHT" remain unchanged Before the cv.set 3 1920.0 4 1080.0 And after the setting, the frame was not set as what I want After the cv.set 3 1920.0 4 1080.0 Is that we are not able to change the resolution by setting its property? Can anyone advice me the usage of .set of cv2.videocapture? More information about the version: Python 3.6.0 [MSC v.1900 64 bit (AMD64)] on win32 &gt;&gt;&gt; import cv2 &gt;&gt;&gt; cv2.__version__ '3.4.0'
accepted answer: http://stackoverflow.com/a/49189768
has comment: http://stackoverflow.com/comment/85382733
score: 1
answer count: 1
has answer: http://stackoverflow.com/a/49189768
has comment: http://stackoverflow.com/comment/85383858
tagged with: python
favorite count: 0
type: Question
has title: Unable to adjust resolution by opencv under python environment
has comment: http://stackoverflow.com/comment/85384668
downvote count: 0

http://stackoverflow.com/q/49177867
type: UnansweredQuestion
has title: Customising ttk.Frame widget
has body: I want to be able to adjust the color of a ttk.Frame() widget. I know this question has been asked numerous times here. A very useful answer was given here: Change color of "tab header" in ttk.Notebook. One can do this using style.theme_create(). I want to make a similar adjustment using ttk.Style() but cannot figure out how. Could someone explain to me how I can do this? The reason I am not using the method proposed in the above link is because there are other widgets in my code that I want to (and can) customize using ttk.Style(). import tkinter as tk from tkinter import ttk class Window(): def __init__(self, parent): self.parent = parent self.parent.minsize(width=600, height=400) self.widgets() def widgets(self): s1 = ttk.Style() s1.configure('My.TNotebook.Tab', padding=5, background='red') s1.map('My.TNotebook.Tab', background=[('selected', 'green')]) self.nb1 = ttk.Notebook(self.parent, style='My.TNotebook.Tab') self.tab1 = ttk.Frame(self.nb1) self.tab2 = ttk.Frame(self.nb1) self.tab3 = ttk.Frame(self.nb1) self.nb1.add(self.tab1, text='Tab1') self.nb1.add(self.tab2, text='Tab2') self.nb1.add(self.tab3, text='Tab3') self.nb1.place(relx=0.1, rely=0.1, width=500, height=200) self.b1 = ttk.Button(self.parent, text='Quit', command=self.quit) self.b1.place(relx=0.4, rely=0.7, height=70, width=150) def quit(self): self.parent.destroy() root = tk.Tk() app = Window(root) root.mainloop()
has comment: http://stackoverflow.com/comment/85364691
answer count: 1
tagged with: ttk
has comment: http://stackoverflow.com/comment/85373578
has comment: http://stackoverflow.com/comment/85392881
has comment: http://stackoverflow.com/comment/85392809
linked to: http://stackoverflow.com/q/22389198
score: 0
linked to: http://stackoverflow.com/q/23038356
has comment: http://stackoverflow.com/comment/85936792
tagged with: python
has answer: http://stackoverflow.com/a/49197153
type: Question
tagged with: tkinter

http://stackoverflow.com/comment/85327746
type: Comment
has text: Thanks! I like Wens solutions more since it does not use any additional libraries, but this definitely works as well.
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49161052

http://stackoverflow.com/a/49237869
type: AcceptedAnswer
has body: You can pass your conditions to dict df.replace({'c': None,'a':'s','b':'n'}) Out[164]: 1 2 3 4 5 0 s n s n None 1 s None s s None 2 n s None s n
type: Answer
answers question: http://stackoverflow.com/q/49237821
score: 2
upvote count: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49237821

http://stackoverflow.com/q/49166050
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/85337460
has answer: http://stackoverflow.com/a/49166212
tagged with: python
has answer: http://stackoverflow.com/a/49166213
has comment: http://stackoverflow.com/comment/85337458
has body: I have a "list" (emphasis on the quotes) of a list of dictionary items that I am trying to get the length of. The current format (JSON-like) of the item looks like this: x = {"fullgame":"+2","firsthalf":"Ev","secondhalf":"-1"} {"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""} {"fullgame":"-2","firsthalf":"-0.5","secondhalf":""} {"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""} {"fullgame":"-1.5","firsthalf":"-0.5","secondhalf":""} {"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""} Obviously, the length of this list would be 6 if it were formatted correctly. I have been attempting to split the items at the closing bracket or using append, but I always end up getting a printout of the length of each item (or worse). Essentially, I guess I am really just trying to turn the above object into what is printed below because I know it gets the output I am looking for... x = [{"fullgame":"+2","firsthalf":"Ev","secondhalf":"-1"}, {"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""}, {"fullgame":"-2","firsthalf":"-0.5","secondhalf":""}, {"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""}, {"fullgame":"-1.5","firsthalf":"-0.5","secondhalf":""}, {"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""},] Forgive the newbie question. I have been searching for answers to this, but have come up empty though I am sure it is pretty simple. EDIT: I am just trying to get the length of this list which is much, much longer than above 6 entries. After that I will be looping through that list skipping every 7 entries and pulling specific values and pushing them into a csv. I have had no problems with that portion of the project though
answer count: 3
upvote count: 0
downvote count: 3
has title: getting the length of a list with several lists (with dictionary items) within it
has answer: http://stackoverflow.com/a/49167222
favorite count: 0
type: Question

http://stackoverflow.com/comment/85337588
has text: @FTP okay well perhaps they are "just in time" iterated, so you'd have to do z = bob(x+0.1) which would generate *all possible parts* of the spline (or splines). I'm assuming that you are using newer versions of numpy and scipy than I have now?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49151547

http://stackoverflow.com/a/71059851
has body: I tried to reproduce the problem but - as far as I can tell - there is no interpolation happening inside of either ImageIO or Pillow: from PIL import Image import imageio as iio import numpy as np import io for _ in range(100): expected_frames = np.round(100+20*np.random.randn(10, 40, 40)).astype(np.uint8) # test writing with pillow pil_buffer = io.BytesIO() im = Image.fromarray(expected_frames[0]) gif_bytes = im.save(pil_buffer, format="GIF") actual_pil = iio.v3.imread(pil_buffer, mode="L") assert np.all(actual_pil == expected_frames[0]) # test writing with ImageIO gif_bytes = iio.v3.imwrite("<bytes>", expected_frames, format="GIF") actual_iio = iio.v3.imread(gif_bytes, index=None, mode="L") assert np.all(actual_iio == expected_frames) print("No roundtrip modified any pixels.") So I think that either There may have been a bug in Pillow or ImageIO that has since been fixed (it has been 3 years) The tool/application you used to display the second image interpolates as you zoom into the image (since that image is 200x200 px instead of being 40x40 pixels)
score: 0
answers question: http://stackoverflow.com/q/49243732
type: Answer

http://stackoverflow.com/q/49219632
has title: Python IDLE and HomeBrew updated versions
answer count: 1
downvote count: 1
favorite count: 0
has body: A while ago, I downloaded Python via its website and have been using the following ever since: 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 It is a simple editor and I am fine with it. When I enter in command line $ python3 --version, I get Python 3.5.2 obviously. A few months ago, I installed HomeBrew and ever since I have been updating my Mac's Python via $ brew update and $ brew upgrade. Today, I noticed in its updating results that my latest installed and updated Python version is python-3.6.4_4.el_capitan I went into my usr/local/bin as well as usr/bin and realized that there is a variety of versions in them. This can be seen in the two attached images: I understand the one installed in /usr/bin is provided with my OS X and is used by the system, and other instances are provided by external packages. So, I shouldn't try to remove/uninstall Python 2 then, right? How do I clean this up and make sure I only have the latest installed and updated Python 3.6.4 (the one managed via brew) and also how can I point my IDLE to this latest version? There is no option in its menus... Do I always have to go to http://www.python.org/download and install the latest from there? Is there anyway I can use 3.6.4 in my current IDLE? I know how to use 3.6.4 via Terminal, but I would like to be able to use it via my IDLE that is currently at 3.5.2 I do not have a deep knowledge of the underlying system, so when I see in other posts that somebody says change blah in the $path blah, I am not too sure how to do it. Of course there are many tutorials on this, but I worry following each one word by word might result in my doing something terrible to system files, etc... So, I would appreciate someone helping me in detail and explaining to me how I can achieve the above two (in bold) so that in the process I also learn a few things and not find command line and path related subjects daunting.
type: Question
has comment: http://stackoverflow.com/comment/85443120
tagged with: python
accepted answer: http://stackoverflow.com/a/49219721
has comment: http://stackoverflow.com/comment/85443056
has answer: http://stackoverflow.com/a/49219721
type: AnsweredQuestion
score: 0
upvote count: 1

http://stackoverflow.com/q/49272861
has answer: http://stackoverflow.com/a/49272908
tagged with: global
has comment: http://stackoverflow.com/comment/85548503
has comment: http://stackoverflow.com/comment/85548626
has comment: http://stackoverflow.com/comment/85548462
answer count: 3
has comment: http://stackoverflow.com/comment/85548647
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85548367
downvote count: 2
has comment: http://stackoverflow.com/comment/85548545
has answer: http://stackoverflow.com/a/49272921
has answer: http://stackoverflow.com/a/49273111
has comment: http://stackoverflow.com/comment/85548520
type: Question
favorite count: 0
has body: I need to read some words text by text in python, and I am getting this error. "NameError: global name 'wordList' is not defined. i=0 with fitxer as f: for line in f: for word in line.split(): wordList[i]=word i+1 return wordList
has title: global ... is not defined python
score: -2
tagged with: python

http://stackoverflow.com/q/49189637
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85401043
tagged with: scipy
accepted answer: http://stackoverflow.com/a/49197772
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49197772
answer count: 1
tagged with: scikit-learn
tagged with: python
has body: Context I'm running into an error when trying to use sparse matrices as an input to sklearn.neural_network.MLPRegressor. Nominally, this method is able to handle sparse matrices. I think this might be a bug in scikit-learn, but wanted to check on here before I submit an issue. The Problem When passing a scipy.sparse input to sklearn.neural_network.MLPRegressor I get: ValueError: input must be a square array The error is raised by the matrix_power function within numpy.matrixlab.defmatrix. It seems to occur because matrix_power passes the sparse matrix to numpy.asanyarray (L137), which returns an array of size=1, ndim=0 containing the sparse matrix object. matrix_power then performs some dimension checks (L138-141) to make sure the input is a square matrix, which fail because the array returned by numpy.asanyarray is not square, even though the underlying sparse matrix is square. As far as I can tell, the problem stems from numpy.asanyarray preventing the dimensions of the sparse matrix being determined. The sparse matrix itself has a size attribute which would allow it to pass the dimension checks, but only if it's not run through asanyarray. I think this might be a bug, but don't want to dive around filing issues until I've confirmed that I'm not just being an idiot! Please see below, to check. If it is a bug, where would be the most appropriate place to raise an issue? NumPy? SciPy? or Scikit-Learn? Minimal Example Environment Arch Linux kernel 4.15.7-1 Python 3.6.4 numpy 1.14.1 scipy 1.0.0 sklearn 0.19.1 Code import numpy as np from scipy import sparse from sklearn import model_selection from sklearn.preprocessing import StandardScaler, Imputer from sklearn.neural_network import MLPRegressor ## Generate some synthetic data def fW(A, B, C): return A * np.random.normal(.3, .1) + B * np.random.normal(.6, .1) def fX(A, B, C): return B * np.random.normal(-1, .1) + A * np.random.normal(-.9, .1) / C # independent variables N = int(1e4) A = np.random.uniform(2, 12, N) B …
tagged with: sparse-matrix
has title: Sparse Matrix error in MLPRegressor

member-variables
type: Tag
tags question: http://stackoverflow.com/q/49237781
tag name: member-variables

http://stackoverflow.com/comment/85538368
type: QuestionComment
comment on: http://stackoverflow.com/q/49267392
score: 0
has text: Yeah that is the error I got initailly, and makes sense why I got it. The documentation I have directs me to using JSON
type: Comment

http://stackoverflow.com/comment/85358712
comment on: http://stackoverflow.com/a/49176701
score: 0
type: AnswerComment
has text: Thanks @jezrael you're awesome!
type: Comment

http://stackoverflow.com/comment/85285619
comment on: http://stackoverflow.com/a/49134708
has text: Beyond that, I think we've exhausted the use of comments on this post. If you want to know how to pass a list of objects from Python to R, I would read up on that process, or post a new question.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49170787
tagged with: dataframe
tagged with: python
score: 2
upvote count: 4
type: AnsweredQuestion
answer count: 3
has body: I am working with a DataFrame that contains a large set of columns. I would like to be able to select a subset of columns that follow a given pattern. Example df = pd.DataFrame({'a_1': [1,2,3],'b': [2,3,4],'c_1': [3,4,5]}) a_1 b c_1 0 1 2 3 1 2 3 4 2 3 4 5 I would like to be able to select only the columns that are ending with _1 (this can be expressed as '.*_1' using the regular expression syntax) resulting in: a_1 c_1 0 1 3 1 2 4 2 3 5
tagged with: pandas
has answer: http://stackoverflow.com/a/49171291
has answer: http://stackoverflow.com/a/49170818
downvote count: 2
possible better answer: http://stackoverflow.com/a/49170818
has answer: http://stackoverflow.com/a/49171489
accepted answer: http://stackoverflow.com/a/49171489
tagged with: selection
favorite count: 0
tagged with: pattern-matching
type: Question
has title: Select DataFrame columns with names that follow a given pattern in pandas

http://stackoverflow.com/a/49142499
type: Answer
answers question: http://stackoverflow.com/q/49140718
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49140718
score: 3
has comment: http://stackoverflow.com/comment/85291056
has body: Your WSGIScriptAlias is misconfigured. Your app is being served by Apache relative to /foo To get the behavior you want, the alias should be for the root directory, I.E. / instead of /foo

http://stackoverflow.com/q/49254559
accepted answer: http://stackoverflow.com/a/49254719
has answer: http://stackoverflow.com/a/49254719
tagged with: pandas
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49254872
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49254872
favorite count: 0
type: Question
has body: I was wondering if there was a way to find patterns in a pandas DataFrame based on categories. I know kmeans works for numeric values but my dataframe mainly consists of categories and dates: car check jobcard date season merc A 12A 01-01-2010 Winter bmw B 45A 03-02-2010 Winter merc A 12D 10-01-2010 Winter bmw C 25C 01-05-2010 Spring vw A 62B 01-08-2010 Summer etc It goes on for about 5000 rows, the dataset represents different types of checks that required repairs after the check, and I would like to see a pattern, for instance a BMW has problems mainly in the summer, or the 12A jobcard never happens in the winter. I have already made some scatterplots, but I was not able to get any results from them: Scatterplot Is there any package that can provide a better overview or that can cluster categories in the same way kmeans does with numeric values?
answer count: 2
tagged with: cluster-analysis
tagged with: categories
tagged with: python
has title: Is there a way to find patterns based on categories in a pandas DataFrame?

http://stackoverflow.com/q/49195864
upvote count: 2
has comment: http://stackoverflow.com/comment/85398431
has answer: http://stackoverflow.com/a/49196051
score: 1
downvote count: 1
favorite count: 0
type: Question
has body: I've been reading about the following solutions here, but it only works for one IP Address only. I'm not able to print the rest of the IPs (multiple network/wireless cards). References http://net-informations.com/python/net/ipadress.htm Finding local IP addresses using Python&#39;s stdlib How do I determine all of my IP addresses when I have multiple NICs? C:\&gt;ipconfig | findstr IPv4 IPv4 Address. . . . . . . . . . . : 192.168.1.1 IPv4 Address. . . . . . . . . . . : 192.168.5.1 C:\&gt;python Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import socket &gt;&gt;&gt; print (socket.gethostbyname(socket.gethostname())) 192.168.5.1 &gt;&gt;&gt; Please let me know how to print all IP Addresses in Python. Update 1: As suggested by Rahul, I've tried the following code but it didn't return anything on the screen. c:\Python\Codes&gt;more ip.py from netifaces import interfaces, ifaddresses, AF_INET def ip4_addresses(): ip_list = [] for interface in interfaces(): for link in ifaddresses(interface)[AF_INET]: ip_list.append(link['addr']) return ip_list c:\Python\Codes&gt; c:\Python\Codes&gt;ip.py c:\Python\Codes&gt; Update 2: I've also tried Elemag's code as suggested here. It works on Python interpreter but not when I save the code to .py c:\Python\Codes&gt;python Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; &gt;&gt;&gt; [netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface in netifaces.interfaces() if netifaces.AF_INET in netifa ces.ifaddresses(iface)] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'netifaces' is not defined &gt;&gt;&gt; &gt;&gt;&gt; import netifaces &gt;&gt;&gt; [netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr'] for iface i…
answer count: 2
tagged with: windows
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85398795
has answer: http://stackoverflow.com/a/52197019
has title: How to get all IP addresses using Python (Windows)?
linked to: http://stackoverflow.com/q/166506
linked to: http://stackoverflow.com/q/270745

http://stackoverflow.com/q/49150902
has title: python parse json data in a for loop
has comment: http://stackoverflow.com/comment/85308380
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49151093
possible better answer: http://stackoverflow.com/a/49151093
tagged with: http://stackoverflow.com/tag/json
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/85306059
answer count: 2
has answer: http://stackoverflow.com/a/49150990
accepted answer: http://stackoverflow.com/a/49150990
downvote count: 0
has comment: http://stackoverflow.com/comment/85309087
upvote count: 1
score: 1
has body: i'm trying to parse my data from json. I have a function that loads all data... Data are like this: devices_infos = get_devices() { "page" : 0, "size" : 20, "totalCount" : 2, "data" : [ { "namespace" : "android", "id" : "0000001111111", "creationTs" : 1516216756819, "name" : "Eric's phone", "description" : "This device was auto registered by [mqtt] ", "tags" : [ ], "properties" : { }, "lastUpdateTs" : 1518610495832, "connected" : false, "path" : [ ], "metadata" : { "api_key_id" : "XXX000XXX000XXX", "connection_start_time" : "2018-02-14T12:14:04.778Z", "mqtt_version" : 4, "mqtt_username" : "json+device", "mqtt_timeout" : 20, "remote_addr" : "00.00.00.00/PORT" }, "groupId" : "root", "groupPath" : "/" }, { "namespace" : "sensor", "id" : "temp001", "creationTs" : 1520415684605, "name" : "mySensor001", "description" : "moisture sensor", "tags" : [ "france", "lyon" ], "properties" : { "manufacturer" : "miel", "model" : "MoistureSensorV3" }, "lastUpdateTs" : 1520415684605, "connected" : false, "path" : [ ], "groupId" : "root", "groupPath" : "/" } ] I would like to extract the name of the devices via a for loop like this: if devices_infos is not None: print('Devices are: ') for each in devices_infos['data'][0]['name']: print (each) else: print("[!] Request failed") This only print me the first device, ie Eric's phone , i would like to have too mySensor001.
favorite count: 0

http://stackoverflow.com/a/49280352
type: AcceptedAnswer
downvote count: 0
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49149932
has body: By switching to working by segments between squares of consecutive primes, creating these sets for each segment one after another. For each segment you'll have to calculate the starting point of the enumeration of a prime's multiples, for each known prime which is not greater than the segment's top value (i.e. the next "core" prime's square). The "core" primes, to get the squares of, you can get separately, independently, by a recursive application of the same algorithm. An example of this approach (the separate primes supply that is) is How to implement an efficient infinite generator of prime numbers in Python? To make it parallel, you'll need to find means to use the set in a shared fashion between all the enumerations, which each will set each of its enumerated multiples off in the same shared set. Order of operations is not important, as long as they are all finished. The access need not be guarded, as setting the same location off twice (or more) is perfectly fine. This will also be very efficient.
answers question: http://stackoverflow.com/q/49149932
score: 1

http://stackoverflow.com/a/49225192
answers question: http://stackoverflow.com/q/49222772
type: Answer
has body: Summarizing answers provided by @Wen and @jezrael (thanks a lot!) I decided to check the performance of the suggested solutions by wrapping the consecutive approaches into functions: Dataset data = pd.DataFrame( {'dates': ['2017-01-31', '2017-02-28', '2017-02-28'], 'tech': [['c++', 'python'], ['c++', 'c', 'java'], ['java']]} ) First solution - dummies def first(): pd.get_dummies(data.set_index('dates').tech.apply(pd.Series).stack()).sum(level = 0) Second solution - sklearn from sklearn.preprocessing import MultiLabelBinarizer def second(): mlb = MultiLabelBinarizer() pd.DataFrame(mlb.fit_transform(data.tech), data.dates, mlb.classes_).sum(level = 0) Third solution - tolist() def third(): (pd.DataFrame(data['tech'].values.tolist(), index = data['dates'].values) .stack() .groupby(level = 0) .value_counts() .unstack(fill_value = 0)) Performance comparison %timeit first() # 4.86 ms ± 102 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit second() # 2.09 ms ± 29 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) %timeit third() # 3.66 ms ± 256 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) Summary To sum up, all the proposed approaches brought the same result. In terms of execution time, the fastest one was the second solution, which takes advantage of MultiLabelBinarizer function imported from sklearn.
score: 0

tableau-api
type: Tag
tag name: tableau-api
tags question: http://stackoverflow.com/q/49261303

http://stackoverflow.com/comment/85389202
has text: Memory error with 11.3 Gigs?
comment on: http://stackoverflow.com/q/49188148
type: Comment
type: QuestionComment
score: 0

tweepy
tags question: http://stackoverflow.com/q/49221544
type: Tag
tags question: http://stackoverflow.com/q/49255511
tags question: http://stackoverflow.com/q/49163512
tags question: http://stackoverflow.com/q/49123098
tags question: http://stackoverflow.com/q/49233871
tags question: http://stackoverflow.com/q/49201016
tags question: http://stackoverflow.com/q/49200983
tags question: http://stackoverflow.com/q/49244096
tag name: tweepy

http://stackoverflow.com/q/49226200
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49226310
type: Question
tagged with: python-3.x
answer count: 2
possible better answer: http://stackoverflow.com/a/49226237
upvote count: 1
has title: (if exists) get an element from a structured JSON with Python 3.6
has answer: http://stackoverflow.com/a/49226237
accepted answer: http://stackoverflow.com/a/49226310
linked to: http://stackoverflow.com/q/24898797
favorite count: 0
has comment: http://stackoverflow.com/comment/85560263
type: AnsweredQuestion
score: 0
has body: In this answer I understand that I can use the GET instruction to catch an element of a JSON file and get a None if this does not exists. But I can't understand how to use with more than one level of JSON data. Let's have a look at the following example: import json json_input = '{"persons": [{"name": "Brian", "city": "Seattle"}, {"name": "David", "city": "Amsterdam"} ] }' d = json.loads(json_input) Input d.get('persons') output [{'name': 'Brian', 'city': 'Seattle'}, {'name': 'David', 'city':'Amsterdam'}] Input d.get('animals') output None but I would like to use the same to check if d['persons'][0]['name'] exist, or if d['persons'][0]['tel_number']. If I use d.get(['persons'][0]['name']) I get the following error: Traceback (most recent call last): File "", line 1, in d.get(['persons'][0]['name']) TypeError: string indices must be integers
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/49254799
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/85512830
tagged with: pandas
type: AnsweredQuestion
has title: Update 2 columns for a single case condition
has body: df['RULE'] = 0 df['COLUMN'] = 0 df.ix[((df['IND'].str.upper() == 'YES')), 'RULE'] = 1 The above code help me to update Column 'RULE' as 1 if Indicator is 'YES'. How can I update one more column in the same line. Or should i write one more line of the above code to update the second column. I want to update COL2 also, as 2. Columns 'Rule' and 'Column' are defaulted to '0' IND RULE COL2 YES 1 2 NO 0 0 YES 1 2
score: 1
accepted answer: http://stackoverflow.com/a/49254829
favorite count: 0
has answer: http://stackoverflow.com/a/49254829
type: Question
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49169012
accepted answer of: http://stackoverflow.com/q/49168695
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85343066
has body: You set window2 = None window1 = None as global variables and then define the command function for button2 to be lambda: newScreen(window2, window1) Which calls newScreen with the values window2 and window1 which are both None, hence the error. The underlying issue here is your setWindow function: def setWindow(windowEnter): global window window = windowEnter window = Tk() window.attributes("-fullscreen", True) which doesn't work the way you are using it. When you call setWindow(window1), you pass the value of window1, what the function does with the variable cannot be seen on a global scope. A quick example would be this: def increment(a): a +=1 x = 1 print(x) increment(x) print(x) which will print 1 twice. To achieve what you want I suggest you use a dictionary to keep track of your windows. from tkinter import * def hello(): print("U pressed it lol") global window1, window2 windows = {} def setWindow(window_name): windows[window_name] = Tk() windows[window_name].attributes("-fullscreen", True) def newScreen(newScreen_name, screenToDelete_name): setWindow(newScreen_name) print("New Window Created") windows[screenToDelete_name].destroy() del windows[screenToDelete_name] #delete invalid entry from dict print("He ded lol") setWindow("window1") def setStuff(): button = Button(windows["window1"], text="hey", command=hello) label = Label(windows["window1"], text="YoYoYo My dude") button2 = Button(windows["window1"], text="Next Page", command = lambda: newScreen("window2", "window1")) button.pack() label.pack() button2.pack() setStuff() Note on the side: previously your function was def newScreen(newScreen, screenToDelete), which is very confusing/bad style since both the function and its first argument share the same name. I changed it anyway to highlight that it now takes strings as arguments, but keep it in mind for the furture.
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49168695
upvote count: 2
has comment: http://stackoverflow.com/comment/85343252

http://stackoverflow.com/comment/85480516
has text: If you omit that column it's actually a lot easier.
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49238332
type: Comment

http://stackoverflow.com/comment/85347533
type: QuestionComment
comment on: http://stackoverflow.com/q/49171254
score: 0
type: Comment
has text: Print out `item` in `for item in path`. Do you get a list of file names, or a list of letters? Just re-use the `drx` list that you already gathered.

http://stackoverflow.com/comment/85329574
type: AnswerComment
has text: I ran your code on pandas 0.22.0 (I just installed it) and it does return the NaN, maybe the version you were running on had a bug
comment on: http://stackoverflow.com/a/49154226
type: Comment
score: 0

http://stackoverflow.com/comment/85399550
type: Comment
type: QuestionComment
has text: Is there a format I can write the output to so the colors are shown when I do less on it?
score: 0
comment on: http://stackoverflow.com/q/49197280

http://stackoverflow.com/q/49228683
upvote count: 1
type: UnansweredQuestion
downvote count: 1
has comment: http://stackoverflow.com/comment/85462909
has title: Exporting max values of different csv files in to one
favorite count: 0
type: Question
has body: I got 3 datasets which contain the flow in m3/s per location. Dataset 1 is a 5 year ARI flood, Dataset 2 is a 20 year ARI flood and Dataset 3 is a 50 year ARI flood. Per location I found the maximum discharge (5,20 &amp; 50) Code: for key in Data_5_ARI_RunID_Flow_New.keys(): m = key y5F_RunID = Data_5_ARI_RunID_Flow_New.loc[:,m] y20F_RunID = Data_20_ARI_RunID_Flow_New.loc[:,m] y50F_RunID = Data_50_ARI_RunID_Flow_New.loc[:,m] max_y5F = max(y5F_RunID) max_y20F = max(y20F_RunID) max_y50F = max(y50F_RunID) Max_DataID = m, max_y5F, max_y20F, max_y50F print (Max_DataID) The output is like this: ('G60_18', 44.0514, 47.625, 56.1275) ('Area5_11', 1028.4065, 1191.5946, 1475.9685) ('Area5_12', 1017.8286, 1139.2628, 1424.4304) ('Area5_13', 994.5626, 1220.0084, 1501.1483) ('Area5_14', 995.9636, 1191.8066, 1517.4541) Now I want to export this result to a csv file, but I don't know how. I used this line of code, but it didn't work: Max_DataID.to_csv(r'C:\Users\Max_DataID.csv', sep=',', index = False)
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85461626
tagged with: python
has comment: http://stackoverflow.com/comment/85461090
has answer: http://stackoverflow.com/a/50427231
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/49228886
answer count: 2

http://stackoverflow.com/a/49144278
has comment: http://stackoverflow.com/comment/85332589
has comment: http://stackoverflow.com/comment/85332541
has body: You can't ignore SyntaxError. It's not a warning, it's an error.
answers question: http://stackoverflow.com/q/49144064
type: Answer
score: 0

http://stackoverflow.com/a/49169476
has comment: http://stackoverflow.com/comment/85344496
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49169328
has body: First up, you should post your code inside your text and not in seperate images. Just indent each line with four spaces to format it as code. You can simply read in a file line by line, change the lines you want to change and then write the output. with open(infile, 'r') as f_in, open(outfile, 'w') as f_out: for line in f_in: output_line = edit_line(line) f_out.write(output_line) Then you just have to write a function that does the string replacement.

http://stackoverflow.com/a/49128699
has body: If all you're trying to remove is b and :, you can use a nested list comprehension with a set membership test: a_new = [[y for y in x if y not in {'b', ':'}] for x in a] Although, if you'd like to generalise this to remove any non-numeric element, filter with an isinstance check: import numbers a_new = [[y for y in x if isinstance(y, numbers.Number)] for x in a] Note that this is the same as: a_new = [] for i in a: a_new.append([]) for j in i: if isinstance(j, numbers.Number): a_new[-1].append(j) Note that you only need 2 loops here (your code has 3 which is why everything is replicated 3 times - the number of items in each inner list!). print(a_new) [[1, 2], [3, 4], [5, 6]] Another note here, numbers.Number is an injected superclass of any numeric value (including irrational values). If your use case does not include complex numbers, you may instead want to use numbers.Rational or numbers.Real. Final note, as mentioned here, please don't use list/dict other such names as variables, they end up shadowing the actual builtins.
accepted answer of: http://stackoverflow.com/q/49128622
has comment: http://stackoverflow.com/comment/85262065
answers question: http://stackoverflow.com/q/49128622
has comment: http://stackoverflow.com/comment/85262034
type: Answer
has comment: http://stackoverflow.com/comment/85262115
score: 5
upvote count: 5
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85488218
type: Comment
score: 0
type: AnswerComment
has text: Removing the last line worked! Thank you. If you want to edit your answer I'll accept as correct.
comment on: http://stackoverflow.com/a/49241482

http://stackoverflow.com/a/71052332
downvote count: 0
score: 2
type: Answer
answers question: http://stackoverflow.com/q/49188960
upvote count: 2
has body: I may be off the mark but I came to this thread with the same type of problem I found this is the simple answer if you want to see everything in a long list and the index. This is what I use in Spyder: print(df.info()) or this be what is needed in Jupyter: df.info()

http://stackoverflow.com/comment/85436244
type: Comment
has text: oh i didn't see you don't want letters reversed, you can double sort for that
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49216101

http://stackoverflow.com/comment/85316612
comment on: http://stackoverflow.com/q/49152812
has text: Or how about a third Race class, which uses a set of Players and a Course. Move the code to run the course (or race) there. Anyway, I agree with JETM that this should go on Code Review SO.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49266333
has comment: http://stackoverflow.com/comment/85620199
has comment: http://stackoverflow.com/comment/85589467
score: 0
has comment: http://stackoverflow.com/comment/85572858
has comment: http://stackoverflow.com/comment/85616019
type: Answer
has comment: http://stackoverflow.com/comment/85830393
accepted answer of: http://stackoverflow.com/q/49176813
has comment: http://stackoverflow.com/comment/86793721
has comment: http://stackoverflow.com/comment/85617533
has comment: http://stackoverflow.com/comment/85587331
answers question: http://stackoverflow.com/q/49176813
has body: It seems to be a json serialization compability issue. The backend failed to recognize the serialized label map. I'm working to see if it can be fixed on our side but it may need quite a bit to roll out. As a mitigation, in short term you can do replacements as the following in the template file (there should be 2 occurrences). FROM: "labels": {"foo" : "bar"} TO: "labels": [{"key" : "foo"}, {"value" : "bar"}] And see if it works. Sorry for inconvenience.
has comment: http://stackoverflow.com/comment/85617494
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85663411
has comment: http://stackoverflow.com/comment/85575076
has comment: http://stackoverflow.com/comment/85746235
has comment: http://stackoverflow.com/comment/85812233

http://stackoverflow.com/comment/85255553
has text: Can give me example idea.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49125359

http://stackoverflow.com/comment/85346373
score: 0
type: Comment
has text: Thanks a lot! This was the issue sudo apt-get update W: GPG error: http://ppa.launchpad.net trusty InRelease: The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 5BB92C09DB82666C + sudo apt-get -yq install python3.5 E: There are problems and -y was used without --force-yes
comment on: http://stackoverflow.com/a/49158482
type: AnswerComment

http://stackoverflow.com/comment/85315263
type: QuestionComment
comment on: http://stackoverflow.com/q/49155330
has text: https://xkcd.com/292/
score: 6
type: Comment

http://stackoverflow.com/comment/85532735
has text: I think you want `grouped = grouped1.merge( grouped2, axis=1)`
type: QuestionComment
comment on: http://stackoverflow.com/q/49264407
type: Comment
score: 1

http://stackoverflow.com/q/49149932
has answer: http://stackoverflow.com/a/49240350
has answer: http://stackoverflow.com/a/49280352
has body: I have code like below def yield_multiple(): for prime in prime_list: for multiple in range(prime+prime, end, prime): yield multiple And I use this to get the prime numbers multiple_set = set(yield_multiple()) result = [v for v in candidate_list if v not in multiple_set] And I meet the memory error when the set is very large, so I was thinking to use this to save the memory result = [v for v in candidate_list if v not in yield_multiple()] But this will get the wrong result. So, How to avoid memory error to get the prime numbers correctly? Here's my improved solution without too much memory to use. import math import sys import time from mpi4py import MPI import eratosthenes comm = MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() TAG_RESULT = 0 n = sys.argv[1] if n.isdigit(): start_time = time.time() n = int(n) sqrt_n = int(math.sqrt(n)) task_per_block = int(math.ceil((n - 1) / size)) begin = 2 + rank * task_per_block end = begin + task_per_block if begin + task_per_block &lt;= n + 1 else n + 1 if rank == 0: begin = sqrt_n if sqrt_n &lt; end else begin sieve_list = [True] * (end - begin) prime_list = eratosthenes.sieve(sqrt_n) if rank == 0: result = sum(prime_list) for prime in prime_list: start = begin if begin % prime == 0 else (int(begin / prime) + 1) * prime for multiple in range(start, end, prime): sieve_list[multiple - begin] = False result += sum(i + begin for i, v in enumerate(sieve_list) if v) result_received = 0 while result_received &lt; size - 1: data = comm.recv(source=MPI.ANY_SOURCE, tag=TAG_RESULT) result += data result_received += 1 print(result) print(time.time() - start_time) else: for prime in prime_list: start = begin if begin % prime == 0 else (int(begin / prime) + 1) * prime for multiple in range(start, end, prime): sieve_list[multiple - begin] = False result = sum(i + begin for i, v in enumerate(sieve_list) if v) comm.send(result, dest=0, tag=TAG_RESULT)
score: 1
has comment: http://stackoverflow.com/comment/85565812
tagged with: python
tagged with: concurrency
linked to: http://stackoverflow.com/q/2211990
tagged with: primes
has comment: http://stackoverflow.com/comment/85568871
tagged with: sieve-of-eratosthenes
type: Question
tagged with: parallel-processing
answer count: 2
has comment: http://stackoverflow.com/comment/85564042
has comment: http://stackoverflow.com/comment/85304537
has comment: http://stackoverflow.com/comment/85543703
has comment: http://stackoverflow.com/comment/85563142
downvote count: 0
has comment: http://stackoverflow.com/comment/85480019
upvote count: 1
favorite count: 0
has title: Python generator and set(generator) get different results
possible better answer: http://stackoverflow.com/a/49240350
accepted answer: http://stackoverflow.com/a/49280352
linked to: http://stackoverflow.com/q/2068372
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85565191
has comment: http://stackoverflow.com/comment/85304293
linked to: http://stackoverflow.com/q/12559788

http://stackoverflow.com/q/49148877
tagged with: python
has body: I'm using the Adafruit DHT11 Library for my temperature sensor. Sometimes the value that I get form that reading can't be converted to a float (I really don't know what kind of var type that is it only comes out every like 50 readings). Whenever this happens my script stops working with the error code: float() argument must be a string or a number. The piece of code where this would be important is: mid = sum(list)/len(list) print mid humidity, temperature = Adafruit_DHT.read_retry(11,4) temp = float(temperature) if mid + 3 &gt; temp &gt; mid - 3: del list[0] print 'all safe %d' % (temp) list.append(temp) Isn't there some way to make an if expression where the temperature variable is tested before the conversion. The result if it isn't convertible would just be to skip the whole code and start at the beginning for a new reading.
score: -1
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49148969
answer count: 3
linked to: http://stackoverflow.com/q/12265451
has answer: http://stackoverflow.com/a/49149028
upvote count: 0
has title: Only let the script continue if the variable can be converted by float()
has comment: http://stackoverflow.com/comment/85302246
has comment: http://stackoverflow.com/comment/85302348
accepted answer: http://stackoverflow.com/a/49149011
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49149011
linked to: http://stackoverflow.com/q/23294658
has answer: http://stackoverflow.com/a/49148969
has comment: http://stackoverflow.com/comment/116086367

http://stackoverflow.com/q/49124214
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85253657
has body: I am trying to create a data loader for an OCR system. I have 1k document images in which each document contains roughly 200 lines of text. Presently I am extracting each line image along with its ground truth and then append them to a list. I was wondering if there are any efficient data structure where I can quickly store and retrive data without hogging too much memory. class OCRDataset(tud.Dataset): def __init__(self, **kwargs): self.config = kwargs['config'] self.dir = self.config['dir'] self.books = self.config["books"] def __len__(self): return len(self.books) def __getitem__(self, idx): pagewise = read_book(book_path=os.path.join(self.dir, self.books[idx])) sequences, targets = pagewise samples = [(sequences[i], targets[i]) for i in range(len(sequences))] return samples total = [] dataset = OCRdataset(config=config) for i in range(len(dataset)): sample = dataset[i] total.extend(sample) As you can see the class OCRdataset takes a book and returns a list of tuples containing images and annotations. I have several such books and I iterate through each book using a for loop and then extend the list total after every iteration. The bottle neck is that after extending the list for first few books my system eventually starts to slow down. I would be grateful if anybody can suggest a better way of doing this. Thank You EDIT: The idea behind using the total list is to load data from multiple books into a single data structure which will then allow me to split the data into training and validation set and then subsequently use it for traing my classifier. EDIT 2: The function read_book takes a collection of document images and returns the list of tuples containg line images along with their annotations for a particular book.
has comment: http://stackoverflow.com/comment/85253620
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49124337
has comment: http://stackoverflow.com/comment/85253858
has comment: http://stackoverflow.com/comment/85253838
tagged with: python
score: -1
tagged with: data-structures
has comment: http://stackoverflow.com/comment/85253988
has title: What are some efficient data structures in python to store and process large dataset?
has comment: http://stackoverflow.com/comment/85253951
has comment: http://stackoverflow.com/comment/85253666
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85254199
downvote count: 2

http://stackoverflow.com/a/49224732
score: -1
answers question: http://stackoverflow.com/q/49224336
has comment: http://stackoverflow.com/comment/85453752
upvote count: 0
downvote count: 1
has body: simply you can start new line after each print or sys stdout stream output by specify "\n" (ex: print ("hello" + "\n" then your application will write to diffrent lines
type: Answer

http://stackoverflow.com/q/49140391
tagged with: pyqt5
has title: PyQT5 Button Click to remove a label based on boolean values
has comment: http://stackoverflow.com/comment/85287102
has comment: http://stackoverflow.com/comment/85287015
has comment: http://stackoverflow.com/comment/85290678
has comment: http://stackoverflow.com/comment/85287957
has comment: http://stackoverflow.com/comment/85287612
has comment: http://stackoverflow.com/comment/85288370
tagged with: python
has body: What I'm trying to do is based on the idea that "if a button was clicked" the "display area" of my little app it'll draw additional labels buttons check buttons, and remove these based on if other buttons are pushed. The issue is that this will show my new label but it wont remove it, it'll actually make the text darker. So... if button1 == True: show the additional widgets else: hide these additional widgets import sys from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton, QLabel from PyQt5.QtGui import QIcon, QPixmap from PyQt5.QtCore import pyqtSlot class App(QMainWindow): def __init__(self): super().__init__() self.title = 'test app' self.left = 0 self.top = 0 self.width = 800 self.height = 400 self.statusBarMessage = "Status Bar Test" self.currentSprite = 'test.png' self.btn1Active = False self.btn2Active = False self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.statusBar().showMessage(self.statusBarMessage) # Set up the buttons btn1 = QPushButton('Set Up', self) btn1.setToolTip('Click me for an initial setup') btn1.resize(100,100) btn1.move(0,0) btn1.clicked.connect(self.btn1_clicked) btn2 = QPushButton('Set Up', self) btn2.setToolTip('Click me for an initial setup') btn2.resize(100,100) btn2.move(100,0) btn2.clicked.connect(self.btn2_clicked) spriteHelper = QLabel(self) spriteHelper.move(600,100) spriteHelper.setPixmap(QPixmap(self.currentSprite)) spriteHelper.resize(200,280) #Display the area self.show() # I've tried moving this around in different areas without any luck self.testLabel = QLabel(self) @pyqtSlot() def btn1_clicked(self): print("Button 1 is clicked") self.btn1Active = True self.btn2Active = False self.currentSprite = 'win_blank_frown.png' print(self.btn1Active) self.statusBarMessage = "Button 1 was clicked" self.statusBar().showMessage(self.statusBarMessage) print(self.btn2Active) # If the button was clicked and the boolean is true # then cre…
has comment: http://stackoverflow.com/comment/85288079
tagged with: qpushbutton
type: Question
score: 0
answer count: 0
tagged with: pyqt
type: UnansweredQuestion

http://stackoverflow.com/a/49654021
has body: You may have a folder /usr/local/lib/python2.7/site-packages with your old packages... In such a case you can list the installed packages with ls
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49131554

http://stackoverflow.com/a/69541512
score: 0
answers question: http://stackoverflow.com/q/49277640
has body: Easiest solution: convert pandas.core.series.Series to integer! my_code = int(df[df['Fruit'] == 'blueberry']['Code']) print(my_code) Outputs: 5
type: Answer

http://stackoverflow.com/comment/85300121
score: 1
type: QuestionComment
has text: If you are in interactive mode (which it sounds like you are) then you shouldn't need to call `show()`. `ax.plot()` should update the figure
comment on: http://stackoverflow.com/q/49147612
type: Comment

magic-numbers
tag name: magic-numbers
tags question: http://stackoverflow.com/q/49160576
type: Tag

http://stackoverflow.com/comment/85434676
comment on: http://stackoverflow.com/a/49212101
type: AnswerComment
has text: Yeah, it is a weird problem indeed. Marked as answer for getting me pretty much 95% of the way there and explaining the BOM. Thanks again for your help.
type: Comment
score: 0

http://stackoverflow.com/comment/85512190
comment on: http://stackoverflow.com/q/49254129
score: 0
type: Comment
type: QuestionComment
has text: @Sam put the same in `D:\Softwares\python\WinPython-64bit-3.4.4.4Qt5\python-3.4.4.amd64\nltk_data` and `D:\Softwares\python\WinPython-64bit-3.4.4.4Qt5\python-3.4.4.amd64\nltk_data\tokenizers`, it started working!!!

http://stackoverflow.com/comment/85405027
comment on: http://stackoverflow.com/q/49199891
score: 0
has text: I realized, i forgot to show the output. sorry for that. the output should look like this new Pandas Object --> date: 1.1.2018;1.1.2018;1.1.2018;31.12.2017;28.12.2017;27.12.2017;1.1.2018;31.1.2017;28.1.2017
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49263508
has comment: http://stackoverflow.com/comment/85531130
has comment: http://stackoverflow.com/comment/85530775
has answer: http://stackoverflow.com/a/49264036
has comment: http://stackoverflow.com/comment/85530933
has comment: http://stackoverflow.com/comment/85531054
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49263548
has comment: http://stackoverflow.com/comment/85531199
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has title: Skip first lines of CSV in Python - does not work? Why?
has answer: http://stackoverflow.com/a/49263548
tagged with: python
has body: My csv data looks like as follows: $('table').each(function(index) { $(this).find('tr').each(function() { $(this).find('td:first-child').each(function(i) { var a; var b; var c; $(this).find('a:first').each(function(i) { a = $(this).text(); }); $(this).find('p:first').each(function(i) { b = ($(this).text()); }); $(this).find('time:first').each(function(i) { c = $(this).text(); }); console.log(a + ";" + b + ";" + c); }); }); }); XA452:01 Description in Column 1;ID Column1;13.03.2018 AY102:22 Description in Column 2;ID Column2;13.03.2018 BC001:31 Description in Column 3;ID Column3;13.03.2018 DE223:34 Description in Column 4;ID Column4;13.03.2018 FG315:56 Description in Column 5;ID Column5;13.03.2018 HA212:34 Description in Column 6;ID Column6;13.03.2018 EE111:12 Description in Column 7;ID Column7;13.03.2018 I want to start parsing the data where the row begins with XA452:01. I tried this: import pandas as pd testimport_data = pd.read_csv("C:/Users/fff/Desktop/test_data.txt", sep=";", skiprows = 19) print(testimport_data) It should work, shouldn't it be? However, I get the following error message: Traceback (most recent call last): File "C:/Users/fff/PycharmProjects/Test/Test.py", line 3, in &lt;module&gt; testimport_data = pd.read_csv("C:/Users/fff/Desktop/test_data", sep=";", skiprows = 19) File "C:\Users\fff\PycharmProjects\Test\venv\lib\site-packages\pandas\io\parsers.py", line 709, in parser_f return _read(filepath_or_buffer, kwds) File "C:\Users\fff\PycharmProjects\Test\venv\lib\site-packages\pandas\io\parsers.py", line 449, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File "C:\Users\fff\PycharmProjects\Test\venv\lib\site-packages\pandas\io\parsers.py", line 818, in __init__ self._make_engine(self.engine) File "C:\Users\fff\PycharmProjects\Test\venv\lib\site-packages\pandas\io\parsers.py", line 1049, in _make_engine self._engine = CParserWrapper(self.f, **self.options) File "C:\Users\fff\PycharmProjects\Test\venv\lib\site-packages\pandas\io\parsers…
tagged with: rows
tagged with: readfile
type: Question
has comment: http://stackoverflow.com/comment/85531379
possible better answer: http://stackoverflow.com/a/49264036
answer count: 2

http://stackoverflow.com/a/49206096
type: Answer
has comment: http://stackoverflow.com/comment/85747420
accepted answer of: http://stackoverflow.com/q/49206051
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49206051
upvote count: 1
has body: You can use tensordot or reduce_sum: a = tf.constant(np.random.rand(2, 3, 5, 7)) b = tf.constant(np.random.rand(7)) tf.tensordot(a, b, [-1, -1]) # &lt;tf.Tensor 'Tensordot_1:0' shape=(2, 3, 5) dtype=float64&gt; tf.reduce_sum(a * b, axis=-1) # &lt;tf.Tensor 'Tensordot_1:0' shape=(2, 3, 5) dtype=float64&gt;
score: 1

http://stackoverflow.com/q/49135821
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49135849
has title: Pandas: How to add number of the row within grouped rows
has body: so I have DataFrame: &gt;&gt;&gt; df2 text 0 0 a 0 1 b 0 2 c 0 3 d 1 4 e 1 5 f 1 6 g 2 7 h 2 8 1 How do I create another column, which contains counter for each row within an level=0 index? I have tried the following code (i need to get df['counter'] column): current_index = '' for index, row in df.iterrows(): if index[0] != current_index: current_index = index[0] df[(df.index == current_index)]['counter'] = np.arange(len(df[(df.index == current_index)].index)) and following code as well: df2 = pd.DataFrame() for group, df in df1.groupby('level_0_column'): df0 = df0.sort_values(by=['level_1_column']) df['counter'] = list(df.reset_index().index.values + 1) df2 = df2.append(df0) I have around 650K rows in DataFrame... goes to infinite loop. Please advice
type: AnsweredQuestion
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: pandas-groupby
tagged with: pandas
tagged with: group-by
accepted answer: http://stackoverflow.com/a/49135849

http://stackoverflow.com/q/49202386
tagged with: python
type: Question
score: 0
answer count: 2
type: UnansweredQuestion
has title: Use a lookup table to fill nans in another table pandas
upvote count: 1
has answer: http://stackoverflow.com/a/49203333
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49202783
tagged with: lookup
tagged with: pandas
has body: I have the following dataframe df1: col_a | col_b | =============== 101 | abc | 102 | def | 103 | NaN | 104 | pqr | 105 | NaN | I want to fill these NaN values with the correct value using a corresponding lookup table lookup_df that looks like this: val_a | val_b | =============== 101 | abc | 102 | def | 103 | ghi | 104 | pqr | 105 | stu | I know that I can do a left merge, but since it is possible to have the same value in col_a, I want to essentially just fill all NANs by looking at lookup_df. Thanks.

3d
tags question: http://stackoverflow.com/q/49236389
tags question: http://stackoverflow.com/q/49209846
tags question: http://stackoverflow.com/q/49230967
type: Tag
tag name: 3d
tags question: http://stackoverflow.com/q/49166416
tags question: http://stackoverflow.com/q/49180957
tags question: http://stackoverflow.com/q/49219586
tags question: http://stackoverflow.com/q/49268918

http://stackoverflow.com/comment/85248764
has text: Also, any pointers as to how I can set the canvas size in this instance?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49121550
score: 0

http://stackoverflow.com/a/49154225
type: Answer
answers question: http://stackoverflow.com/q/49154153
downvote count: 0
score: 1
upvote count: 1
has body: Your coursesFilter already a list object , do not need add [] df2[df2['col2'].isin(coursesFilter)] Out[410]: col2 col3 col4 name 0 acct 1 1 bil

http://stackoverflow.com/q/49269267
accepted answer: http://stackoverflow.com/a/49269550
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49269550
type: AnsweredQuestion
score: 0
has body: I have the following python code using Bottle framework: # -*- coding: utf-8 -*- from bottle import route, request, template def foo(number): return [number,number+1,number+2] @route('/test') def test(): return template('test') And the template test: Lorem Ipsum % for item in foo(2): item % end But I get NameError: name 'foo' is not defined Is it possible in Simple Template to call external python functions?
tagged with: bottle
has title: Bottle / SimpleTemplate - Call python function from a template
type: Question

http://stackoverflow.com/a/49269709
downvote count: 0
has body: My problem is, despite explicitly declaring the lap times as 'float' before appending them into the list, they are still getting stored as strings. You have done no such thing. Python doesn't have variable declarations. You have simply called the float type constructor and passed it a string as an argument. It returns the float value you are expecting, but you never capture its output, and it is immediately discarded. Instead, do: lapTimes.append(float(lap))
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49269684
has comment: http://stackoverflow.com/comment/85542516

http://stackoverflow.com/a/49165104
has comment: http://stackoverflow.com/comment/85335815
type: Answer
score: 0
has body: If I understand your code correctly, you don't need to use while. All you need is if..elif..else Try this: print("\t\tWelcome to Bible Champion!\n " "It can be difficult to remember the characters of the bible.\n " "Bible Champion makes it fun and easy with trivia " "style questions!\n") name =(input("Please enter your first name to get started: ")) print() name1 = name[1:] + name[0] + "ay" + "7" print("Here is player one's game name:",name1,"\n") qf= open("/Users/eon/Downloads/linex.txt", "r") for i in range(2): question = qf.readline() answer = False while answer == False: print (question) user_ans = str(input()) if user_ans[0] =="a" or user_ans[0] == "a.": answer = True # increment score here print ("Correct") elif user_ans[0] =="b" or user_ans[0] == "b.": print ("Incorrect") elif user_ans[0] =="c" or user_ans[0] == "c.": print ("Incorrect") elif user_ans[0] =="d" or user_ans[0] == "d.": print ("InCorrect") qf= open("/Users/eon/Downloads/linex.txt", "r") for i in range(4): question = qf.readline() answer = False while answer == False: print (question) user_ans = str(input()) if user_ans[0] =="a" or user_ans[0] == "a.": answer = True # increment score here print ("Correct") elif user_ans[0] =="b" or user_ans[0] == "b.": print ("Incorrect") elif user_ans[0] =="c" or user_ans[0] == "c.": print ("Incorrect") elif user_ans[0] =="d" or user_ans[0] == "d.": print ("InCorrect") qf.close()
has comment: http://stackoverflow.com/comment/85335778
has comment: http://stackoverflow.com/comment/85335963
answers question: http://stackoverflow.com/q/49165003

http://stackoverflow.com/comment/85381150
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49162202
has text: @Ma The optimization step requires additional tweakings, which hinders the use of model.fit

http://stackoverflow.com/comment/85594468
score: 0
type: Comment
type: QuestionComment
has text: @Nae thanks for your suggestions! I have read some related questions (a lot of which were answered by Bryan Oakley) that helped me very much.
comment on: http://stackoverflow.com/q/49252844

http://stackoverflow.com/q/49132403
tagged with: sorting
answer count: 1
favorite count: 0
tagged with: time-series
type: Question
accepted answer: http://stackoverflow.com/a/49133227
tagged with: datetime
has answer: http://stackoverflow.com/a/49133227
tagged with: python
has body: I have a dataframe like this index value 2014-05-21 09:00:00 0 2014-05-22 10:00:00 23.66 2014-05-22 11:00:00 7.54 2014-05-22 12:00:00 17.83 ... 2017-07-10 23:00:00 9.43 the index is time (time step is 'hour') and first column is the value. And now I would like to make a new dataframe which looks ike this index value 2014-05-21 [NaN, NaN, NaN ... 23.66, 7.54, 17.83, ...] 2014-05-22 [2.64, 7.43, 9.88, 0, 13.4, ... ] 2014-05-23 [ ... ] ... 2017-07-10 [ ... , 9.43] the index is time (time step is 'day') and the value is a numpy arrange(or list ) that each one contain 24 values inside (24 hours data), and like the data in the first day, the missing data would automatically replace by "NaN" Because in the end I would like to calculate the annual mean as below (ex. named df_average) index value 1 [0.5, 5.67, 12.32, ... , 13.21] 2 [ 0, 13.65, 2.34, ... , 2.45 ] 3 [... ] ... 365 [... ] which the column "value" could still show the average hourly value (24 values inside) and the time series(index) are 365 or 365 (a year). and the "NaN" would be automatically skipped when calculating the average. I tried some way but the missing value still confused me, and the code looks stupid and lengthy, do anyone have a better or smart way to solve it? thanks in advance.
tagged with: pandas
has title: Time series sorting and insufficient part replace by NaN in python
upvote count: 2
type: AnsweredQuestion
score: 2
downvote count: 0

http://stackoverflow.com/q/49126825
has comment: http://stackoverflow.com/comment/85258258
upvote count: 2
accepted answer: http://stackoverflow.com/a/49127048
downvote count: 2
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85258379
type: Question
has comment: http://stackoverflow.com/comment/85258339
has body: I have a multi threaded application in Python 3 and have a setter and getter method of a list. The setter method appends an element to the list, while the getter method deletes all elements of the list after returning them. The setter method looks like the following, which is in a larger async function: while self.semaphor: print("waiting...") time.sleep(0.001) self.semaphor=True self.messages.append(msg) print("appended data!") While the getter method looks like the following: while self.semaphor: time.sleep(0.001) self.semaphor = True l = self.messages self.messages = [] self.semaphor = False if len(l) == 0: return None else: return l However the application crashes without any error messages (probably hidden due to multithreaded output in the command line) right after the prinst statetement "append data" - So I was wondering if the code snippets are thread safe and correct?
has comment: http://stackoverflow.com/comment/85258685
tagged with: multithreading
tagged with: python
has answer: http://stackoverflow.com/a/49127048
has comment: http://stackoverflow.com/comment/85258287
has comment: http://stackoverflow.com/comment/85258462
has title: When lists are thread safe in python, is it safe to delete them?
has comment: http://stackoverflow.com/comment/85258415
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85258522
score: 0

http://stackoverflow.com/q/49139443
tagged with: python-3.x
has body: How to explicitly define any variable as static in Python so that only one copy of it is created in memory and whenever the program is executed only that copy is modified and not every time a new copy is generated.
type: Question
has title: How to explicitly define a variable as static in python
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85327309
score: -3
downvote count: 4
has answer: http://stackoverflow.com/a/49139478
has comment: http://stackoverflow.com/comment/85285014
has comment: http://stackoverflow.com/comment/85284209
answer count: 1
has comment: http://stackoverflow.com/comment/85284645
favorite count: 0

http://stackoverflow.com/q/49272943
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: object-detection
has answer: http://stackoverflow.com/a/49619786
downvote count: 0
upvote count: 1
score: 1
answer count: 1
has title: Reduction axis 1 is empty in shape [9,0]
has body: I'm trying to train a custom object detection model using faster_rcnn_resnet101 model as base and it's checkpoint. But I've been hitting the same issue on 2 different data sets. These are the config file for the training session pipeline.config And I'm converting the data set to the TFRecord format with this script tf_record.py After running this command python object_detection/train.py --logtostderr --pipeline_config_path=${PIPELINE_CONFIG} --train_dir=${PATH_TO_TRAIN_DIR} This is the final output InvalidArgumentError (see above for traceback): Reduction axis 1 is empty in shape [9,0] [[Node: Loss/RPNLoss/Match/cond/ArgMax_1 = ArgMax[T=DT_FLOAT, Tidx=DT_INT32, output_type=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](Loss/RPNLoss/Match/cond/Shape_1/Switch:1, Loss/RPNLoss/Match/cond/ArgMax_1/dimension)]] The full stack trace is here There has been a similar issue posted here, but the solution of the author has not helped. Or am I extra "dumb" and not seing the obvious error
linked to: http://stackoverflow.com/q/44995679
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/a/49186432
has comment: http://stackoverflow.com/comment/85378375
has body: The problem is in how re.findall is returing data it seems that data is a list containing one string.check len(data) ,it should return one. You need to reprocess it . Another thing is that your dictionary keys are not string,they are being treated as variable that are not defined. you need to make them as strings as show below new_list=[{'ID':0,'N':'2ndChance W200123','SIP':'','NC':'CDWW','R':'','I':'','M':'','LT':0,'C':0,'VL':0.000,'BV':6099.000,'B':'0.007','S':'0.009','SV':7278.300,'O':0,'H':0,'L':0,'V':0.000,'SC':'5','PV':0.009,'P':0,'BL':'100','P_':'X','V_':''}] &gt;&gt;&gt; d=pd.DataFrame(new_list) &gt;&gt;&gt; d B BL BV C H I ID L LT M ... PV P_ R S SC SIP \ 0 0.007 100 6099.0 0 0 0 0 0 ... 0.009 X 0.009 5 SV V VL V_ 0 7278.3 0.0 0.0 [1 rows x 24 columns] &gt;&gt;&gt;
score: 0
answers question: http://stackoverflow.com/q/49186198
type: Answer

django-rest-auth
tag name: django-rest-auth
tags question: http://stackoverflow.com/q/49242405
tags question: http://stackoverflow.com/q/49233653
type: Tag
tags question: http://stackoverflow.com/q/49199253
tags question: http://stackoverflow.com/q/49278917

http://stackoverflow.com/q/49140589
accepted answer: http://stackoverflow.com/a/49140957
tagged with: python
has title: Filling Pandas columns with lists of unequal lengths
has comment: http://stackoverflow.com/comment/85286561
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/58541357
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49140957
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/58541357
downvote count: 0
has body: I am having trouble filling Pandas dataframes with values from lists of unequal lengths. nx_lists_into_df is a list of numpy arrays. I get the following error: ValueError: Length of values does not match length of index The code is below: # Column headers df_cols = ["f1","f2"] # Create one dataframe fror each sheet df1 = pd.DataFrame(columns=df_cols) df2 = pd.DataFrame(columns=df_cols) # Create list of dataframes to iterate through df_list = [df1, df2] # Lists to be put into the dataframes nx_lists_into_df = [[array([0, 1, 3, 4, 7]), array([2, 5, 6, 8])], [array([0, 1, 2, 6, 7]), array([3, 4, 5, 8])]] # Loop through each sheet (i.e. each round of k folds) for df, test_index_list in zip_longest(df_list, nx_lists_into_df): counter = -1 # Loop through each column in that sheet (i.e. each fold) for col in df_cols: print(col) counter += 1 # Add 1 to each index value to start indexing at 1 df[col] = test_index_list[counter] + 1 Thank you for your help. Edit: This is how the result should hopefully look:- print(df1) f1 f2 0 0 2 1 1 5 2 3 6 3 4 8 4 7 NaN print(df2) f1 f2 0 0 3 1 1 4 2 2 5 3 6 8 4 7 NaN
has answer: http://stackoverflow.com/a/49140715

http://stackoverflow.com/a/49251820
answers question: http://stackoverflow.com/q/49251379
has body: Your error contains this: Cannot run program "/home/my_name/PycharmProjects/untitled/venv/bin/python" which indicates, that nothing is wrong with your file, but, instead pycharm cannot locate the python interpreter. It is configured to use a venv one in a project folder "untitled" which, as you said, you deleted. You should choose another interpreter
has comment: http://stackoverflow.com/comment/85507684
has comment: http://stackoverflow.com/comment/85508107
has comment: http://stackoverflow.com/comment/85508230
has comment: http://stackoverflow.com/comment/85507305
has comment: http://stackoverflow.com/comment/85509515
has comment: http://stackoverflow.com/comment/85507217
has comment: http://stackoverflow.com/comment/85507957
has comment: http://stackoverflow.com/comment/85507863
type: Answer
has comment: http://stackoverflow.com/comment/85507885
has comment: http://stackoverflow.com/comment/85508489
has comment: http://stackoverflow.com/comment/85507789
has comment: http://stackoverflow.com/comment/85508975
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85509114
has comment: http://stackoverflow.com/comment/85508552
has comment: http://stackoverflow.com/comment/85508665
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49251379
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85507949

http://stackoverflow.com/q/49264518
favorite count: 0
has body: I'm trying to make a sorted bar graph with a dual y-axis. So far, I have the graph in place but I am trying to sort it from the most to the least enrollment. Here is the code for how I've sorted my data frame: #Merging the Two DFs viz_df = pd.merge(totenrl_df, gpaAvg_df, on = 'Institution') #Sorting Values based off Enrollment viz_df = viz_df.sort_values('Total Female Enrollment', ascending = False) #Reducing DF to exclude those who do not have enrollment numbers viz_df = viz_df[viz_df['Total Female Enrollment'] != 0] viz_df.head(10) This yields me: The problem I'm running into is getting Bokeh to understand this sorted graph. This is the code I have for generating my graph: #Creating Output File output_notebook() #Setting Dimensions p = figure(plot_width = 800, plot_height = 400) #Creating Point Renderer p.cross(viz_df.index,viz_df['Totals, Female: Cumulative GPA (Tot. F)'].values,line_width = 0.5, color = 'red', y_range_name = 'GPA') #Creating alterante range for GPA p.extra_y_ranges = {'GPA': Range1d(start = 0, end = 4.0)} p.add_layout(LinearAxis(y_range_name = 'GPA'), 'right') #Creating Bar Values h = viz_df['Total Female Enrollment'].values #Adding Bar Renderer p.vbar(x = viz_df.index, bottom = 0, top = h, width = .5) show(p) Which yields me: I don't know what I'm doing wrong, I think it should be working. Thank you for any help.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85534050
type: Question
downvote count: 0
upvote count: 1
tagged with: python
type: UnansweredQuestion
answer count: 1
has answer: http://stackoverflow.com/a/67492027
has comment: http://stackoverflow.com/comment/85535883
tagged with: visualization
tagged with: pandas
has title: Bokeh not reading sorted Pandas Dataframe correctly
tagged with: bokeh
score: 1

http://stackoverflow.com/a/49273409
upvote count: 0
has comment: http://stackoverflow.com/comment/85550337
type: Answer
has comment: http://stackoverflow.com/comment/85549933
score: -1
has body: You can create object for that class M=Myapp() M.build() will help in calling that function. Try this for your scenario class A(): def funct1(self): sample="hi" class B(): def func2(self): A.sample="hello" print A.sample a=A() a.funct1() b=B() b.func2() Output: hello
has comment: http://stackoverflow.com/comment/85550422
has comment: http://stackoverflow.com/comment/85550377
has comment: http://stackoverflow.com/comment/85551271
downvote count: 1
has comment: http://stackoverflow.com/comment/85550115
has comment: http://stackoverflow.com/comment/85551136
has comment: http://stackoverflow.com/comment/85550062
answers question: http://stackoverflow.com/q/49273317
has comment: http://stackoverflow.com/comment/85551031
has comment: http://stackoverflow.com/comment/85550710

http://stackoverflow.com/comment/85280348
has text: Usually KeyErrors are not inexplicable, they are a result of trying to access a key that does not exist. Have you tried to [Catch the error](https://docs.python.org/3/tutorial/errors.html#handling-exceptions) and inspect/print relevant data in the except suite?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49137560

http://stackoverflow.com/q/49150541
answer count: 2
score: 1
upvote count: 1
tagged with: migration
downvote count: 0
tagged with: django
has comment: http://stackoverflow.com/comment/85305659
has answer: http://stackoverflow.com/a/51822611
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49150666
type: UnansweredQuestion
has body: I need to auto fake a Django 1.9 migration. Is there a flag that can put in the migration file that will auto fake, rather than having to log onto multiple servers and run. The migrations layout is like this migtarions |-- 0001_initial.py |-- 0002.py |-- 0003.py I know I can do ./manage.py my_app migrate 0002 --fake, but can migration 0002 be auto faked ? and all I need to run is ./manage.py my_app migrate
has comment: http://stackoverflow.com/comment/111102018
has comment: http://stackoverflow.com/comment/85317446
tagged with: python
has comment: http://stackoverflow.com/comment/85305519
has title: Auto Fake Django Migration

http://stackoverflow.com/a/76558865
type: AcceptedAnswer
type: Answer
score: 0
has body: with open('testfile5.txt','w') as testfile5: text = "" for a in range(al): for i in range(5): text += str(al[(a*5)+i]) testfile5.write(text) testfile5.write("/n") testfile5.close()
accepted answer of: http://stackoverflow.com/q/49226391
answers question: http://stackoverflow.com/q/49226391

http://stackoverflow.com/q/49136472
accepted answer: http://stackoverflow.com/a/49138172
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/47034888
has answer: http://stackoverflow.com/a/49138172
tagged with: tensorflow
favorite count: 0
type: Question
has title: TensorFlow sequence_loss with label_smoothing
upvote count: 2
tagged with: sequence-to-sequence
tagged with: softmax
has body: Would it be possible to use the label_smoothing feature from tf.losses.softmax_cross_entropy with tf.contrib.seq2seq.sequence_loss ? I can see that sequence_loss optionally takes a softmax_loss_function as parameter. However, this function would take the targets as a list of ints, instead of one-hot encoded vectors required by tf.losses.softmax_cross_entropy, which is also the only function to support label_smoothing in TensorFlow. Can you recommend a way of making label_smoothing work with sequence_loss ?
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: cross-entropy

http://stackoverflow.com/a/49252092
has body: Why do you want to compile everything from source? Just download and run the Debian/Ubuntu installer for the SCIP Optimization Suite. Then run pip install pyscipopt. It's all explained here. And I strongly suggest to work within a virtual environment for Python and not to install Python modules using sudo. You might also want to check out Anaconda for organizing your Python environment.
downvote count: 0
answers question: http://stackoverflow.com/q/49246912
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/comment/85317047
type: QuestionComment
comment on: http://stackoverflow.com/q/49140454
has text: @JerinPeterGeorge `class Bookmark(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) resource = models.ForeignKey("Resource", on_delete=models.CASCADE, related_name="bookmarks") # meta created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ('user', 'resource',) ordering = ('resource',) def __str__(self): return "{} | {}".format(self.user, self.resource) `
type: Comment
score: 0

http://stackoverflow.com/a/49143114
score: 1
upvote count: 1
type: AcceptedAnswer
has body: In SQL, the INNER JOIN without equality is equivalent to CROSS JOIN and ON can be replaced with WHERE. Technically, even with equality! So your need of: INNER JOIN number_table as n ON n.N &lt;= t.some_integer_field Can be replaced as: CROSS JOIN number_table as n WHERE n.N &lt;= t.some_integer_field And because cross joins are cartesian products, run the same process in pandas where you assign a column in both dataframes of same value and merge on it which returns all possible combinations of rows from both sets since key will align. df_number['key'] = 1 # OR df_number.assign(key=1) df_table['key'] = 1 # CROSS JOIN WITH CONDITIONAL FILTER pd.merge(df_table, df_number, on='key').query('N &lt; some_integer_field') Now performance of CJs is another question!
type: Answer
answers question: http://stackoverflow.com/q/49142836
has comment: http://stackoverflow.com/comment/85322907
has comment: http://stackoverflow.com/comment/85322453
accepted answer of: http://stackoverflow.com/q/49142836
downvote count: 0

http://stackoverflow.com/comment/85437242
has text: I want in memory database, why shall I consider redis?
comment on: http://stackoverflow.com/q/49216483
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85498384
has text: `(x + y == 16) and ((10*x) + (25*y) == 250)`?
comment on: http://stackoverflow.com/q/49247325
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85412742
comment on: http://stackoverflow.com/a/49200317
type: AnswerComment
score: 0
type: Comment
has text: it Worked!! I have no idea what this code does, I will have to go read about it to fully understand it. I appreciate all your help.

http://stackoverflow.com/q/49270560
answer count: 3
upvote count: 2
has comment: http://stackoverflow.com/comment/85559150
downvote count: 0
linked to: http://stackoverflow.com/q/29638136
has body: The data I want to insert into the database likes this: datalist =[['2012', '1', '3', '1', '832.0', '261.0', '100.00'], ['2012', '1', '5', '1', '507.0', '193.0', '92.50'], ['2012', '2', '3', '1', '412.0', '200.0', '95.00'], ['2012', '2', '5', '1', '560.0', '335.0', '90.00'], ['2012', '3', '3', '1', '584.0', '205.0', '100.00'], ['2012', '3', '5', '1', '595.0', '162.0', '92.50'], ['2012', '4', '3', '1', '504.0', '227.0', '100.00'], ['2012', '4', '5', '1', '591.0', '264.0', '92.50']] But in fact, there are 500,000 rows in datalist. So I just listed a part of it. The code I insert into the database likes this： import pymssql server = '127.0.0.1' user = "test" password = "test" database='SQLTest' datalist = [['2012', '1', '3', '1', '832.0', '261.0', '100.00'], ['2012', '1', '5', '1', '507.0', '193.0', '92.50'], ['2012', '2', '3', '1', '412.0', '200.0', '95.00'], ['2012', '2', '5', '1', '560.0', '335.0', '90.00'], ['2012', '3', '3', '1', '584.0', '205.0', '100.00'], ['2012', '3', '5', '1', '595.0', '162.0', '92.50'], ['2012', '4', '3', '1', '504.0', '227.0', '100.00'], ['2012', '4', '5', '1', '591.0', '264.0', '92.50']] #But in fact, there are 500,000 rows in datalist try: conn = pymssql.connect(server, user, password, database) cursor = conn.cursor() for one_row in datalist: val1 = one_row[4] val2 = one_row[5] val3 = one_row[6] sql = "insert into table_for_test values(col1, col2, col3)" % (val1, val2,val3) cursor.execute(sql) conn.commit() except Exception as ex: conn.rollback() raise ex finally: conn.close() Because of the amount of data is too large,So I want to insert data in batchs,how to modify the code?
favorite count: 0
type: Question
type: AnsweredQuestion
has title: How to use python to commit data in batches to SQLServer database?
tagged with: python
accepted answer: http://stackoverflow.com/a/59655554
possible better answer: http://stackoverflow.com/a/49271261
tagged with: pymssql
has answer: http://stackoverflow.com/a/75890464
has comment: http://stackoverflow.com/comment/85545441
has answer: http://stackoverflow.com/a/59655554
score: 2
has answer: http://stackoverflow.com/a/49271261

http://stackoverflow.com/q/49151531
accepted answer: http://stackoverflow.com/a/49837376
has comment: http://stackoverflow.com/comment/85307505
has title: How to Display Python Argparse Command Line for Users
has body: Python can be daunting for non-programmers. Should argparse make it clear to to users that python needs to be typed before the rest of the usage line? If so what is the convention? The Argparse Tutorial example: https://docs.python.org/2/howto/argparse.html prog.py import argparse parser = argparse.ArgumentParser() parser.parse_args() Output $ python prog.py --help usage: prog.py [-h] optional arguments: -h, --help show this help message and exit
tagged with: python
has comment: http://stackoverflow.com/comment/85309162
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49837376
has comment: http://stackoverflow.com/comment/85321570
tagged with: argparse
has comment: http://stackoverflow.com/comment/85327672
answer count: 1
has comment: http://stackoverflow.com/comment/85308271
type: Question

http://stackoverflow.com/comment/85349279
comment on: http://stackoverflow.com/a/49172083
type: AnswerComment
has text: Got it now. Thanks for the explanation @user32185
type: Comment
score: 0

http://stackoverflow.com/comment/85316310
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/166410/discussion-between-growler-and-jezrael).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49144541
score: 0

http://stackoverflow.com/comment/116107178
type: Comment
type: QuestionComment
has text: I think it is good to find the simple answer here on stackoverflow. The two questions are not the same...
comment on: http://stackoverflow.com/q/49182755
score: 0

http://stackoverflow.com/comment/85249187
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49121807
type: AnswerComment
has text: "List comprehensions do not work in place." That is what I needed to know.

http://stackoverflow.com/q/49136816
tagged with: python
has answer: http://stackoverflow.com/a/49139198
type: AnsweredQuestion
score: 0
tagged with: tkinter
answer count: 1
accepted answer: http://stackoverflow.com/a/49139198
type: Question
has body: I have two queries in this section. In my code i have created two frames under root, the first frame have "NEXT" button to go on second frame. In second frame there is Run button, which has mapped with close_window function. It should close all windows properly. But in my case not closing it. When i click "Run" i need to close all windows and need to execute another script on the same directory. Is that possible to do it ? &nbsp; from Tkinter import * def close_window(): frame2.destroy() frame1.destroy() def swap_frame(frame): frame.tkraise() root = Tk() root.geometry("900x650+220+20") root.title("Testing") root.configure(borderwidth="1", relief="sunken", cursor="arrow", background="#dbd8d7", highlightcolor="black") root.resizable(width=False, height=False) frame2 = Frame(root, width=900, height=650) frame1 = Frame(root, width=900, height=650) Button1 = Button(frame1, text="Next", width=10, height=2, bg="#dbd8d7", command=lambda: swap_frame(frame2)) Button1.place(x=580, y=580) Button2 = Button(frame2, text="Run", width=10, height=2, bg="#dbd8d7", command=close_window,) Button2.place(x=580, y=580) frame2.grid(row=0, column=0) frame1.grid(row=0, column=0) root.mainloop() what is wrong in the code?
has comment: http://stackoverflow.com/comment/85291781
has title: Destroy window not closing all windows properly
has comment: http://stackoverflow.com/comment/85279676

http://stackoverflow.com/q/49140526
has comment: http://stackoverflow.com/comment/85313762
type: Question
has answer: http://stackoverflow.com/a/49157020
has title: PyQt5 - how to bring the Qfiledialog to the front?
has body: My code uses PyQt to open up a folder select dialog. Once a folder is selected it is minimized. I'd like for the dialog to pop up in front of any other windows. I haven't been able to find a solution yet. Any suggestions? from sys import executable, argv from subprocess import check_output from PyQt5.QtWidgets import QFileDialog, QApplication def gui_fname(directory=''): file = check_output([executable, __file__, directory]) return file.strip() if __name__ == "__main__": directory = argv[1] app = QApplication([directory]) folderpath = QFileDialog.getExistingDirectory(None, "Select folder")
tagged with: qfiledialog
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85309584
tagged with: pyqt5
tagged with: python
favorite count: 0
score: 2
type: AnsweredQuestion
answer count: 1
accepted answer: http://stackoverflow.com/a/49157020

http://stackoverflow.com/a/49222917
score: 1
type: Answer
has body: You could give your Bullet class a self.live attribute and set it to True or False depending on the random number during the instantiation. Then iterate over the collided sprites and only call enemy.kill() if the bullet's live attribute is True. import random import pygame as pg pg.init() BG_COLOR = pg.Color('gray12') ENEMY_IMG = pg.Surface((50, 30)) ENEMY_IMG.fill(pg.Color('darkorange1')) BULLET_IMG = pg.Surface((9, 15)) BULLET_IMG.fill(pg.Color('aquamarine2')) class Enemy(pg.sprite.Sprite): def __init__(self, pos): super().__init__() self.image = ENEMY_IMG self.rect = self.image.get_rect(center=pos) class Bullet(pg.sprite.Sprite): def __init__(self, pos): super().__init__() self.image = BULLET_IMG self.rect = self.image.get_rect(center=pos) self.pos = pg.math.Vector2(pos) self.vel = pg.math.Vector2(0, -450) # If `live` is True, the bullet is able to destroy an enemy. self.live = True if random.randrange(100) &lt; 70 else False def update(self, dt): # Add the velocity to the position vector to move the sprite. self.pos += self.vel * dt self.rect.center = self.pos # Update the rect pos. if self.rect.bottom &lt;= 0: # Outside of the screen. self.kill() class Game: def __init__(self): self.clock = pg.time.Clock() self.screen = pg.display.set_mode((800, 600)) self.all_sprites = pg.sprite.Group() self.enemies = pg.sprite.Group() self.bullets = pg.sprite.Group() for i in range(15): pos = (random.randrange(30, 750), random.randrange(500)) enemy = Enemy(pos) self.enemies.add(enemy) self.all_sprites.add(enemy) self.bullet_timer = .1 self.done = False def run(self): while not self.done: # dt = time since last tick in milliseconds. dt = self.clock.tick(60) / 1000 self.handle_events() self.run_logic(dt) self.draw() def handle_events(self): for event in pg.event.get(): if event.type == pg.QUIT: self.done = True elif event.type == pg.MOUSEBUTTONDOWN: bullet = Bullet(pg.mouse.get_pos()) self.bullets.add(bullet) self.all_sprites.add(bullet) pg.display.set_caption('This bullet is l…
answers question: http://stackoverflow.com/q/49211084
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49211084
upvote count: 1
has comment: http://stackoverflow.com/comment/85488948

http://stackoverflow.com/comment/85333265
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49162639
score: 0
has text: The "$$$$" wont populate any idea on what I'm missing?

http://stackoverflow.com/comment/85408015
type: QuestionComment
comment on: http://stackoverflow.com/q/49201431
has text: Can you include the code that you are using to combine the matrices? Also how are you trying to combine these matrices? Is this concatenation in 2nd dimension or is it combining them to form a 4D matrix?
score: 0
type: Comment

http://stackoverflow.com/q/49276368
tagged with: google-chrome
accepted answer: http://stackoverflow.com/a/49277804
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49277804
has body: We have a Selenium process that fetches data from our data provider for further processing. The process tries to get all historical data, and since we do not have functionality to reliably filter out data that has been edited recently, we must get full data dumps from time to time to ensure that no records are dropped. The Selenium process is written as a Python script. It goes to a specific website, logs in, presses a button that triggers report generation, and then downloads the report. The issue is that for full dump reports, the report generation has started to take longer than the default Selenium timeouts. We use the Google Chrome driver, but would be willing to change the browser/driver if only other drivers have the ability to fully disable timeouts. Below is a simplified, stripped-down version of the code with just the bare bones needed to appropriately describe this issue. The places where the report times out are marked out. It's waiting for a response from the website after clicking a button. How to disable that, and why what we currently do (can be seen below) is not enough? from selenium import webdriver def selectPopUp(driver, main_window_handle, maxWait=100): """ Selects a pop-up window. If no pop-up window appears, raises an Exception. :param maxWait: how long to wait (in seconds) before raising the error? """ popup_window_handle = None i = 0 while (not popup_window_handle) and (i &lt; maxWait): for handle in driver.window_handles: if handle != main_window_handle: popup_window_handle = handle break # Wait a litle and re-iterate. time.sleep(1) i += 1 if popup_window_handle != None: driver.switch_to.window(popup_window_handle) return popup_window_handle else: raise Exception("No pop-up window appeared although the program was expecting one.") def selectOption(dropdown, option, possibilities): """ Validates and selects an option from a drop-down. :param dropdown: the Selenium reference to the dropdown selection. :param option: the name of the option we…
has comment: http://stackoverflow.com/comment/85561363
answer count: 1
linked to: http://stackoverflow.com/q/46939451
has title: Selenium [Python Binding, Chrome Driver]: Disable Timeouts Completely
has comment: http://stackoverflow.com/comment/85563759
type: Question
tagged with: selenium
tagged with: python

http://stackoverflow.com/comment/85485650
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49240693
has text: I implemented both of the functions that you shared (thanks), and achieved this result: `<2380x144824 sparse matrix of type '<class 'numpy.float64'>' with 11728974 stored elements in Compressed Sparse Row format>` - However, I'm wondering if I've just nullified the data being used as it's no longer related to the Year data?
type: Comment

http://stackoverflow.com/q/49136783
downvote count: 0
has body: Let's explain the context: Someone gives me multiple parquet files obtain from multiple .csv files. I want to read all this parquet files and make a big dataset. For this I use pyarrow.parquet package. So, I have multiple parquet file (We could call them file1.pq ; file2.pq ; file3.pq). All the files have exactly the same structure: the same column name and the same content of column. But sometimes in all the rows of a column in one file the value is the same and egal to NA. In this particular case the function dataset = pq.ParquetDataset(file_list) fail because physical type change. lets make a visual exemple: | File1.csv | |-------------|-----|----| | Column Name | C1 | C2 | |-------------|-----|----| | Row 1 | YES | 10 | | Row 2 | NA | 15 | | Row 3 | NO | 9 | | File2.csv | |-------------|-----|----| | Column Name | C1 | C2 | |-------------|-----|----| | Row 1 | NA | 10 | | Row 2 | NA | 15 | | Row 3 | NA | 9 | | File2.csv | |-------------|-----|----| | Column Name | C1 | C2 | |-------------|-----|----| | Row 1 | YES | 10 | | Row 2 | NA | 15 | | Row 3 | NO | 9 | After conversion to parquet we have: pq.ParquetFile("File1.pq").schema[1].physical_type = 'BYTE_ARRAY' --&gt; good ! pq.ParquetFile("File1.pq").schema[2].physical_type = 'DOUBLE' --&gt; good ! pq.ParquetFile("File2.pq").schema[1].physical_type = 'DOUBLE' --&gt; BAD ! pq.ParquetFile("File2.pq").schema[2].physical_type = 'DOUBLE' --&gt; good ! pq.ParquetFile("File3.pq").schema[1].physical_type = 'BYRE_ARRAY' --&gt; good! pq.ParquetFile("File3.pq").schema[2].physical_type = 'DOUBLE' --&gt; good ! I try to open each parquet file and modify column type with something like that : for i in np.arange(0,len(file_list)): if list_have_to_change[i] != []: df = pd.read_parquet(file_list[i]) df[list_have_to_change[i]] = df[list_have_to_change[i]].astype(bytearray) df.to_parquet(COPIEPATH + "\\" + ntpath.basename(file_list[i])) else : shutil.move(file_list[i],COPIEPATH + "\\" + ntpath.basename(file_list[i])) Where: file_l…
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85281701
has title: Trouble with schema using pyarrow.parquet ParquetDataset (how to force a particular schema)
score: 3
type: UnansweredQuestion
tagged with: python
upvote count: 3
tagged with: parquet
answer count: 0
tagged with: pyarrow
has comment: http://stackoverflow.com/comment/85284471
has comment: http://stackoverflow.com/comment/85280378

http://stackoverflow.com/comment/85425565
type: QuestionComment
comment on: http://stackoverflow.com/q/49201956
score: 0
has text: I managed to get the result I was looking for. I think my problem was the multipolygon character of the data. Here's the link to get the files:http://www.gadm.org/country choose Spain and shapefile. I unzipped and got the adm0 since all I need are country boundaries. I'll try posting an answer to my own quesiton. Thank you anyway!!!
type: Comment

http://stackoverflow.com/a/49247939
answers question: http://stackoverflow.com/q/49247636
downvote count: 0
upvote count: 7
has body: You can use str.partition that guarantee three tuple output in the format: (part before separator, separator itself, part after separator) &gt;&gt;&gt; "a".partition(" ") &gt;&gt;&gt; ('a', '', '') &gt;&gt;&gt; "a b".partition(" ") &gt;&gt;&gt; ('a', ' ', 'b') &gt;&gt;&gt; "a b c".partition(" ") &gt;&gt;&gt; ('a', ' ', 'b c')
score: 7
type: Answer
has comment: http://stackoverflow.com/comment/85499415

ansible
tags question: http://stackoverflow.com/q/49151299
tags question: http://stackoverflow.com/q/49153403
type: Tag
tag name: ansible

http://stackoverflow.com/comment/85409804
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49201812
has text: Sorry, not sure if I'm following you @Longroadahead just based on your code. It would help if you could add some example input/output data that represents where you're trying to get to.
type: Comment

http://stackoverflow.com/comment/85285148
type: Comment
type: AnswerComment
has text: Ive put that at the end of my script however it still finishes after self.four()
comment on: http://stackoverflow.com/a/49139836
score: 0

http://stackoverflow.com/comment/85374989
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49168223
score: 0
has text: @MrT I didn't fully understand the system. Thanks for letting me know.

http://stackoverflow.com/a/49263047
score: 0
answers question: http://stackoverflow.com/q/49250071
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49250071
has comment: http://stackoverflow.com/comment/85576243
has body: It seems you need to loop over every element and look at the sectionCategory for each: element.sectionCategory.name 'solid &lt; materialname >' so you build a full list something like: steelels = [ el.label for el in instance.elements if el.sectionCategory.name == 'solid &lt; steel &gt;'] Really the preferred approach here is to create the appropriate element sets as you build the model.
has comment: http://stackoverflow.com/comment/85545273
has comment: http://stackoverflow.com/comment/85730949
type: Answer

http://stackoverflow.com/q/49200983
type: Question
has comment: http://stackoverflow.com/comment/85532703
has comment: http://stackoverflow.com/comment/85407601
has title: Reading json twitter streams with python
score: 1
has comment: http://stackoverflow.com/comment/85432861
has answer: http://stackoverflow.com/a/49264934
tagged with: http://stackoverflow.com/tag/json
tagged with: python
tagged with: tweepy
has comment: http://stackoverflow.com/comment/85407122
has body: I am pretty new at working with python and coding in general so I feel as though this answer is something that I do not understand about how python works. I have been working with using Tweepy to collect streams of data from python to measure sentiment with different things. That part worked fine. When I ran the program, I had the data write to a txt file and then was trying to use the data within that file to see things such as common words or locations. But I am running into problems when I am reading the data. I have been searching online and found a number of different ways that people have read the data but as I am unfamiliar with json files in general, I don't understand why these methods would work or not. The main error I seem to be running into is something similar to this: JSONDecodeError: Expecting value: line 1 column 1 (char 0). From my understanding, this means that the data is not reading in correctly as can't be read as a json file. But I have also experienced the error where it reads like this: JSONDecodeError: Expecting value: line 4 column 1 (char 0). I don't understand why it would change or not. I have tried reading the file in as the original txt file and then saving it again as a json file. The first error I received when trying it as a json file with the second coming from the txt file. I have read a number of different threads discussing similar problems but they keep giving me these types of errors. Just as an example, here is what my code looked like for the most recent error: import json source = open("../twitterdata24.json") json_data = json.load(source) One of my other attempts: import json tweets = [] for line in open("fileinfo"): tweets.append(json.load(line)) One other point of interest, the data I am working with contains many individual tweets and from what I have read, I think there is a problem with each individual tweet being a new dictionary, so I tried to make the whole data file a list using [] but that just moved the error d…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49264934
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85407477
upvote count: 1
favorite count: 0

http://stackoverflow.com/a/49257078
answers question: http://stackoverflow.com/q/49213003
score: 0
type: AcceptedAnswer
has body: It appears they added some features to excel https://msdn.microsoft.com/library/1ed840b1-7e20-4419-ad2f-d82054c9b2ab They have power queries that you can use to build a data parser similar to the Regex framework. It's pretty easy and there is a good level of detail on the documentation on how to use it. When you import the text file hit advanced and it will bring you to the query editor.
accepted answer of: http://stackoverflow.com/q/49213003
type: Answer

http://stackoverflow.com/comment/85554185
type: Comment
type: AnswerComment
has text: Is it possible that your `x` and `y` axes cover a huge range, like millions, where a 100 movement would be small?
comment on: http://stackoverflow.com/a/49275688
score: 1

http://stackoverflow.com/comment/134628099
comment on: http://stackoverflow.com/a/49169747
score: 0
type: AnswerComment
has text: This works for me: `vips text x.png Puzzling --dpi 300 --fontfile LoversQuarrel-Regular.ttf --font LoversQuarrel` and gets the bounding box right. Did you select the font as well as specifying the fontfile?
type: Comment

http://stackoverflow.com/q/49135021
tagged with: python
type: UnansweredQuestion
score: -2
tagged with: pandas
tagged with: powerbi
upvote count: 0
has answer: http://stackoverflow.com/a/49135154
tagged with: http://stackoverflow.com/tag/json
has title: How to convert complicated JSON file structure to CSV in Python?
answer count: 3
favorite count: 0
has answer: http://stackoverflow.com/a/49139503
has body: This is what the JSON structure looks likes. I have taken out personal information from the data. { "Version": "1.0", "IsUpToDate": false, "LastModificationGUID": "{numbers}", "DisplayName": "DATE", "CreateDate": "DATE AND TIME", "ServerID": 0, "CreatorServerID": 0, "TournamentID": "NUMBERS", "PitchMoundDistance": NUMBER, "SensorModel": 20, "Results": [ { "Guid": "{NUMBERS}", "PitchServerID": 0, "HitServerID": 0, "PitchResult": { "LaunchSpeed": LONG FLOATING NUMBER, "LaunchAzimDeg": LONG FLOATING NUMBER, "LaunchElevDeg": LONG FLOATING NUMBER, "BackspinRPM": -NUMBER, "SidespinRPM": -NUMBER, "RiflespinRPM": -NUMBER, "X": [ -LONG FLOATING NUMBER, LONG FLOATING NUMBER, -LONG FLOATING NUMBER, LONG FLOATING NUMBER, -LONG FLOATING NUMBER ], "Y": [ LONG FLOATING NUMBER, -LONG FLOATING NUMBER, LONG FLOATING NUMBER, -LONG FLOATING NUMBER, -LONG FLOATING NUMBER ], "Z": [ LONG FLOATING NUMBER, LONG FLOATING NUMBER, -LONG FLOATING NUMBER, -LONG FLOATING NUMBER, LONG FLOATING NUMBER ], "FlightTime": LONG FLOATING NUMBER, "TrackTime": LONG FLOATING NUMBER, "StartPositionX": -LONG FLOATING NUMBER, "StartPositionY": LONG FLOATING NUMBER, "StartPositionZ": LONG FLOATING NUMBER, "StrikeZoneFrontPositionX": LONG FLOATING NUMBER, "StrikeZoneFrontPositionY": LONG FLOATING NUMBER, "StrikeZoneFrontPositionZ": LONG FLOATING NUMBER, "StrikeZoneFrontTime": LONG FLOATING NUMBER, "StrikeZoneBackPositionX": LONG FLOATING NUMBER, "StrikeZoneBackPositionY": LONG FLOATING NUMBER, "StrikeZoneBackPositionZ": LONG FLOATING NUMBER, "StrikeZoneBackTime": LONG FLOATING NUMBER, "BreakDistance": LONG FLOATING NUMBER, "MovementDistance": LONG FLOATING NUMBER, "Extension": LONG FLOATING NUMBER, "MLBSpinAxisDeg": LONG FLOATING NUMBER, "MLBSpinTiltHoursOnly": 12, "MLBSpinTiltHours": 12, "MLBSpinTiltMinutes": 15, "MLBHBreak": LONG FLOATING NUMBER, "MLBVBreak": -LONG FLOATING NUMBER, "MLBVBreakInduced": LONG FLOATING NUMBER, "MLBHMovement": -LONG FLOATING NUMBER, "MLBVMovement": LONG FLOATING NUMBER, "SimpleHBre…
has answer: http://stackoverflow.com/a/49135682
type: Question
downvote count: 2

http://stackoverflow.com/a/49166437
type: Answer
has body: I guess you could splat your kwargs and use dict.setdefault class Foo(): def __init__(self, **kwargs): kwargs.setdefault('kwarg1', 'a') kwargs.setdefault('kwarg2', kwargs['kwarg1']) kwargs.setdefault('kwarg3', kwargs['kwarg1']) self.__dict__.update(kwargs)
score: 0
answers question: http://stackoverflow.com/q/49166292

http://stackoverflow.com/q/49239647
tagged with: audio
score: 0
answer count: 0
tagged with: spectrogram
has comment: http://stackoverflow.com/comment/85483445
type: Question
linked to: http://stackoverflow.com/q/17494185
linked to: http://stackoverflow.com/q/34156050
type: UnansweredQuestion
has title: How to plot a Spectrogram with very small values?
tagged with: matplotlib
has body: I am using librosa to read a sound file and matplotlib.pyplot.specgram to plot its spectrogram and return its frequency and time bins in spectrum. Code: import librosa import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import specgram filepath = r"1301524547165114.wav" f, sr = librosa.load(filepath) spectrum, freqs, t, im = specgram(np.array(f), Fs=sr, noverlap=2**7, NFFT=2**8) print(spectrum.shape) plt.suptitle("Figure 1: Spectrogram") plt.colorbar() plt.show() Output: (129, 347) Here spectrogram looks good, but when I plot it using spectrum, most of the graph is dark because most of the values in spectrum are very small. Code: def print_image(image, title): plt.imshow(image, origin="lower") plt.title(title) plt.colorbar() plt.show() print_image(spectrum, "Figure 2: Spectrogram") Output: Here's the audio file I used: https://drive.google.com/open?id=1WMvOqsSNllgX5R_hUzhHm0gYopYnbZGZ Why matplotlib.pyplot.specgram is able to plot it properly? How can I plot it using data (spectrum) I received from matplotlib.pyplot.specgram.
has comment: http://stackoverflow.com/comment/85484064
tagged with: python
duplicate of: http://stackoverflow.com/q/34156050
has comment: http://stackoverflow.com/comment/85484220

http://stackoverflow.com/comment/85351630
comment on: http://stackoverflow.com/q/49171994
score: 0
has text: @MehdiSadeghi will try this now
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49158825
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85326788
downvote count: 0
upvote count: 1
score: 1
has answer: http://stackoverflow.com/a/49160801
accepted answer: http://stackoverflow.com/a/49160801
answer count: 1
linked to: http://stackoverflow.com/q/7546050
favorite count: 0
type: Question
has body: I have created my own python script following the suggestion of this post, Switch between two frames in tkinter. I have also followed this post, How to access variables from different classes in tkinter python 3. However, I want to set or change the value of the shared value in one frame and then access it in another, when I switch between the frames. class MainApplication(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.app = { "foo": None } self.frames = {} for F in (PageOne, PageTwo): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame("PageOne") def show_frame(self, page_name, **kwargs): # self.app["foo"] = kwargs.get("bar") frame = self.frames[page_name] frame.tkraise() class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller button = tk.Button(self, text="Login", command=lambda: self.func()) button.pack() def func(self): # self.controller.show_frame("PageTwo", bar="something") self.controller.show_frame("PageTwo") class PageTwo(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller print(self.controller.app["foo"]) I tried adding arguments to the show_frame() function that allows for switching between frames but the result in PageTwo is still None. I have commented out the lines, to show what I attempted.
tagged with: python
linked to: http://stackoverflow.com/q/33646605
has title: Tkinter - Set Shared Variable and Access in Different Class
type: AnsweredQuestion
tagged with: python-3.x
linked to: http://stackoverflow.com/q/35029188

http://stackoverflow.com/q/49162854
type: Question
tagged with: apache-spark
score: 1
tagged with: pyspark
tagged with: python
accepted answer: http://stackoverflow.com/a/49166009
type: AnsweredQuestion
has title: Pyspark - TypeError: 'float' object is not subscriptable when calculating mean using reduceByKey
downvote count: 0
upvote count: 1
has body: my "asdasd.csv" file has the following structure. Index,Arrival_Time,Creation_Time,x,y,z,User,Model,Device,gt 0,1424696633908,1424696631913248572,-5.958191,0.6880646,8.135345,a,nexus4,nexus4_1,stand 1,1424696633909,1424696631918283972,-5.95224,0.6702118,8.136536,a,nexus4,nexus4_1,stand 2,1424696633918,1424696631923288855,-5.9950867,0.6535491999999999,8.204376,a,nexus4,nexus4_1,stand 3,1424696633919,1424696631928385290,-5.9427185,0.6761626999999999,8.128204,a,nexus4,nexus4_1,stand Ok, I get the following {key,value} tuple to operate with it. # x y z [(('a', 'nexus4', 'stand'), ((-5.958191, 0.6880646, 8.135345)))] # part A (key) part B (value) My code for calculating the mean is the following, I have to calculate the mean from each column, X, Y Z for each Key. rdd_ori = sc.textFile("asdasd.csv") \ .map(lambda x: ((x.split(",")[6], x.split(",")[7], x.split(",")[9]),(float(x.split(",")[3]),float(x.split(",")[4]),float(x.split(",")[5])))) meanRDD = rdd_ori.mapValues(lambda x: (x,1)) \ .reduceByKey(lambda a, b: (a[0][0] + b[0][0], a[0][1] + b[0][1], a[0][2] + b[0][2], a[1] + b[1]))\ .mapValues(lambda a : (a[0]/a[3], a[1]/a[3],a[2]/a[3])) My problem I that I tried that code and it works fine on other PC with the same MV I'm using for developing it (PySpark Py3) Here is an example, that this code is correct: But I don't know why I'm getting this error, important part is in Strong. --------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) in () 9 #sum_1 = count_.reduceByKey(lambda x, y: (x[0][0]+y[0][0],x0+y0,x[0][2]+y[0][2])) 10 ---> 11 print(meanRDD.take(1)) /opt/spark/current/python/pyspark/rdd.py in take(self, num) 1341 1342 p = range(partsScanned, min(partsScanned + numPartsToTry, totalParts)) -> 1343 res = self.context.runJob(self, takeUpToNumLeft, p) 1344 1345 items += res /opt/spark/current/python/pyspark/context.py in runJob(self, rdd, partitionFunc, partitions, allowLocal) 990 # SparkContext#runJob. …
has comment: http://stackoverflow.com/comment/85399522
answer count: 1
has comment: http://stackoverflow.com/comment/125312261
has answer: http://stackoverflow.com/a/49166009
favorite count: 0

http://stackoverflow.com/comment/85446920
comment on: http://stackoverflow.com/a/49212830
has text: thanks a lot, that's very helpful! Last question for clarification then: If I would want different cells, I would just use different scopes right?
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85501420
score: 0
has text: Finally, can you give us the actual exception (with traceback), not just a vague description of it?
type: QuestionComment
comment on: http://stackoverflow.com/q/49248432
type: Comment

http://stackoverflow.com/a/49135375
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49134831
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49134831
type: Answer
score: 13
upvote count: 13
has body: I have to answer my question because now I know the solution: The way I described in the start post should work. The docs are just wrong: https://code.djangoproject.com/ticket/29192
has comment: http://stackoverflow.com/comment/85276051

http://stackoverflow.com/a/49236263
answers question: http://stackoverflow.com/q/49235486
upvote count: 2
downvote count: 0
has body: Put all your common configurations in the commonsettings.py file. add following the line into the __init__.py file in the settings directory from commonsettings import * This makes every configuration in the commonsettings file available in all other files in the settings folder start your server with python3 manage.py runserver --settings=djangorest.settings.dev
score: 2
type: Answer

http://stackoverflow.com/comment/85486181
type: Comment
score: 0
type: AnswerComment
has text: I have done a video explaining what its try to do and the error i get: https://youtu.be/8sDwmKjP0LM
comment on: http://stackoverflow.com/a/49240977

http://stackoverflow.com/a/49269718
has body: lapTimes = [] count = 0 while True: count += 1 lap = input("Enter lap time " + str(count) + ": ") if lap == 'x': break else: lap = float(lap) print(type(lap)) lapTimes.append(lap) print(type(lapTimes[-1])) print("Fastest Lap time was: ", min(lapTimes)) print("Slowest lap time was: ", max(lapTimes)) You missed assignment of lap after converting to float. That's why saw error.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49269684

marker
tag name: marker
tags question: http://stackoverflow.com/q/49278649
type: Tag

http://stackoverflow.com/q/49245479
has title: How to display a list across multiple pages in Flask?
upvote count: 1
tagged with: flask
tagged with: jinja2
favorite count: 0
accepted answer: http://stackoverflow.com/a/49245648
possible better answer: http://stackoverflow.com/a/49245654
type: Question
has answer: http://stackoverflow.com/a/49245648
has answer: http://stackoverflow.com/a/49245654
has answer: http://stackoverflow.com/a/49245660
tagged with: http://stackoverflow.com/tag/html
has answer: http://stackoverflow.com/a/57770670
tagged with: python
score: 1
has body: In Flask, I am trying to display a dynamic list of items across multiple pages. The size of the list can possibly reach over 1000. In app.py I have a route such as: @app.route('/displayitems') def displayitems(): item_list = ['item1', 'item2', 'item3'] # Up to 1000 items return render_template('displayitems.html', item_list=item_list) Then in displayitems.html i have: {% for item in itemList%} &lt;li class="list-group-item"&gt; &lt;div class="item_number"&gt;{{ loop.index }}&lt;/div&gt; &lt;div class="item_name"&gt;{{ item }}&lt;/div&gt; &lt;/li&gt; {% endfor %} Which lists all items on the same page. However, I would like to somehow have, say, the first 20 items on one page, then be able to click a "next" button to view the next 20 items on another page, and so on for all of the items in the list. Does anyone know the best way to go about doing this?
answer count: 4
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/49240685
downvote count: 0
has comment: http://stackoverflow.com/comment/85485123
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49240781
accepted answer: http://stackoverflow.com/a/49240950
tagged with: python
has answer: http://stackoverflow.com/a/49240759
has body: I have an URL of the form: http://www.foo.com/bar?arg1=x&amp;arg2=y If I do: request.url I get: http://www.foo.com/bar?arg1=x&amp;arg2=y Is it possible to get just http://www.foo.com/bar?
tagged with: bottle
possible better answer: http://stackoverflow.com/a/49240759
score: 4
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85484987
answer count: 3
has answer: http://stackoverflow.com/a/49240950
has title: Bottle - Is it possible to retrieve URL without parameters?

py2exe
tags question: http://stackoverflow.com/q/49258897
type: Tag
tag name: py2exe
tags question: http://stackoverflow.com/q/49159990
tags question: http://stackoverflow.com/q/49233110

http://stackoverflow.com/q/49133004
tagged with: dataframe
tagged with: python
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/52553052
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/72581106
type: UnansweredQuestion
has title: AWS Glue Limit Input Size
favorite count: 0
type: Question
has body: I would like to test my AWS Glue PySpark job with a small subset of the data available. How can this be achieved? My first try was to convert the Glue dynamic frame to a spark data frame, and use the take(n) method to limit the number of rows to be processed as follows: datasource0 = glueContext.create_dynamic_frame.from_catalog( database = "my_db", table_name = "my_table", transformation_ctx = "ds0") applymapping1 = ApplyMapping.apply( frame = datasource0, mappings = [("foo", "string", "bar", "string")], transformation_ctx = "am1") truncated_df = applymapping1.toDF().take(1000) datasink2 = glueContext.write_dynamic_frame.from_options( frame = DynamicFrame.fromDF(truncated_df, glueContext, "tdf"), connection_type = "s3", ... ) job.commit() This fails with the following error message: AttributeError: 'list' object has no attribute '_jdf' Any ideas?
tagged with: apache-spark
tagged with: aws-glue

http://stackoverflow.com/q/49267271
has comment: http://stackoverflow.com/comment/85540732
answer count: 1
has body: I have copyed my django app (that works locally) to a droplet from Digitalocean where I have installed the django 1-click app. I get 502 Bad Gateway and can't manage to understand why. 2018/03/13 22:25:06 [error] 2104#2104: *44 upstream prematurely closed connection while reading response header from upstream, client: 139.162.251.201, server: _, request: "GET / HTTP/1.0", upstream: "http://unix:/home/django/gunicorn.socket:/" 2018/03/13 22:28:19 [error] 2104#2104: *46 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "46.101.7.245" 2018/03/13 22:31:51 [error] 2104#2104: *49 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "46.101.7.245" 2018/03/13 22:32:05 [error] 2104#2104: *52 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 93.55.242.118, server: _, request: "GET /admin HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/admin", host: "46.101.7.245" 2018/03/13 22:40:18 [error] 2104#2104: *55 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET /admin HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/admin", host: "46.101.7.245" 2018/03/13 22:40:23 [error] 2104#2104: *55 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "46.101.7.245" 2018/03/13 22:44:08 [error] 2104#2104: *59 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 93.55.242.118, server: _, req…
has title: Django app deployed to Digitalocean 502 Bad Gateway
type: Question
tagged with: nginx
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: digital-ocean
score: 0
has answer: http://stackoverflow.com/a/49269811

http://stackoverflow.com/comment/85534593
has text: I'll try, and maybe ask again if I have some particular issue :D thanks again!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49241875

http://stackoverflow.com/q/49259169
type: Question
has comment: http://stackoverflow.com/comment/85522225
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85522156
has title: python CSV file reader adding an extra blank column
linked to: http://stackoverflow.com/q/11503637
has body: I have a CSV file that is generated by one of my clients and each row is a bunch of rows something like: 81.20414497158737,172.9103317265073,95.21067544500737,158.57147044650964,-84.25709905588982,-63.29849243164,-82.75973199495726,-61.30949985476218,-63.29849243164,-59.267658616873035, Notice the , at the end of each row which is then followed by a carriage return. The problem is that when I read it in python it generates an extra blank column. So, I read it as: import csv path = "path-to-file.csv" with open(path) as f: csv_file = csv.reader(f, delimiter=',') for row in csv_file: print(row) This prints an example row as: ['81.91382020661584', '172.6194974551915', '95.000737839972', '157.5919980874564', '-83.09440263458094', '-63.29849243164', '-82.28324366654695', '-61.65345112997187', '-63.29849243164', '-57.6629400774182', ''] Note the extra blank column at the end. Is there a way to work around this with the python CSV reader?
score: 0
has comment: http://stackoverflow.com/comment/85522333
answer count: 0
tagged with: http://stackoverflow.com/tag/csv
duplicate of: http://stackoverflow.com/q/11503637
has comment: http://stackoverflow.com/comment/85521960
has comment: http://stackoverflow.com/comment/85521636

http://stackoverflow.com/comment/85524978
score: 0
comment on: http://stackoverflow.com/q/49260693
type: Comment
type: QuestionComment
has text: Do you want it to remain as a 2D list?

http://stackoverflow.com/comment/85529217
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49262522
has text: I'm writing to a completely different file, so i don't think that's the issue, but i might be wrong. Ill try it and see what happens (Yep still get the error).

del
tag name: del
tags question: http://stackoverflow.com/q/49266464
type: Tag

oop
tags question: http://stackoverflow.com/q/49159557
tags question: http://stackoverflow.com/q/49150549
tags question: http://stackoverflow.com/q/49161846
tags question: http://stackoverflow.com/q/49167442
tags question: http://stackoverflow.com/q/49198122
tags question: http://stackoverflow.com/q/49188400
tags question: http://stackoverflow.com/q/49155657
tags question: http://stackoverflow.com/q/49162957
tags question: http://stackoverflow.com/q/49252844
tag name: oop
tags question: http://stackoverflow.com/q/49134201
tags question: http://stackoverflow.com/q/49143001
tags question: http://stackoverflow.com/q/49171095
tags question: http://stackoverflow.com/q/49167024
tags question: http://stackoverflow.com/q/49142362
tags question: http://stackoverflow.com/q/49222472
tags question: http://stackoverflow.com/q/49121895
tags question: http://stackoverflow.com/q/49211118
type: Tag
tags question: http://stackoverflow.com/q/49184456
tags question: http://stackoverflow.com/q/49206732
tags question: http://stackoverflow.com/q/49188794
tags question: http://stackoverflow.com/q/49265245
tags question: http://stackoverflow.com/q/49221338
tags question: http://stackoverflow.com/q/49271771
tags question: http://stackoverflow.com/q/49146388

http://stackoverflow.com/comment/85536278
comment on: http://stackoverflow.com/q/49266391
type: QuestionComment
type: Comment
has text: `.title h2` ? Start one level up then go by the actual element tag instead of its class.
score: 2

http://stackoverflow.com/comment/85386216
type: QuestionComment
type: Comment
score: 0
has text: Use Jupyter Notebook. Executing `estimator.train()` will generate the log
comment on: http://stackoverflow.com/q/49188239

http://stackoverflow.com/comment/85355930
has text: @szeta I'm noting that `rolling` doesn't work as it is with strings, it seems to skip every non-numeric value, I'm looking into an alternative path.
type: Comment
comment on: http://stackoverflow.com/a/49173921
score: 0
type: AnswerComment

http://stackoverflow.com/a/49251129
upvote count: 1
has comment: http://stackoverflow.com/comment/85511787
answers question: http://stackoverflow.com/q/49237363
has comment: http://stackoverflow.com/comment/85535744
type: Answer
has body: You can decouple the animation rate from the frame rate by tying it to time in some way. One way is to use pygame.time.get_ticks() to return the number of milliseconds since pygame.init() was called. If you store this value, you can measure how much time has elapsed and animate appropriately. def update(self): self.elapsed = pygame.time.get_ticks() - self.elapsed if self.elapsed &gt; 500: # animate every half second self.animate() Note: you'll also need to initialise self.elapsed in the constructor.
accepted answer of: http://stackoverflow.com/q/49237363
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49211603
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49209226
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85428460
type: Answer
accepted answer of: http://stackoverflow.com/q/49209226
has body: The default JSON encoder (that you linked to) only knows how to handle "easy" things like dicts, lists, strings, and numbers. It makes no attempt to serialize classes so there is no "special" method you can implement on a class to make it JSON serializable. Basically, if you want to use json.dumps, you're going to have to pass something extra in order to make it work with your custom classes. When the encoder doesn't know what to do with the object, it calls the default method. Based on your question, I believe you discovered that already but you're a bit confused about where the default method should go. Here's an example that does what you're looking for: import json def default(o): if hasattr(o, 'to_json'): return o.to_json() raise TypeError(f'Object of type {o.__class__.__name__} is not JSON serializable') class A(object): def __init__(self): self.data = 'stuff' self.other_data = 'other stuff' def to_json(self): return {'data': self.data} a = A() b = [a, 3, 'hello'] c = {'hey': b, 'huy': 3} d = [a, b, c] print(json.dumps(d, default=default)) Which prints out: [{"data": "stuff"}, [{"data": "stuff"}, 3, "hello"], {"hey": [{"data": "stuff"}, 3, "hello"], "huy": 3}] Note that every custom class just needs to implement the to_json method now and everything will serialize correctly (assuming you pass the custom default function in when calling json.dumps).

http://stackoverflow.com/comment/85299396
has text: Wow! Thank you so much for this fast and right answer! \ instead of / is the right answer.
comment on: http://stackoverflow.com/a/49147378
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/85416685
score: 1
comment on: http://stackoverflow.com/a/49204794
has text: This is definitely interesting though the problem with isdecimal is that it doesn't handle float. +1 :)
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49179181
type: Question
type: UnansweredQuestion
answer count: 1
score: 0
has title: Matplotlib overlaying imshow and pie chart
tagged with: matplotlib
tagged with: python
has answer: http://stackoverflow.com/a/49179419
has body: I am trying to overlay a pie chart over radial gradient as a background. It does work, but I want the figure to show the entire radial gradient (without the figure boundary being cut as a square). How do I acheive this? I want something like this to this Thank you. import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt delta = 0.02 x = y = np.arange(-1.0, 1.0, delta) X, Y = np.meshgrid(x, y) plt.imshow(-X**2+-Y**2, interpolation='bicubic', cmap=plt.cm.Blues, origin='lower',extent=[-1.2, 1.2, -1.2, 1.2]) plt.pie([1] , explode=None, radius=1.2 \ , labels=['H'] \ , labeldistance=0.9 \ , startangle=270 \ , colors=[g(0.70)]) plt.show()

http://stackoverflow.com/q/49185027
tagged with: random
score: -1
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/49185111
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49185111
downvote count: 1
favorite count: 0
has title: Why does my function throw a TypeError; num() got an unexpected keyword argument 'ip'?
type: AnsweredQuestion
has body: My goal is to create a random int (1-254) but keep getting the unexpected keyword argument error when trying to use click. What am I doing wrong? import click from random import randint as r @click.command() @click.option("--ip", default="192.168.0.1", help="IP Address") @click.option('--host', default="www.google.com" , help="Host URL") def num(self): x = r(1,254) click.echo(x) if __name__ == "__main__": num()

http://stackoverflow.com/q/49189962
score: 0
tagged with: apache-spark
tagged with: pyspark
has comment: http://stackoverflow.com/comment/85386181
tagged with: python
has comment: http://stackoverflow.com/comment/85385501
has body: I have a dataframe, which one column 'topic1' is a type of structure and another one 'topic' is string, i want to extract the value of 'topic1' according to column 'topic' use the udf. But something goes wrong because the number of dataframe is mismatch. def mapExtr_miss(map_var, key, miss_num): try: if key and str(key) in map_var.keys() and len(map_var[str(key)])&gt;0: return map_var[str(key)] except: return [0]*miss_num def udf_Extr_miss(miss_num): return udf(lambda map_var, key: mapExtr_miss(map_var, key, miss_num), ArrayType(IntergType())) the results as follows: c1 = combine.withColumn('topic2', udf_Extr_miss(198)(col('topic1'), col('topic'))) c1.count() 266132 combine.count() 271997 c2= combine.withColumn('topic2', udf_Extr_miss(41)(col('topic1'), col('topic'))) c2.count() 277497 thanks for any idea about this problem c1.head(n=2) [Row(uid=u'u1', newsid=u'451', topic1=Row(98=None, 99=None, 9999=[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, 0, 0, 0, 0, 0, 1212, 1212, 1212, 1212, 1212, 1212, 1, 1, 1, 500, 0]), topic=None, heat=0.5841230154037476, jumpLink=0, topic2=None),Row(uid=u'u822316', newsid=u'4514', topic1=Row(98=None, 99=None, 9999=[1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1212, 1212, 1212, 1212, 1212, 1212, 1, 1, 1, 500, 0]), topic='9999', heat=0.5841230154037476, jumpLink=0, topic2=[1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1212, 1212, 1212, 1212, 1212, 1212, 1, 1, 1, 500, 0])]
answer count: 1
accepted answer: http://stackoverflow.com/a/49198620
has comment: http://stackoverflow.com/comment/85385269
has comment: http://stackoverflow.com/comment/85385462
has title: Pyspark apply udf to add a new col, but the the number of rows is not correspond
has answer: http://stackoverflow.com/a/49198620
type: Question
tagged with: user-defined-functions
type: AnsweredQuestion

http://stackoverflow.com/a/49308420
type: Answer
answers question: http://stackoverflow.com/q/49270010
has body: I emailed the developer and this was the response. the python bindings for LCIO using swig have been discontinued a long time ago and they have nothing to do with pyLCIO, so that document you found is not relevant. pyLCIO builds on top of the pyROOT bindings, making use of the ROOT dictionaries provided with LCIO that allow to store LCIO objects directly in ROOT files. These dictionaries also implicitly provide python interfaces to all classes. In pyROOT c-style arrays (or any other pointer to basic types) have to be passed as python arrays or numpy arrays of the corresponding type (see for example "19.1.9.2 Writing a Tree" in https://root.cern.ch/root/htmldoc/guides/users-guide/ROOTUsersGuide.html#using-pyroot). (Also, you should use IMPL.MCParticleImpl to construct MCParticles by hand, see http://lcio.desy.de/v02-09/doc/doxygen_api/html/classIMPL_1_1MCParticleImpl.html. The IOIMPL version only adds a constructor from an SIO stream which is needed to read it from an LCIO file). In this case you should do from pyLCIO import IMPL from array import array particle=IMPL.MCParticleImpl() p = array('f', [1.0, 2.0, 3.0]) # the type ‘f’ has the length of a C++ float, for a double use ‘d' particle.setMomentum(p) Since I never liked the design choice of LCIO to pass physics vectors as c-style arrays I extended all class interfaces in pyLCIO to also support the usage of ROOT physics vectors (TVector3). All setters and getters that are in fact physics vectors have another version called setXxxVec() or getXxxVec() which accept or return physics vectors instead. If an object has getEnergy and getMomentum it will also have getLorentzVec in pyLCIO which returns a ROOT TLorentzVector object. See https://github.com/iLCSoft/LCIO/blob/master/src/python/pyLCIO/base/DecorateLcioClasses.py for the extended interfaces. So in your example you could also use from pyLCIO import IMPL from ROOT import TVector3 particle=IMPL.MCParticleImpl() p = TVector3(1.0, 2.0, 3.0) particle.setMomentumVec(p)…
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/a/49193348
type: Answer
answers question: http://stackoverflow.com/q/49192469
score: 0
has body: import pandas as pd df = pd.read_csv('input1.csv', sep=',', header=None) df.applymap(lambda x: x*10 if "0.0" in str(x) else x).to_csv('out1.csv')

http://stackoverflow.com/comment/85439210
type: Comment
comment on: http://stackoverflow.com/q/49217617
score: 0
type: QuestionComment
has text: I'm at a loss. Can you post an image/`ls` of the directory your `.py` and `.txt` file is in?

http://stackoverflow.com/q/49256682
tagged with: python-sphinx
type: UnansweredQuestion
downvote count: 0
upvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/85517120
tagged with: cron
score: 1
type: Question
has title: Sphinx Python: create documentation where python script imports a module I don't have installed
answer count: 0
linked to: http://stackoverflow.com/q/15889621
has body: Is it possible to create a documentation in Sphinx (Python), where one of the python scripts imports a module (in this case python-crontab (https://pypi.python.org/pypi/python-crontab)) that I don't have installed? from crontab import CronTab Basically I am writing the documentation on a Windows machine. The code works fine, but not on a Windows machine since crontab is only for Linux. Thus, I was wondering if there is a way in Sphinx to tell it that it doesn't matter if it cannot find crontab

http://stackoverflow.com/a/49155391
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49153509
answers question: http://stackoverflow.com/q/49153509
has comment: http://stackoverflow.com/comment/85338202
type: Answer
has body: You could adjust the location based on the height of each bar: import matplotlib.pyplot as plt x = [0, 1, 2, 3, 4, 5] y = [2.09e+12, 3.2e+09, 6.41e+10, 6.34e+11, 1.75e+07, 3.29e+09] colors = ['blue', 'orange', 'green', 'red', 'blue', 'black'] split_point = max(y) / 4.0 bars = plt.bar(x, y, color=colors) for bar, color in zip(bars, colors): bbox = bar.get_bbox() va, y = ('top', bbox.y1) if bbox.y1 &gt; split_point else ('bottom', 0) plt.annotate(' {:.2e}'.format(bbox.y1), xy=(bbox.x1+0.05, y), xycoords='data', rotation=90, va=va, color=color) plt.show() This calculates the highest bar and aligns anything less than a 1/4 height to be aligned to the bottom.
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85338290
type: AcceptedAnswer

http://stackoverflow.com/a/68615216
has comment: http://stackoverflow.com/comment/125636262
answers question: http://stackoverflow.com/q/49161174
score: 3
type: Answer
upvote count: 3
has body: I have faced a similar issue and found out that I have missed the flatten layer between CNN and Dense layers. Adding the flatten layer resolved this issue for me.
downvote count: 0

http://stackoverflow.com/comment/85374926
comment on: http://stackoverflow.com/a/49175904
type: Comment
score: 0
type: AnswerComment
has text: This does not work because I need to keep `stdin` open to receive input continuously while subprocesses further down the chain handle the input to date. The missing piece from my example was flushing the output buffers in the subprocesses' code. On Linux `./cat.py` will work if you have permission to execute the file (and your Python 3 binary is at `/usr/bin/python3`).

http://stackoverflow.com/q/49234333
upvote count: 2
type: UnansweredQuestion
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: frameworks
has answer: http://stackoverflow.com/a/73086645
tagged with: python
has title: Kivy performance degradation over time
tagged with: kivy
score: 2
tagged with: kivy-language
has answer: http://stackoverflow.com/a/49255942
answer count: 2
has body: I am learning Kivy, and to make it more fun I am creating a small 2D game. For now its just a tank that can be controlled with WASD and shot projectiles with o. The problem is that the FPS degrades over time. This happens even if I do nothing in the game. I don´t have an FPS counter, but its something like half the FPS after a minute of gametime. My feeling is that the problem lies somewhere in the updating of canvas in widgets. Since the slowdowns occur even if the player does nothing for the whole game, its seems like there is data somewhere that is just added and added. I don´t know how to better explain it, other than it's weird... A quick overview of how the game is programmed so far: The main widget is the class Game. It detects keypresses and runs "Clock.schedule_interval-function". The Tank widget is a child of Game. It holds some data and loads the hull and turret sprites via Kivys Image widget, which becomes its child. It has its own update function that updates everything tank-related, including setting the position of its canvas and rotating the hull and turret image canvas. The update-function in the Tank widget class is invoked by "Clock.schedule_interval" in Game class. The Shots widget does the same as the Tank widget, only it holds data for each shot fired instead "Clock schedule_interval"-function holds a list of each shot widget, and deletes them when they get off screen. However, the slowdown problems persist even if no shots are fired. I have attached the complete code. This might be excessive, but I don´t know which part of it that provokes slowdowns. If you want to run the game, just put those four python-files in the same folder, and the images in a sub-folder called "images tank". I hope someone can take a look at it main.py: #Import my own modules: import tank import shot from stats import Stats #Import kivy: from kivy.app import App from kivy.uix.widget import Widget from kivy.clock import Clock #Set window size properties: from kivy.confi…

http://stackoverflow.com/comment/85467534
has text: So I should also put the import statements inside the if __name__ == 'main' except for the import multiprocessing?
type: Comment
comment on: http://stackoverflow.com/a/49232067
score: 0
type: AnswerComment

http://stackoverflow.com/a/49382555
downvote count: 0
has body: Taking a look at the source code, the result matrix is created here using np.zeros() with no dtype keyword argument which would result in dtype being set to default value set in function definition which is float. I think the choice of this data type is made to support all forms of transformation like tfidf which results in non-integer output. So I think you have to options: 1. Change the source code You can change add a keyword argument to definition of texts_to_matrix like dtype and change the line where matrix is created to x = np.zeros((len(sequences), num_words), dtype=dtype) 2.Use another tool for preprocessing: You can preprocess your text using another tool and then feed it to keras network. For example you can use scikit learn's CountVectorizer like: from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer(dtype=np.int8, ...) matrix = cv.fit_transform(texts).toarray()
accepted answer of: http://stackoverflow.com/q/49263269
type: Answer
answers question: http://stackoverflow.com/q/49263269
has comment: http://stackoverflow.com/comment/86144485
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/86149498
type: AcceptedAnswer

http://stackoverflow.com/comment/85418999
type: Comment
type: QuestionComment
has text: I think the problem here lies in the font Matplotlib is using. Try changing the font using the RcParams in Matplotlib
score: 1
comment on: http://stackoverflow.com/q/49171947

http://stackoverflow.com/q/49184502
has answer: http://stackoverflow.com/a/49538226
tagged with: pycharm
type: Question
tagged with: airflow
has comment: http://stackoverflow.com/comment/85375868
upvote count: 1
tagged with: python
has body: The airflow docs suggest that a basic sanity check for a DAG file is to interpret it. ie: $ python ~/path/to/my/dag.py I've found this to be useful. However, now I've created a plugin, MordorOperator under $AIRFLOW_HOME/plugins: from airflow.plugins_manager import AirflowPlugin from airflow.utils.decorators import apply_defaults from airflow.operators import BaseOperator from airflow.exceptions import AirflowException import pika import json class MordorOperator(BaseOperator): JOB_QUEUE_MAPPING = {"testing": "testing"} @apply_defaults def __init__(self, job, *args, **kwargs): super().__init__(*args, **kwargs) # stuff def execute(self, context): # stuff class MordorPlugin(AirflowPlugin): name = "MordorPlugin" operators = [MordorOperator] I can import the plugin and see it work in a sample DAG: from airflow import DAG from airflow.operators import MordorOperator from datetime import datetime dag = DAG('mordor_dag', description='DAG with a single task', start_date=datetime.today(), catchup=False) hello_operator = MordorOperator(job="testing", task_id='run_single_task', dag=dag) However, when I try to interpret this file I get failures which I suspect I shouldn't get since the plugin successfully runs. My suspicion is that this is because there's some dynamic code gen happening at runtime which isn't available when a DAG is interpreted by itself. I also find that PyCharm can't perform any autocompletion when importing the plugin. (venv) 3:54PM /Users/paymahn/solvvy/scheduler mordor.operator ✱ ❮❮❮ python dags/mordor_test.py section/key [core/airflow-home] not found in config Traceback (most recent call last): File "dags/mordor_test.py", line 2, in from airflow.operators import MordorOperator ImportError: cannot import name 'MordorOperator' How can a DAG using a plugin be sanity tested? Is it possible to get PyCharm to give autocompletion for the custom operator?
answer count: 1
has comment: http://stackoverflow.com/comment/85375770
has title: How to validate airflow DAG with customer operator?
type: AnsweredQuestion
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/49538226
favorite count: 0

http://stackoverflow.com/comment/85500436
score: 0
type: Comment
has text: hi martineau , i'm trying to extract value from variable "name'' which is of type StringVar, and second, the extraction logic is written in function, so chances are there that correct reference is not passed.Since I'm new to Tkinter can you help me with the correct code snippet
comment on: http://stackoverflow.com/q/49247669
type: QuestionComment

http://stackoverflow.com/q/49252677
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: database
downvote count: 0
has title: Opening a Visual FoxPro DBC file in Python
tagged with: python
has comment: http://stackoverflow.com/comment/85565374
has comment: http://stackoverflow.com/comment/85525467
has comment: http://stackoverflow.com/comment/85525481
score: 2
has comment: http://stackoverflow.com/comment/85567510
linked to: http://stackoverflow.com/q/13994584
tagged with: visual-foxpro
favorite count: 0
type: Question
has body: I have an old system that I'm working on that uses Visual FoxPro so I was wondering if there's any way I can access the .DBC file using Python 3.6.4 in order to create reports for it. I've read using dbfread but that only looks at one table at a time and preferably like to look at multiple at once. Is there any modules or methods that I could use to not only look at but also edit this database?

http://stackoverflow.com/a/49273330
has comment: http://stackoverflow.com/comment/85549772
has body: Ctrl+C signals an interrupt. Python interpreter checks for the interrupt regularly, and raises KeyboardInterrupt exception, when it detects one. When Paramiko is waiting for an incoming data on a socket, the checking for interrupts is probably suspended (just guessing). So if a remote command is not producing any output, you cannot break the local script. Your loop.py produces an output using print(i), so your local Python script can be interrupted at the moment it's processing the output. In any case, it's not the remote script that cannot be interrupted, it's the local script. So it has probably nothing to do with time.sleep as such. See also: Stopping python using ctrl+c https://docs.python.org/3/library/exceptions.html#KeyboardInterrupt If you actually do not want to wait for the command to finish, your question is not really about Python (nor Paramiko), but about Linux. See Execute remote commands, completely detaching from the ssh connection.
answers question: http://stackoverflow.com/q/49271629
has comment: http://stackoverflow.com/comment/85583809
has comment: http://stackoverflow.com/comment/85585771
has comment: http://stackoverflow.com/comment/85549685
score: 0
has comment: http://stackoverflow.com/comment/85549621
has comment: http://stackoverflow.com/comment/85553611
has comment: http://stackoverflow.com/comment/85552095
has comment: http://stackoverflow.com/comment/85550624
type: Answer
has comment: http://stackoverflow.com/comment/85553469

datetime
tags question: http://stackoverflow.com/q/49195188
tags question: http://stackoverflow.com/q/49244430
tags question: http://stackoverflow.com/q/49177077
tags question: http://stackoverflow.com/q/49277417
tags question: http://stackoverflow.com/q/49205798
tag name: datetime
tags question: http://stackoverflow.com/q/49163361
tags question: http://stackoverflow.com/q/49238359
tags question: http://stackoverflow.com/q/49279067
tags question: http://stackoverflow.com/q/49150187
tags question: http://stackoverflow.com/q/49239262
tags question: http://stackoverflow.com/q/49230012
tags question: http://stackoverflow.com/q/49191998
tags question: http://stackoverflow.com/q/49161684
tags question: http://stackoverflow.com/q/49276429
tags question: http://stackoverflow.com/q/49143128
tags question: http://stackoverflow.com/q/49263547
tags question: http://stackoverflow.com/q/49269997
tags question: http://stackoverflow.com/q/49215267
tags question: http://stackoverflow.com/q/49160939
tags question: http://stackoverflow.com/q/49180476
tags question: http://stackoverflow.com/q/49132403
tags question: http://stackoverflow.com/q/49240478
tags question: http://stackoverflow.com/q/49243434
tags question: http://stackoverflow.com/q/49157349
type: Tag
tags question: http://stackoverflow.com/q/49204453
tags question: http://stackoverflow.com/q/49226624
tags question: http://stackoverflow.com/q/49172824
tags question: http://stackoverflow.com/q/49250239
tags question: http://stackoverflow.com/q/49193536
tags question: http://stackoverflow.com/q/49179132
tags question: http://stackoverflow.com/q/49127697
tags question: http://stackoverflow.com/q/49157786
tags question: http://stackoverflow.com/q/49132090
tags question: http://stackoverflow.com/q/49143411
tags question: http://stackoverflow.com/q/49130183
tags question: http://stackoverflow.com/q/49223770
tags question: http://stackoverflow.com/q/49244017
tags question: http://stackoverflow.com/q/49267837

http://stackoverflow.com/a/49264724
score: 0
accepted answer of: http://stackoverflow.com/q/49264272
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49264272
has body: I think it's important to recognize here that the speed of the rectangle object here is a scalar value, not it's vector counterpart velocity. You are attempting to multiply the rectySpeed (a scalar value) by -(math/pi)/2, which is a value that will be returned in radians as @0x5453 mentioned. As far as the rectangle bouncing differently depending on the wall that it contacted, you have not specified the differing constraints that you intend to impose. I think you may want to consider why you want the rectangle to always bounce at a 90° angle. Note that a rectangle that always bounces at a 90° angle would yield some very odd functionality to the player/user. The angle that the rectangle is approaching the wall measured from the horizontal will be equal to the angle that the rectangle will rebound off the wall measured from the vertical line of the wall to it's new path (in the case of an x-directional bounce). In terms of an accurate physics engine, you may want to consider just simplifying your mechanics to the following in the case that the rectangle contacts a wall: if rect_y&gt;450 or rect_y&lt;0: rectySpeed=rectySpeed*-1 if rect_x&gt;650 or rect_x&lt;0: rectxSpeed=rectxSpeed*-1 The above ensures that the rectangle object simply changes direction, therefore the magnitude of the rectangle's speed does not change, however the velocity indeed does since it is a vector quantity.
type: Answer

http://stackoverflow.com/comment/85414396
type: Comment
score: 0
type: AnswerComment
has text: Hi Wasi, thanks for the answer first. The thing is that, I have multiple LSTMs and I concatenate the results together(torch.Merge) to predict the target. For example, for a, the input is a[0][0] for LSTM_0, a[0][1] for LSTM_1, and a[0][2] for LSTM_2. The results for each LSTM will be merged. In this way, is there any method to sort the input sequences?
comment on: http://stackoverflow.com/a/49204483

http://stackoverflow.com/comment/85606718
type: QuestionComment
comment on: http://stackoverflow.com/q/49240236
score: 0
has text: I'll gladly provide a jobId, but not through StackOverflow. Do you have a feedback email for dataflow? My team has previously used cloudml-feedback@google.com.
type: Comment

http://stackoverflow.com/q/49217783
type: Question
tagged with: tkinter
type: UnansweredQuestion
answer count: 1
tagged with: ttk
tagged with: python
has answer: http://stackoverflow.com/a/49223415
has comment: http://stackoverflow.com/comment/95707248
score: 0
tagged with: colors
has title: How to change tkinter ttk Notebook background colour (Python)?
has body: I am trying to change the background color of the ttk Notebook widget in my python tkinter application so that it matches the blue color instead of being white. I've tried searching for hours but to no avail. Is it not working because I'm working on a mac? tabs_notebook = ttk.Notebook(self) tabs_notebook.configure(bg=DARKBLUE) tabs_notebook.pack() view_tab = ttk.Frame(tabs_notebook) new_tab = ttk.Frame(tabs_notebook) tabs_notebook.add(view_tab, text="View Patient Details") tabs_notebook.add(new_tab, text="Add New Patient")

http://stackoverflow.com/q/49167011
upvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: plot
has body: I want to set the x tick density by specifying how many ticks to skip each time. For example, if the x axis is labelled by 100 consecutive dates, and I want to skip every 10 dates, then I will do something like import numpy as np import pandas as pd import matplotlib.pyplot as plt ts = pd.period_range("20060101", periods=100).strftime("%Y%m%d") y = np.random.randn(100) ax = plt.subplot(1, 1, 1) ax.plot(ts, y) xticks = ax.get_xticks() ax.set_xticks(xticks[::10]) plt.xticks(rotation="vertical") plt.show() However the output is out of place. Pyplot only picks the first few ticks and place them all in the wrong positions, although the spacing is correct: What can I do to get the desired output? Namely the ticks should be instead: ['20060101' '20060111' '20060121' '20060131' '20060210' '20060220' '20060302' '20060312' '20060322' '20060401'] @klim's answer seems to put the correct marks on the axis, but the labels still won't show. An example where the date axis is correctly marked yet without labels:
has answer: http://stackoverflow.com/a/49167525
has title: Pyplot set_xticks doesn't work as expected
score: 1
tagged with: matplotlib
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49204453
answer count: 3
has answer: http://stackoverflow.com/a/49204512
duplicate of: http://stackoverflow.com/q/13648774
upvote count: 16
favorite count: 0
type: Question
score: 14
linked to: http://stackoverflow.com/q/13648774
has title: How can I get year - month - day from a numpy datetime64?
has answer: http://stackoverflow.com/a/49204479
accepted answer: http://stackoverflow.com/a/49204479
tagged with: datetime
tagged with: python
has body: I have a numpy datetime. numpy.datetime64('2010-06-01T00:00:00.000000000') How can I get something like: numpy.datetime64('2010-06-01') or '2010-06-01' Basically, I want to remove the hour and beyond timestamp.
tagged with: numpy
possible better answer: http://stackoverflow.com/a/49204512
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49204500
downvote count: 2

http://stackoverflow.com/a/49272654
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49257433
downvote count: 0
has body: Try this: driver.switch_to_alert().accept()
has comment: http://stackoverflow.com/comment/85549808
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49257433

http://stackoverflow.com/a/66553864
answers question: http://stackoverflow.com/q/49155540
score: 0
has body: After digging in, to give the full background on this, first of all SciPy relies on having NumPy already installed. The SciPy wheel's setup.py file uses NumPy functionality to configure and install the wheel. SciPy setup.py: ... if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) Secondly, when just trying to use the wheel, if you run into this error, you can see after inspecting the wheel's files that the reason is the binary wheels have a naming convention where the shared object file, here it's called _ccallback_c.so, is instead named based on the architecture that the binary wheel supports. When trying to import the shared object by file name in /_lib/_ccallback.py it can't find it, hence this error (line 1 in /_lib/_ccallback.py) because, instead of being named _ccallback_c.so it's called _ccallback_c.cpython-36m-x86_64-linux-gnu.so or another architecture variation: from . import _ccallback_c These file names may be an artifact of having not run the NumPy setup process yet or something related to Cython, that I'm not quite sure about. But the easiest fix is to change the .whl extension to .zip and rename all those relevant .so files to not contain the architecture snippet. Then change .zip -&gt; .whl and it should be good to go.
type: Answer

http://stackoverflow.com/comment/85325173
has text: This is not quite the same problem as mutable shared default values, but the visible confusion is the same, so [the FAQ about those](https://docs.python.org/3/faq/programming.html#why-are-default-values-shared-between-objects) may be helpful for understanding this case.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49159840

http://stackoverflow.com/q/49210113
has comment: http://stackoverflow.com/comment/85425029
has comment: http://stackoverflow.com/comment/85425006
has comment: http://stackoverflow.com/comment/85425123
has comment: http://stackoverflow.com/comment/85425105
accepted answer: http://stackoverflow.com/a/49210448
has body: I'm a bit new to Python and Pandas and I'm trying to do a very simple thing, which is looping over a column of a pandas dataframe called df and modify a value, like in the following snippet for i in range(0,len(df.time) - 1): if df.time[i] == df.time[i+1]: df.at[i,'time'] = df.time[i] - 1 df is the dataframe, which has the column "time". I'm looking for repetitive ticks on time, and if two subsequent timesteps have the same value, I decrement the first by 1. The problem is that it takes too much time! I ran it for over 20 minutes and it didn't end! On Matlab, the same thing runs in seconds. Why is that and how can I fix? I should also say that the size of this dataframe is over 9 million. Thanks in advance.
answer count: 1
has comment: http://stackoverflow.com/comment/85424900
has title: Very long execution during loop over a pandas dataframe
tagged with: loops
has comment: http://stackoverflow.com/comment/85425066
has comment: http://stackoverflow.com/comment/85424793
has comment: http://stackoverflow.com/comment/85424876
has comment: http://stackoverflow.com/comment/85424788
type: Question
type: AnsweredQuestion
score: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49210448
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/49220671
answers question: http://stackoverflow.com/q/49220617
type: Answer
has body: i am not a flask user but perhaps this is your wanted decorator def timed_cache(cache_time:int, nullable:bool=False): result = '' timeout = 0 def decorator(function): def wrapper(*args, **kwargs): nonlocal result nonlocal timeout if timeout &lt;= time.time() or not (nullable or result): result = function(*args, **kwargs) timeout = time.time() + cache_time return result return wrapper return decorator
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85269701
comment on: http://stackoverflow.com/q/49130476
score: 0
type: Comment
type: QuestionComment
has text: I want to know what functions can be applied rather than the list of methods of the class [I'm probably using the wrong term, but e.g mean() is not a method of rolling_window [i think?], but can be applied]

http://stackoverflow.com/comment/85455664
comment on: http://stackoverflow.com/q/49225933
has text: You *could* use a structured datatype, something like `bigram_type = np.dtype([('x','u4'),('y','u4')])`, not sure how useful this would be. I would just stick with `list` objects
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85417968
has text: maybe have a look at https://docs.python.org/3/tutorial/classes.html#a-first-look-at-classes
type: QuestionComment
comment on: http://stackoverflow.com/q/49206448
score: 0
type: Comment

http://stackoverflow.com/q/49245779
type: Question
has body: Hi I'm using Ubuntu and have created a conda environment to build a project. I'm using Python 2.7 and Pytorch plus some other libraries. When I try to run my code in Spyder I receive a ModuleNotFoundError telling me that torch module hasn't been installed. However, when I type conda list into a terminal I can clearly see torch is there. How can I configure this to work with Spyder? Thanks.
has title: ModuleNotFoundError in Spyder with Python
type: UnansweredQuestion
answer count: 1
tagged with: ubuntu
score: 0
has answer: http://stackoverflow.com/a/49248423
tagged with: spyder
tagged with: python

http://stackoverflow.com/q/49247477
has comment: http://stackoverflow.com/comment/85500242
has comment: http://stackoverflow.com/comment/85500564
has body: I have written some code which uses pandas. It is working fine when i execute it from the command prompt. But when I make it as a .exe file and try to run it from command prompt, it getting this error as below: Traceback (most recent call last): File "Result_generator.py", line 2, in &lt;module&gt; File "c:\users\akhil\appdata\local\temp\pip-build-rccgn1\pyinstaller\PyInstaller\loader\pyimod03_importers.py", line 396, in load_module File "result_test.py", line 3, in &lt;module&gt; File "c:\users\akhil\appdata\local\temp\pip-build-rccgn1\pyinstaller\PyInstaller\loader\pyimod03_importers.py", line 396, in load_module File "site-packages\pandas\__init__.py", line 35, in &lt;module&gt; ImportError: C extension: No module named tslib not built. If you want to import pandas from the source directory, you may need to run 'python setup.py build_ext --inplace --force' to build the C extensions first. [12340] Failed to execute script Result_generator I have installed tslib package also. But of no use. What is the wrong i am doing? Please help me with this. Thanks in Advance. Doubt: In the error statement, it is saying to run "python setup.py..." command. But I didn't find any setup.py file in pandas directory. What is the solution for that?
score: 0
has comment: http://stackoverflow.com/comment/85500447
linked to: http://stackoverflow.com/q/29109324
tagged with: pandas
tagged with: pyinstaller
has comment: http://stackoverflow.com/comment/85500627
has comment: http://stackoverflow.com/comment/85501350
has comment: http://stackoverflow.com/comment/85498800
type: Question
has title: ImportError: C Extension : no module named tslib.... error is being displayed if I run .exe file made using PyInstaller
has comment: http://stackoverflow.com/comment/85499604
has comment: http://stackoverflow.com/comment/85500528
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49185754
answer count: 1
tagged with: file
has comment: http://stackoverflow.com/comment/85377097
has comment: http://stackoverflow.com/comment/85377787
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85377132
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49185773
accepted answer: http://stackoverflow.com/a/49185773
has comment: http://stackoverflow.com/comment/85377171
has comment: http://stackoverflow.com/comment/85377289
has comment: http://stackoverflow.com/comment/85377152
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85377119
has title: Python If == true statement only working on last line of readline
linked to: http://stackoverflow.com/q/43950757
has comment: http://stackoverflow.com/comment/85377098
has body: My function only says that the last word in a file of words is an anagram (the first helper function). But every word in the file is an anagram of the word I tested and returns true independently with the helper function outside of the main function. I am not sure if it has something to do with /n being a part of the string, and then it accounting for that, but I tried putting in an if statement saying to delete it if it was in there and that did not work either. I also did test to make sure it is running through each word in the .txt file and it is. def is_anagram(string1, string2): """Returns True if the two strings are anagrams of eachother. str, str -&gt; bool""" if sorted(string1)==sorted(string2): return True else: return False def find_anagrams(word): final = [] content = open("small_list.txt") content.close while True: line = content.readline() print(line) if is_anagram(word, line) == True: print("bruh") final.append(line) elif line == '': break return final
upvote count: 1
score: 1

http://stackoverflow.com/a/49247402
type: AcceptedAnswer
has body: x = 1 y = 1 print (x + y == 16) # False print ((10*x) + (25*y) == 250) # False print ((x + y == 16) == ((10*x) + (25*y) == 250)) # False == False x = 10 y = 6 print (x + y == 16) # True print ((10*x) + (25*y) == 250) # True print ((x + y == 16) == ((10*x) + (25*y) == 250)) # True == True
type: Answer
answers question: http://stackoverflow.com/q/49247325
score: 0
accepted answer of: http://stackoverflow.com/q/49247325

http://stackoverflow.com/q/49182978
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85372560
has comment: http://stackoverflow.com/comment/85372100
has comment: http://stackoverflow.com/comment/85374427
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85371954
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85371860
has comment: http://stackoverflow.com/comment/85372135
has title: How can embedded python call a C++ class's function?
has comment: http://stackoverflow.com/comment/85372621
tagged with: python
has comment: http://stackoverflow.com/comment/85371788
accepted answer: http://stackoverflow.com/a/49245482
tagged with: c++
type: AnsweredQuestion
score: 2
tagged with: python-import
has comment: http://stackoverflow.com/comment/85373661
has answer: http://stackoverflow.com/a/49245482
has body: So, StackOverflow, I'm stumped. The code as I have it is a C++ function with embedded Python. I generate a message on the C++ side, send it to the python, get a different message back. I got it to work, I got it tested, so far, so good. The next step is that I need Python to generate messages on their own and send them into C++. This is where I'm starting to get stuck. After spending a few hours puzzling over the documentation, it seemed like the best way would be to define a module to hold my functions. So I wrote up the following stub: static PyMethodDef mailbox_methods[] = { { "send_external_message", [](PyObject *caller, PyObject *args) -&gt; PyObject * { classname *interface = (classname *) PyCapsule_GetPointer(PyTuple_GetItem(args, 0), "turkey"); class_field_type toReturn; toReturn = class_field_type.python2cpp(PyTuple_GetItem(args, 1)); interface -&gt;send_message(toReturn); Py_INCREF(Py_None); return Py_None; }, METH_VARARGS, "documentation" }, { NULL, NULL, 0, NULL } }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "turkey", "documentation", -1, mailbox_methods }; //defined in header file, just noting its existence here PyObject *Module; PyMODINIT_FUNC PyInit_turkey() { Module = PyModule_Create(&amp;moduledef); return Module; } And on the Python side, I had the following receiver code: import turkey I get the following response: ImportError: No module named 'turkey' Now, here's the part where I get really confused. Here's the code in my initialization function: PyInit_turkey(); PyObject *interface = PyCapsule_New(this, "instance", NULL); char *repr = PyUnicode_AsUTF8(PyObject_Repr(Module)); cout &lt;&lt; "REPR: " &lt;&lt; repr &lt;&lt; "\n"; if (PyErr_Occurred()) PyErr_Print(); It prints out REPR: &lt;module 'turkey'&gt; Traceback (most recent call last): &lt;snipped&gt; import turkey ImportError: No module named 'turkey' So the module exists, but it's not ever being passed to Python anywhere. I can't find documentation on how to pass it in…
upvote count: 2
has comment: http://stackoverflow.com/comment/85373791
has comment: http://stackoverflow.com/comment/85371831

http://stackoverflow.com/q/49248104
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49250393
tagged with: python
has title: What is `RoleEnvironment.GetLocalResource` equivalent for python on Azure CloudService?
has body: I'm running a python website, and want to use the LocalStorage on the WebRole of Azure CloudService. And I can't get the path of the storage but using RoleEnvironment.GetLocalResource(name_of_storage) in C#. So what is the equivalent version of RoleEnvironment.GetLocalResource in Python?
tagged with: azure-cloud-services
tagged with: azure
score: 1
answer count: 1
tagged with: azure-web-roles
downvote count: 0
upvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/85355729
comment on: http://stackoverflow.com/q/49175185
has text: You should define the filename (where to store the page pointed by the URL). Python doen't modify function arguments.It is your task to find a valid filename, so that your operating system can create such file. Special characters are fine, if they are not `/` or `\` or `:` or `\0`, according various operating systems.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49244267
tagged with: pandas
score: 0
tagged with: string
accepted answer: http://stackoverflow.com/a/49244417
type: Question
has answer: http://stackoverflow.com/a/49244417
tagged with: find
answer count: 1
has body: I have a pandas data frame. Below is a sample table. Event Text A something/AWAIT TO SHIP hello B 13579 C AWAITING SHIP D 24613 E nan I want to only keep rows that contain the words "AWAIT TO SHIP" in the Text column or contains the string 13579 or 24613 in Text column. Below is my desired table: Event Text A something/AWAIT TO SHIP hello B 13579 D 24613 Below is the code I tried: df_STH001_2 = df_STH001[df_STH001['Text'].str.contains("AWAIT TO SHIP") == True | df_STH001['Text'].str.contains("13579") == True | df_STH001['Text'].str.contains("24613") == True] Below is the error I get: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
tagged with: python
has title: Pandas Dataframe Keep Row If Column Contains Any Designated Partial String
type: AnsweredQuestion
tagged with: conditional-statements

http://stackoverflow.com/comment/85438546
comment on: http://stackoverflow.com/q/49217244
type: QuestionComment
has text: you can show me demo please?
type: Comment
score: 0

http://stackoverflow.com/q/49234814
score: -5
answer count: 1
has title: function not defined when called
favorite count: 0
has body: i have a function that returns a list which i would like to use within another function, when i call the function it says that it is not defined, is there something wrong with my code or method of calling? this is function i am returning a list from. def KingMoves(self, rows, columns): FinalMove = [] FinalMove.append(((rows - 1),(columns))) # (left 1) FinalMove.append(((rows + 1),(columns))) # (right 1) FinalMove.append(((columns + 1),(rows))) # (up 1) FinalMove.append(((row + 1),(columns + 1))) # (right 1) (up 1) -- Diagonals for king only FinalMove.append(((row - 1),(columns + 1))) # (left 1)(up 1) FinalMove.append(((row + 1),(columns - 1))) # (right 1)(down 1) FinalMove.append(((row - 1),(columns - 1))) # (left 1)(down 1) return FinalMove; this is where i attempt to use the list returned list. def UserInput(self): global AllPieces TheKingMoves = KingMoves() OnGoing = True this is the error i am receiving: NameError: name 'KingMoves' is not defined i have tried to pass the Kingmoves paramenters but get the same result
type: Question
has comment: http://stackoverflow.com/comment/85472729
has answer: http://stackoverflow.com/a/49234922
downvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/85472749
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85472854
tagged with: list
accepted answer: http://stackoverflow.com/a/49234922
upvote count: 0

http://stackoverflow.com/comment/85461302
has text: In my source code i've imported Coverage as a module ('from coverage import Coverage') and at the end of the code i've used if __name__ == "__main__": cov = Coverage() cov.start() main() cov.stop() cov.html_report(directory="coverage-html"). Well, in my test_connectors.py i use coverage like this: coverage run --source=dir my_program.py
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49194557

http://stackoverflow.com/comment/85275020
comment on: http://stackoverflow.com/q/49132981
has text: I was going to post an answer very similar to the one @sadmicrowave did. =)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49156092
upvote count: 2
has comment: http://stackoverflow.com/comment/85317736
has body: I just learn it recently reorder_levels :-) pd.concat([x,y],keys=['x','y'],axis=1).reorder_levels([1,0],axis=1).sort_index(axis=1) Out[449]: A B x y x y 0 A0 A2 B0 B2 1 A1 A3 B1 B3
answers question: http://stackoverflow.com/q/49155844
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/85317873
downvote count: 0

http://stackoverflow.com/q/49202368
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49202385
score: 1
answer count: 1
upvote count: 1
has title: import numpy array wrapper
favorite count: 0
type: Question
tagged with: numpy
tagged with: arrays
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85410370
accepted answer: http://stackoverflow.com/a/49202385
has body: I have following code: x = array([-273.0, -176.4, -79.8, 16.9, 113.5, 210.1, 306.8, 403.4, 500.0]) y = array([2.25927498e-53, 2.56028619e-03, 8.64512988e-01, 6.27456769e+00, 1.73894734e+01, 3.29052124e+01, 5.14612316e+01, 7.20531200e+01, 9.40718450e+01]) but array() is not recognized by the IDE, so I figure the code is using some sorta method to wrap numpy.array. So I added import numpy.array as array on the top, and the IDE is no longer complaining about using array(). However, when I run this code, I got ModuleNotFoundError: No module named 'numpy.array' So how do I use array() like a buildin function?

http://stackoverflow.com/q/49257274
has comment: http://stackoverflow.com/comment/85517771
has title: Python FOR loops with dictionaries
tagged with: python
has answer: http://stackoverflow.com/a/49257621
has comment: http://stackoverflow.com/comment/85517810
upvote count: 0
downvote count: 2
has comment: http://stackoverflow.com/comment/85517631
answer count: 1
accepted answer: http://stackoverflow.com/a/49257621
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85517969
has body: I'm doing a small program that has the job of a school's subjects and marks management. HOW IT WORKS I've created 4 variables: a dictionary, an initialized empty string(for subjects) and two initialized empty integers(one for the marks, the other one for the subjects number). The program asks the user to input the numbers of subjects to work with. After that, it enters in a for loop that repeats itself in the range of the subjects number. And it works fine. Now the problem comes when the user inputs a mark over the range specified. Let's suppose we have a school and the marks we can input are between 1 and 10. The user can't write 11,12 and so on.. CODE pagella = {} materia = "" voti = 0 length = 0 print("Insert the number of subjects, the subjects and the marks-") num = int(input("Number of subjects: ")) length = len(pagella) length = num for i in range(length): materia = input("Subject: ") voto = eval(input("Mark: ")) if(voto &gt; 10): print("Number between 1 and 10") else: pagella[materia] = voto print(pagella) As you can see, there's the for loop that asks the user to input the subjects and the marks in the range of num(the number of subjects). If I try to input 12 on a mark, the program tells me to input a mark between 1 and 10 so it repeat again the cycle from the beginning. But the problem is that in this case, if I want to have 3 subjects with 3 marks (that means 3 iterations), one is lost because of the wrong mark, so I will not have 3 subjects and marks to input correctly, but only 2. I hope I've explained correctly everything and someone can help me! Thanks in advice
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/23294658
score: -2

http://stackoverflow.com/q/49244795
score: 2
type: AnsweredQuestion
has body: I created an Anaconda Python Conda environment and exported a spec file so I could re-install the exact same environment at a later date if necessary using the command conda list --explicit. That day is today, but I'm disappointed to see that one of the files isn't available and was replaced with a newer version: https://conda.anaconda.org/conda-forge/win-64/gdal-2.1.3-np111py35_vc14_0.tar.bz2 https://conda.anaconda.org/conda-forge/win-64/gdal-2.1.3-np111py35_vc14_7.tar.bz2 Conda encounters an error because the link is broken and then it retries unsuccessfully several times: CondaError: CondaHTTPError: HTTP 404 NOT FOUND for url &lt;https://conda.anaconda.org/conda-forge/win-64/gdal-2.1.3-np111py35_vc14_0.tar.bz2 Elapsed: 00:01.270000 CF-RAY: 3fa8f7eb093298a1-LAX An HTTP error occurred when trying to retrieve this URL. HTTPerrors are often intermittent, and a simple retry will get you on your way. Four-part question: Are spec files intended only for very short term usage? Should I be archiving each .bz2 file independently to be able to recreate the environment later? Is there a tool available to help me do this, or should I look through the folders and manually find what I need and copy it and conda install each one? Is there a better way to check the validity of all the links of a spec file other than attempting to install it and watching it crash? It looks like conda will check to see if it has already downloaded the same file in another environment and won't attempt another download and the broken link could be hidden.
has title: Create from file gives CondaHTTPError: HTTP 404 NOT FOUND
possible better answer: http://stackoverflow.com/a/66898812
favorite count: 0
accepted answer: http://stackoverflow.com/a/49253441
has answer: http://stackoverflow.com/a/66898812
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49253441
answer count: 2
downvote count: 0
tagged with: python
tagged with: conda
tagged with: anaconda

http://stackoverflow.com/q/49165318
has comment: http://stackoverflow.com/comment/85335935
has title: BeautifulSoup - extracting texts within one class
possible better answer: http://stackoverflow.com/a/49165401
has answer: http://stackoverflow.com/a/49165401
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85335991
answer count: 2
has body: I'm trying to extract texts from this webpage below: &lt;div class="MYCLASS"&gt;Category1: &lt;a id=category1 href="SomeURL" &gt; Text1 I want&lt;/a&gt; &amp;gt; Category2: &lt;a href="SomeURL" &gt;Text2 I want&lt;/a&gt;&lt;/div&gt; I tried: for div in soup.find_all('div', class_='MYCLASS'): for url in soup.find_all('a', id='category1'): print(url) And it returned: &lt;a href="someURL" id="category1"&gt;Text1 I want&lt;/a&gt; So I split the text... for div in soup.find_all('div', class_='MYCLASS'): for url in soup.find_all('a', id='category1'): category1 = str(url).split('category1"&gt;')[1].split('&lt;/a&gt;')[0] print(category1) and extracted "Text1 I want", but still miss "Text2 I want". Any idea? Thank you. EDIT: There are other &lt; a> &lt; /a> in the source code, so if I remove id= from my code, it would return all other texts that I don't need. For examples, &lt;div class="MYClass"&gt;&lt;span class="Class"&gt;RandomText.&lt;br&gt;RandomText.&lt;br&gt; &lt;a href=someURL&gt;RandomTextExtracted.&lt;/a&gt;&lt;br&gt; Also, &lt;/div&gt;&lt;div class=MYClass&gt; &lt;a href="SomeURL&gt;RandomTextExtracted&lt;/a&gt;
has comment: http://stackoverflow.com/comment/85336247
has answer: http://stackoverflow.com/a/49166198
accepted answer: http://stackoverflow.com/a/49166198
tagged with: web-scraping
tagged with: beautifulsoup
type: Question
has comment: http://stackoverflow.com/comment/85336826
tagged with: python

http://stackoverflow.com/comment/85291583
has text: Also jus read from RF doc {For example, Python tuple and list with same content are considered equal.} not sure why "Lists Should Be Equal" Keyword failing
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49136800
score: 0

http://stackoverflow.com/a/49220465
type: AcceptedAnswer
downvote count: 0
upvote count: 7
has body: I discovered what what causing this behaviour. I ran my notebook with the following: from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" (documented here) This had the effect of not suppressing matplotlib output when plotting in a loop. However, as mentioned in the original post, it did suppress output as expected when not within a loop. In any case, I fixed the issue by 'undoing' my code above like this: InteractiveShell.ast_node_interactivity = "last_expr" I'm not sure why this would happen.
type: Answer
has comment: http://stackoverflow.com/comment/137067134
answers question: http://stackoverflow.com/q/49218457
accepted answer of: http://stackoverflow.com/q/49218457
score: 7

http://stackoverflow.com/comment/85334346
type: QuestionComment
comment on: http://stackoverflow.com/q/49164393
score: 0
has text: [Python debugging tips](https://stackoverflow.com/questions/1623039/python-debugging-tips). Well, the debugger can tell you that.
type: Comment

http://stackoverflow.com/a/49243713
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49242405
downvote count: 1
answers question: http://stackoverflow.com/q/49242405
type: Answer
upvote count: 2
score: 1
has body: Okay, let's see: Documentation is your best friend. This is especially true in case of Django which has great documentation. Generally, there are three ways to use authentication in Django: Default User class (django.contrib.auth.user.models) just works out of the box. You can extend it by creating other model (like Profile) and linking it via OneToOneField. Alternatively, you can provide your own User class via subclassing (usually AbstractBaseUser) and registering it in Django's settings. Finally, you can write completely custom backend. For customization guide consult this article. For the first part of the question see paragraph above. Regarding removing user groups: its probably possible (though I've never tried it), but I don't see much point. It has practically no overhead whatsoever while providing some useful stuff like staff/admin groups for Django's admin panel. Absolutely there is a generic solution. Just use generic API views. Again, I'm linking documentation. In short, you want to use subclasses of GenericAPIView class. For instance, let's say to want to list User objects under /users/ path: url(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list') For your particular example you would use RetrieveAPIView. If you want to look it up with pk you don't even have to configure it.

concatenation
tags question: http://stackoverflow.com/q/49201814
tags question: http://stackoverflow.com/q/49277682
tags question: http://stackoverflow.com/q/49275996
tags question: http://stackoverflow.com/q/49129473
tags question: http://stackoverflow.com/q/49137151
tags question: http://stackoverflow.com/q/49256063
tags question: http://stackoverflow.com/q/49208737
tags question: http://stackoverflow.com/q/49279343
tags question: http://stackoverflow.com/q/49163590
type: Tag
tag name: concatenation

http://stackoverflow.com/q/49122653
has comment: http://stackoverflow.com/comment/85251162
type: Question
type: UnansweredQuestion
tagged with: python
score: 0
answer count: 0
has body: I have a python module to perform matrix operations and want to code it in C as a C python module using the Python/C api. I am using a class called Matrix, and I want to continue to use the class model. I can initialize the class, but cannot figure out how to use instance variables like I would in python self.var. I have tried looking at documentation and tried looking for examples, but I cannot find anything to help. matrix.c struct matrixStruct { int rows; int cols; float **matrix; }; static PyObject * Matrix_init(PyObject *self, PyObject *args) { int cols, rows; PyObject *selfv; struct matrixStruct m; Py_INCREF(Py_None); // __init__ takes two args, rows, cols if (!PyArg_ParseTuple(args,"Oii",&amp;selfv,&amp;rows,&amp;cols)){ perror("ParseTuples"); return NULL; } m.rows = rows; m.cols = cols; // Create the matrix m.matrix = malloc(m.rows*sizeof(float *)); if (m.matrix == NULL) { return NULL; } for (int i = 0; i &lt; m.rows; i++) { m.matrix[i] = malloc(m.cols*sizeof(float)); if (m.matrix[i] == NULL) { return NULL; } } //init the matrix with all 0 for (int i = 0; i &lt; m.rows; i++) { for (int j = 0; j &lt; m.cols; j++) { m.matrix[i][j] = 0; } } return Py_None; } static PyMethodDef ModuleMethods[] = { {0, 0} }; PyMODINIT_FUNC initMatrix(void) { PyMethodDef *def; PyObject *module = Py_InitModule("Matrix", ModuleMethods); PyObject *moduleDict = PyModule_GetDict(module); PyObject *classDict = PyDict_New( ); PyObject *className = PyString_FromString("Matrix"); PyObject *matrixClass = PyClass_New(NULL, classDict, className); PyDict_SetItemString(moduleDict, "Matrix", matrixClass); Py_DECREF(classDict); Py_DECREF(className); Py_DECREF(matrixClass); for (def = MatrixMethods; def-&gt;ml_name != NULL; def++) { PyObject *func = PyCFunction_New(def, NULL); PyObject *method = PyMethod_New(func, NULL, matrixClass); PyDict_SetItemString(classDict, def-&gt;ml_name, method); Py_DECREF(func); Py_DECREF(method); } }
has comment: http://stackoverflow.com/comment/85250749
has title: Class Instance variables in C extended python

http://stackoverflow.com/comment/85364067
type: QuestionComment
comment on: http://stackoverflow.com/q/49179203
has text: Can you provide a complete example (https://stackoverflow.com/help/mcve)? When I try the obvious to extend this out into something that works, what I get back is a `bytes` object, not a buffer object. And besides, whichever one you get back has the same bytes you put into the `Binary`, so… what's the problem in the first place?
score: 1
type: Comment

http://stackoverflow.com/a/49228851
answers question: http://stackoverflow.com/q/49204280
has comment: http://stackoverflow.com/comment/85878213
has comment: http://stackoverflow.com/comment/85878487
has comment: http://stackoverflow.com/comment/128793002
type: Answer
has body: Begin with some color. Perhaps iterate through all the different colors in the mask. colors = np.unique(source_mask.reshape(-1, 3), axis=0) for color in colors: Create copies: s = source_img.copy() t = target_img.copy() Make everything except the selected region "transparent": s[source_mask != color] = -1 t[target_mask != color] = -1 Throw that into your transfer function: transfer_img = transfer(s, t) Take the output of your transfer function and overlay it onto your source image: mask = transfer_image != -1 source_img[mask] = transfer_img[mask]
has comment: http://stackoverflow.com/comment/128784311
score: 0

http://stackoverflow.com/q/49134213
type: Question
has body: i have a sample csv file with me which contains some random numbers which are not sorted. i want to sort the data from the csv file and i have to write the sorted data into a new csv file. the problem is if i have a data like 3, 65, 20, 21, 19, 34, 8, 0, 22 python is sorting based on the first digit only. if i print out the sorted data, i'm getting the below as output. ['0'], ['19'], ['20'], ['21'], ['22'], ['3'], ['34'], ['65'], ['8'] which is the sorting is performing based on the first digit. and i want to write the sorted data to a new csv file. thanks in advance.
has answer: http://stackoverflow.com/a/49134498
has title: How to sort a csv file using python and write the sorted data to the new csv file
tagged with: python
tagged with: sorting
accepted answer: http://stackoverflow.com/a/49145483
has comment: http://stackoverflow.com/comment/85293810
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49145483
score: 0
possible better answer: http://stackoverflow.com/a/49134288
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/49134288
has comment: http://stackoverflow.com/comment/85273093

http://stackoverflow.com/comment/85489131
type: Comment
score: 0
type: QuestionComment
has text: @QnARails, @ NightFury got the idea! thanks
comment on: http://stackoverflow.com/q/49241719

http://stackoverflow.com/comment/85515632
comment on: http://stackoverflow.com/q/49256063
score: 0
type: Comment
type: QuestionComment
has text: @Aran-Fey : the idea was to first divide the number by 2 and then take the residual from that (0 or 1) and use this to build the concatenated string.

http://stackoverflow.com/comment/107516317
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49259085
type: Comment
has text: can I write x (the data) as an argument to the function that calculates likelihood?

http://stackoverflow.com/comment/85545735
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49270937
has text: @CoXier: Did you try putting `# -*- coding: utf-8 -*-` at the top?
type: Comment

http://stackoverflow.com/comment/85328011
type: AnswerComment
score: 0
has text: @LAS Updated to return all strings as list - they do not have \n at end, you you need to add that or print the strings separately
comment on: http://stackoverflow.com/a/49159309
type: Comment

http://stackoverflow.com/comment/88324246
comment on: http://stackoverflow.com/a/49129883
type: Comment
score: 2
type: AnswerComment
has text: I think you mean [Process **Monitor**](https://learn.microsoft.com/en-us/sysinternals/downloads/procmon) (not Process Explorer--I don't know where it has file handle logging). I had a similar situation where certain modules wouldn't import with "access denied" errors, and Qt apps (e.g. spyder) wouldn't open. It turned out QtCore5.dll and certain modules' \_\_config\_\_.py didn't have the read/read+execute permissions for regular users.

http://stackoverflow.com/comment/85263645
type: Comment
has text: I did it with a new user x...
type: QuestionComment
comment on: http://stackoverflow.com/q/49128817
score: 0

http://stackoverflow.com/q/49137632
downvote count: 0
has title: Pandas Dataframe - Adding new row based on variables
favorite count: 0
score: 2
type: AnsweredQuestion
tagged with: pandas
possible better answer: http://stackoverflow.com/a/49137710
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49137665
has body: I have a program that sorts through a large series of data and pulls a bunch of necessary values and saves them as numbers or strings. How do I then place those values into a new dataframe? For instance: labels = ['A', 'B', 'C', 'D'] df = pd.DataFrame(columns=labels) Now I want to add variables x, y, Z and the text "banana" to the DataFrame into A, B, C and D respectively. Is there a line of code using an append-like method or something similar that will do this quickly and efficiently? (My actual dataframe will have a multitude of columns, so a quick script is much more useful than creating an empty dataframe and changing each cell value.)
has answer: http://stackoverflow.com/a/49137710
type: Question
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49137665

http://stackoverflow.com/a/49155387
has comment: http://stackoverflow.com/comment/85321136
downvote count: 1
has comment: http://stackoverflow.com/comment/85327359
has body: I think PEP8 covers this here: In particular: do not break backwards compatibility just to comply with this PEP! And here is an example from another question where from tkinter import * is considered ok by the Python developers even though it violates PEP 8 advice.
type: Answer
answers question: http://stackoverflow.com/q/49155330
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/85315996
has comment: http://stackoverflow.com/comment/85327083

http://stackoverflow.com/a/49251575
answers question: http://stackoverflow.com/q/49208326
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/85517084
type: AcceptedAnswer
has body: What I don't understand is why only some weights have been modified by the training function since I'm feeding it with a loss that is just one number. So in my opinion, all the weights must be modified in the same way. This is not completely true. Consider the linear activation in the case of a single training sample: Z = W*X + b #(tf.matmul(input,syn0) + b1 Here you are performing the dot product between W and X. basically, you're doing: Z = sum(W[j] * X[j]) + b oss: the matmul works because your weights are row-vector and features are column-vector. After that, you apply the non linear activation function, namely the softmax function. This will give you prediction that you'll use to compute the loss, which is, you said, a scalar. Now, when performing the backpropagation step, TF will compute the derivative of the loss with respect to each of the component of W. Explicitely: dW[j] = dL/dZ * dZ/dW[j] where: dL/dZ is the derivative of the loss wrt to Z dZ/dW[j] is the derivative of Z wrt to W The previous formula comes up from the chain rule. It turns out that: dZ/dW[j] = x[j] That's why you end up with different values for each component. For further analysis, see this question. Basically, initializing all the weights of all the neurons to 0, makes your net redundant since all neurons will have the same values for W. However, in each neuron, the component of W will be different.
accepted answer of: http://stackoverflow.com/q/49208326

http://stackoverflow.com/comment/85542240
type: QuestionComment
has text: The second one isn't a sorted dictionary, it's just a sorted list of pairs (tuples). (But it is pretty handy if you ever _need_ a sorted dictionary—you can just do `collections.OrderedDict(sorted(aa.items()))`.)
comment on: http://stackoverflow.com/q/49269299
score: 0
type: Comment

http://stackoverflow.com/q/49201431
favorite count: 0
has comment: http://stackoverflow.com/comment/85410605
type: Question
has comment: http://stackoverflow.com/comment/85407997
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85408501
has body: I have a different shape of 3D matrices. Such as: Matrix shape = [5,10,2048] Matrix shape = [5,6,2048] Matrix shape = [5,1,2048] and so on.... I would like to put them into big matrix, but I am normally getting a shape error (since they have different shape) when I am trying to use numpy.asarray(list_of_matrix) function. What would be your recommendation to handle such a case? My implementation was like the following: matrices = [] matrices.append(mat1) matrices.append(mat2) matrices.append(mat3) result_matrix = numpy.asarray(matrices) and having shape error!! UPDATE I am willing to have a result matrix that is 4D. Thank you.
has comment: http://stackoverflow.com/comment/85408015
has answer: http://stackoverflow.com/a/49201602
has comment: http://stackoverflow.com/comment/85411130
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85411776
has title: how to convert list of different shape of arrays to numpy array in Python
has comment: http://stackoverflow.com/comment/85411454
score: 2
tagged with: numpy
has comment: http://stackoverflow.com/comment/85408431
upvote count: 2
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85408002

http://stackoverflow.com/q/49262427
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49262921
accepted answer: http://stackoverflow.com/a/49262921
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49262831
has answer: http://stackoverflow.com/a/49262831
has title: Logic to check if a query set exists on a None type?
tagged with: python
type: AnsweredQuestion
has body: I'm showing my example below with 2 groups when there are over 20 groups in the code. I'm not sure if there is a better way to go about this if there is please offer a suggestion. Below I'm checking if the student has 'All Groups' for their student group if they do I want to the groups as None. This part is working fine, same with the else. allgroups = 'All Groups' # if user has all groups then no group will show if allgroups in studentgroup: bhstudentgrouplist = None abstudentgrouplist = None else: bhstudentgrouplist = Groups.objects.filter(~Q(group_id__in= groupIds)).filter(group_id = 2000) abstudentgrouplist = Groups.objects.filter(~Q(group_id__in= groupIds)).filter(group_id = 5000) What's occuring is if user has every item possible in the group they should be flagged as None so they wont' display in my template. In order to do this, I tried the following: 1. if not bhstudentgrouplist.exists(): bhstudentgrouplist = None if not abstudentgrouplist.exists(): abstudentgrouplist = None 2. if bhstudentgrouplist.count() &lt; 1: bhstudentgrouplist = None if not abstudentgrouplist.count() &lt; 1: abstudentgrouplist = None 3. if bhstudentgrouplist.isnull(): bhstudentgrouplist = None if not abstudentgrouplist.isnull(): abstudentgrouplist = None This works for the instances except when a student has All Groups, I get the error can not use the function isnull(), count(), exists() on a None type. How can I go about fixing when the group falls in All Groups and the student has already has all reports in the studentgroup so it needs to be set to None? If there is a better way to go about this entire process please guide me in that direction. The process is checking if a student has All Groups if they don't it will provide the list of available reports. Sometimes the user already has all the available reports in these instances the report group should be set to none, so it doesn't return available reports.
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/85539127
type: Comment
has text: This is a very odd way to store datetimes… but it can be parsed, either by doing some equally odd math, or by just converting to a string, removing the extraneous characters, and using the code from one of the other answers you've seen.
type: QuestionComment
comment on: http://stackoverflow.com/q/49267837
score: 0

http://stackoverflow.com/a/49268656
answers question: http://stackoverflow.com/q/49268606
type: Answer
has body: os.listdir(photoPath) will return you a list of photos already, so if you want to randomly pick one, use random.choice(os.listdir(photoPath)). From your code, the photos is merely the name of that photo, not the whole list of photos.
has comment: http://stackoverflow.com/comment/85540709
score: 0

http://stackoverflow.com/q/49272206
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49272838
tagged with: regex
score: 0
has answer: http://stackoverflow.com/a/49272813
answer count: 2
linked to: http://stackoverflow.com/q/2903309
has title: Split out multiline log entries with python regular expressions
tagged with: multiline
has body: I need to create a regular expression in python that can take the following sample and split out each log entry. I'm using the date as a way to identify the beginning of each log entry but it is only able to get a single line from where the date starts to the end of the first line. It completely misses all of the stack trace stuff. I want all of the log entry because there is a lot of repeated logging and I want to be able to filter out repeats and just reduce it down to a handful of unique log entries. I would also want to be able to remove anything unique about the string like date timestamp once I've identified a log entry so that a comparison function could flag it as a duplicate. I've tried to use positive lookaheads and multiline flags but to no avail. Anyone know what I am trying to do? Some regular expressions I've tried ^\d{4}-\d{2}-\d{2}.*\(.*\)$ // it matches single line date to parenthesis ^(\d{4}-\d{2}-\d{2}|\s|).*\)$ // matches single line with tabs - not much better ^\d{4}-\d{2}-\d{2}.*(?=\d{4}-\d{2}-\d{2}) // positive lookahead but barely works Sample string: 2018-03-06 11:36:40:048 INFO:Starting. (com.X.s.f.o.o) 2018-03-06 11:36:42:931 SEVERE: Error attempting to s: StatusRuntimeException (com.Y.W.Z_H.ZHGC.sHToVe) io.G.StatusRuntimeException: EXCEEDED at io.G.stub.CCalls.toStatusRuntimeException(CCalls.java:227) at io.G.stub.CCalls.getUnchecked(CCalls.java:208) at io.G.stub.CCalls.blockingUnaryCall(CCalls.java:141) 2018-03-06 11:36:46:159 SEVERE: Error attempt: StatusRuntimeException (com.Y.W.Z_H.ZHGC.sHToVe) io.G.StatusRuntimeException: EXCEEDED at io.G.stub.CCalls.toStatusRuntimeException(CCalls.java:227) at io.G.stub.CCalls.getUnchecked(CCalls.java:208) at io.G.stub.CCalls.blockingUnaryCall(CCalls.java:141) 2018-03-06 11:36:46:824 SEVERE: getConfigInteger(): eGSWindowsPortNumber (com.Y.W.Y_Z_config_s.YZConfigs.getInteger) 2018-03-06 11:36:46:844 SEVERE: Failed to get (com.Y.W.Z_H.ZHGC.create) Desired output: Match 1: INFO:Starting. (com.X.s.f.o.o…
tagged with: logging
type: Question
linked to: http://stackoverflow.com/q/231767

http://stackoverflow.com/a/49172206
type: Answer
accepted answer of: http://stackoverflow.com/q/49171370
has body: To search the element with text as Fastener you can use either of the following options : Through Fastener : br.find_element_by_link_text("Fastener").click() Using onclick through fastener (xpath): br.find_element_by_xpath("//a[contains(@onclick,'fastener')]").click() Using onclick through fastener (css_selector): br.find_element_by_css_selector("a[onclick^='fastener']").click()
answers question: http://stackoverflow.com/q/49171370
score: 5
type: AcceptedAnswer
downvote count: 0
upvote count: 5

http://stackoverflow.com/comment/85415570
has text: Dont we have to use algorithm like Naive Bayes??.I just started with NLP..
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49197712

http://stackoverflow.com/comment/85510911
has text: What kind of Authentication are you using Session or Token?
comment on: http://stackoverflow.com/q/49208083
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/a/49257092
type: AcceptedAnswer
has body: I got the answer: import pandas as pd # Reading datasets/coinmarketcap_06122017.csv into pandas dec6 = pd.read_csv('datasets/coinmarketcap_06122017.csv') # Selecting the 'id' and the 'market_cap_usd' columns market_cap_raw = dec6'id','market_cap_usd' cap = market_cap_raw.query('market_cap_usd &gt; 0') #Declaring these now for later use in the plots TOP_CAP_TITLE = 'Top 10 market capitalization' TOP_CAP_YLABEL = '% of total cap' # Selecting the first 10 rows and setting the index cap10 = cap.head(10).set_index('id') # Calculating market_cap_perc cap10 = cap10.assign(market_cap_perc = lambda x: (x.market_cap_usd/cap.market_cap_usd.sum())*100) # Plotting the barplot with the title defined above ax = cap10.market_cap_perc.head(10).plot.bar(title=TOP_CAP_TITLE) # Annotating the y axis with the label defined above ax.set_ylabel(TOP_CAP_YLABEL)
type: Answer
answers question: http://stackoverflow.com/q/49211924
accepted answer of: http://stackoverflow.com/q/49211924
score: 0

http://stackoverflow.com/comment/85498792
type: AnswerComment
comment on: http://stackoverflow.com/a/49247447
has text: `for val in x[1:]:` is the same as `for val in x[1:len(x)]:`
score: 1
type: Comment

http://stackoverflow.com/q/49136804
has answer: http://stackoverflow.com/a/49146917
has comment: http://stackoverflow.com/comment/85298332
has title: Disabling logs when running Scrapy as script
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85278591
has comment: http://stackoverflow.com/comment/85299790
tagged with: python
has comment: http://stackoverflow.com/comment/85279647
has body: I'm using Scrapy in a script of mine as describe in the Common Practices on the docs I need to disable the Scrapy logs completely (not change verbosity). I tried this: Spider.custom_settings['LOG_ENABLED'] = False and this: configure_logging({'LOG_ENABLED': False}) In both cases, Scrapy is still logging everything. How do you completely disable Scapy logs when running Scrapy in a script (note that I have my own logger that I want to keep, it's just Scrapy logs that I want to remove).
favorite count: 0
type: Question
tagged with: python-3.x
downvote count: 0
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85284409
has comment: http://stackoverflow.com/comment/85294124
tagged with: scrapy

http://stackoverflow.com/q/49216095
type: Question
tagged with: recursion
possible better answer: http://stackoverflow.com/a/49216226
has answer: http://stackoverflow.com/a/49216226
has comment: http://stackoverflow.com/comment/85436420
has comment: http://stackoverflow.com/comment/85436559
tagged with: python
accepted answer: http://stackoverflow.com/a/49216285
has answer: http://stackoverflow.com/a/49216285
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49216300
answer count: 3
tagged with: function
has body: I have been looking at the solution for this problem (below) for hours and cannot figure out how the recursion works. Can someone please explain in basic terms how it works. Since group is appended and then popped, isn't the popped list going to just always be equal to nothing []? # Given a list of ints, is it possible to choose a group of some of the # ints, such that the group sums to the given target? # 0, 2, 4, 8, 10 -&gt; True # 0, 2, 4, 8, 14 -&gt; True # 0, 2, 4, 8, 9 -&gt; False def sum_checker(ints, total, group, index): if sum(group) &gt; total: # backtracking return False if index == len(ints): # BASE CASE return sum(group) == total group.append(ints[index]) if sum_checker(ints, total, group, index + 1): return True group.pop() return sum_checker(ints, total, group, index + 1) ints = [int(input()) for i in range(int(input()))] total = int(input()) group = [] print(sum_checker(ints, total, group, 0))
has title: Cannot understand recursive function Python

http://stackoverflow.com/a/72959182
score: 4
upvote count: 4
downvote count: 0
has body: I have an easy solution. No need to sort. def solution(A): s = set(A) m = max(A) + 2 for N in range(1, m): if N not in s: return N return 1 Note: It is 100% total score (Correctness &amp; Performance)
type: Answer
answers question: http://stackoverflow.com/q/49224022

http://stackoverflow.com/comment/85550336
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49198620
has text: hi, the different number of rows can info https://stackoverflow.com/questions/49193614/pyspark-count-different-numbers-for-the-same-dataframe. Besides, your function is right
type: Comment

http://stackoverflow.com/comment/85515769
score: 0
comment on: http://stackoverflow.com/a/49248790
type: Comment
has text: And of course, `isinstance(Iterable, type)` returns True - hence "plain incorrect" as it is.
type: AnswerComment

http://stackoverflow.com/comment/85282725
has text: You must be brave to use pandas with 42 million rows...
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49138499
score: 0

http://stackoverflow.com/a/49277927
type: Answer
has comment: http://stackoverflow.com/comment/85558703
has comment: http://stackoverflow.com/comment/85558600
has body: Referencing index is a requirement (unless you use next()^), since a pd.Series is not guaranteed to have one value. You can use pd.Series.values to extract the values as an array. This also works if you have multiple matches: res = df.loc[df['Fruit'] == 'blueberry', 'Code'].values # array([5], dtype=int64) df2 = pd.concat([df]*5) res = df2.loc[df2['Fruit'] == 'blueberry', 'Code'].values # array([5, 5, 5, 5, 5], dtype=int64) To get a list from the numpy array, you can use .tolist(): res = df.loc[df['Fruit'] == 'blueberry', 'Code'].values.tolist() Both the array and the list versions can be indexed intuitively, e.g. res[0] for the first item. ^ If you are really opposed to using index, you can use next() to iterate: next(iter(res))
answers question: http://stackoverflow.com/q/49277640
downvote count: 0
has comment: http://stackoverflow.com/comment/85558568
score: 3
upvote count: 3

http://stackoverflow.com/comment/110826815
has text: short note: for python 3.8 add `gdal301` as the lib_names.
type: Comment
comment on: http://stackoverflow.com/a/61979107
type: AnswerComment
score: 2

http://stackoverflow.com/q/49128255
has comment: http://stackoverflow.com/comment/85263663
has comment: http://stackoverflow.com/comment/85261168
has title: How to store properly huge amount of data in an ordered way?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49129369
tagged with: database
tagged with: python
has comment: http://stackoverflow.com/comment/85264146
type: Question
has comment: http://stackoverflow.com/comment/85265575
has comment: http://stackoverflow.com/comment/85261649
score: 0
accepted answer: http://stackoverflow.com/a/49129369
tagged with: pandas
answer count: 1
has body: I have a huge amount of data that I need to organize. I think one of the good solutions might be to use a pandas DF and then to pickle the DF to save it. Only problem, I still don't understand how pandas works, and I don't know what approach should be considered in regard of my data. Data: list of the form ((int, int), float, float) but the first tuple of integer can be of different size. Example 1: [((78, 104), 1.55, 0.25), ((78, 104), 1.56, 0.25), ((78, 104), 1.57, 0.25), ((78, 104), 1.58, 0.25), ((75, 100), 5.02, 0.25), ((75, 100), 5.03, 0.25), ((75, 100), 5.04, 0.25), ((75, 100), 5.05, 0.25), ((78, 104), 1.25, 0.333), ((78, 104), 1.26, 0.333)] Example 2: [((20, 78, 104), 1.55, 0.25), ((20, 78, 104), 1.56, 0.25), ((21, 78, 104), 1.57, 0.25), ((21, 78, 104), 1.58, 0.25), ((18, 75, 100), 5.02, 0.25), ((18, 75, 100), 5.03, 0.25), ((18, 75, 100), 5.04, 0.25), ((18, 75, 100), 5.05, 0.25), ((20, 78, 104), 1.25, 0.333), ((20, 78, 104), 1.26, 0.333)] These are just extracts. At the moment I wrote the data in .txt files and then parse it back with string methods when I read a file. As you can see, the tuple can be common to a lot of value (hundreds or thousands) and have a len of 2 or more. Another way to represent this data is a dictionary of the form: Dict[tuple] = ([list of column 1], [list of column 2]): data_dict = dict() for elt in data_list: if elt[0] not in data_dict.keys(): data_dict[elt[0]] = ([elt[1]], [elt[2]]) else: data_dict[elt[0]][0].append(elt[1]) data_dict[elt[0]][1].append(elt[2]) Example 1: data_list = [((78, 104), 1.55, 0.25), ((78, 104), 1.56, 0.25), ((78, 104), 1.57, 0.25), ((78, 104), 1.58, 0.25), ((75, 100), 5.02, 0.25), ((75, 100), 5.03, 0.25), ((75, 100), 5.04, 0.25), ((75, 100), 5.05, 0.25), ((78, 104), 1.25, 0.333), ((78, 104), 1.26, 0.333)] Output: {(78, 104): ([1.55, 1.56, 1.57, 1.58, 1.25, 1.26], [0.25, 0.25, 0.25, 0.25, 0.333, 0.333]), (75, 100): ([5.02, 5.03, 5.04, 5.05], [0.25, 0.25, 0.25, 0.25])} Example 2: data_list = [((20, 78, 104), …

http://stackoverflow.com/comment/85368239
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49181127
type: Comment
has text: In my experience, `pd.concat` inside a loop can be v expensive. I think you can add your results to a list and concat the list of dataframes at the end.

http://stackoverflow.com/q/49225866
answer count: 4
possible better answer: http://stackoverflow.com/a/49225920
has comment: http://stackoverflow.com/comment/85455427
has answer: http://stackoverflow.com/a/49226171
has comment: http://stackoverflow.com/comment/85455473
has answer: http://stackoverflow.com/a/49225920
type: AnsweredQuestion
downvote count: 0
score: 1
upvote count: 1
has body: I have a code for squaring each number in a list in Python, but I have issues with it. My code doesn't give me the right answer. If I have [2,3,4,5,6,7] the answer should be [4, 9, 16, 25, 36, 49], but I get [49]. Here’s my code: numList = [2,3,4,5,6,7] def square (N): sq = N * N return (sq) def cmput_square(numList): i = 0 L = [] while i &lt; len (numList): L = [square(numList[i])] i = i + 1 return (L) n = cmput_square (numList) print ("The squares of your numbers are:", n)
accepted answer: http://stackoverflow.com/a/49225900
has comment: http://stackoverflow.com/comment/85455581
favorite count: 0
has answer: http://stackoverflow.com/a/49225900
type: Question
has title: Need help editing Python code that squares numbers in a list?
has answer: http://stackoverflow.com/a/49225928
has comment: http://stackoverflow.com/comment/85455647
tagged with: python

http://stackoverflow.com/comment/85593744
comment on: http://stackoverflow.com/q/49230981
type: QuestionComment
has text: Where did you get the .egg files from?
score: 0
type: Comment

http://stackoverflow.com/q/49134984
tagged with: file-io
has comment: http://stackoverflow.com/comment/85274757
has title: How to extract line after line till a specific keyword and then declare to a variable
answer count: 1
has body: I'm currently trying to extract some lines till i reach a keyword out of a .txt file to declare a variable with the text. Right now I have this code to get the lines I want to have: def extract_line(row): a = open("Z:/xyz/xyz/test.txt","r", encoding="utf-8") b = a.readlines() a.close() count = 0 for line in b: count += 1 if count == row: if "REQUIREMENT TYPE " in line: break else: print(line) extract_line(row + 1) which works fine for printing out the lines, but I can't extract the lines to declare a variable with the text. How do I do that?
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49135669
type: AnsweredQuestion
tagged with: cpu-word
has answer: http://stackoverflow.com/a/49135669
score: 0

http://stackoverflow.com/comment/85373069
comment on: http://stackoverflow.com/q/49183329
score: 0
type: Comment
type: QuestionComment
has text: @daKmoR added 3 examples

http://stackoverflow.com/q/49247924
tagged with: oauth-2.0
downvote count: 0
answer count: 1
has body: I have successfully authorized an API connection using "data_read" as a scope, however I am having issues passing multiple scope parameters ("data_read" and "data_write") into the OAuth2Session() function. The parameters for multiple scopes need to be passed into the URL string as https://api.website.com/oauth20/authorize?response_type=code&amp;client_id=123456&amp;redirect_uri=https...&amp;scope=data_read&amp;scope=data_write... I have tried using a comma delimited list: scope=["data_read", "data_write"] which results in: https://api.website.com/oauth20/authorize?response_type=code&amp;client_id=123456&amp;redirect_uri=https...&amp;scope=data_read+data_write I have also tried passing a list of scopes within a dictionary: dict_scope = {'scope':["data_read", "data_write"]} Which results in an error: ValueError: Invalid scope ({'scope': ['data_read', 'data_write']}), must be string, tuple, set, or list. I have reviewed requests documentation here: http://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls here: http://requests-oauthlib.readthedocs.io/en/latest/api.html#oauth-2-0-session and OAuth2 examples here: http://requests-oauthlib.readthedocs.io/en/latest/examples/examples.html#examples Any ideas or suggestions would be greatly appreciated
tagged with: python-requests
favorite count: 0
type: Question
has title: Python Requests OAuth2Session() passing multiple scope arguments
type: UnansweredQuestion
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/70755201
upvote count: 4

http://stackoverflow.com/q/49195281
type: Question
has title: numpy array processing takes more time than list processing python
linked to: http://stackoverflow.com/q/49112552
accepted answer: http://stackoverflow.com/a/49198909
tagged with: python
has comment: http://stackoverflow.com/comment/85402653
has answer: http://stackoverflow.com/a/49198909
has comment: http://stackoverflow.com/comment/85402569
tagged with: numpy
has comment: http://stackoverflow.com/comment/85403560
type: AnsweredQuestion
score: 2
linked to: http://stackoverflow.com/q/17579357
upvote count: 2
has comment: http://stackoverflow.com/comment/85418101
has comment: http://stackoverflow.com/comment/85395735
answer count: 1
downvote count: 0
has body: I am trying to compare the processing time for python list and numpy array. I know the fact that numpy arrays are faster than the python list but when I am checking practically I get lists are faster than numpy array. Here is my code : import numpy from datetime import datetime def pythonsum(n): ''' This function calculates the sum of two python list ''' a = list(range(n)) b = list(range(n)) c = [] total = 0 for i in range(len(a)): a[i] = i ** 2 b[i] = i ** 3 c.append(a[i] + b[i]) return c def numpysum(n): ''' This function calculates the sum of two numpy array ''' a = numpy.arange(n) ** 2 b = numpy.arange(n) ** 3 c = a + b return c if __name__ == "__main__": n = int(input("enter the range")) start = datetime.now() result = pythonsum(n) delta = datetime.now()-start print("time required by pythonsum is",delta.microseconds) start = datetime.now() result1 = numpysum(n) delta = datetime.now()-start print("time required by numpysum is",delta.microseconds) delta = datetime.now()-start print("time required by numpysum is",delta.microseconds) Output : In [32]: run numpy_practice.py enter the range7 time required by pythonsum is 0 time required by numpysum is 1001
has comment: http://stackoverflow.com/comment/85395455
favorite count: 0

http://stackoverflow.com/q/49213469
has comment: http://stackoverflow.com/comment/85431595
has comment: http://stackoverflow.com/comment/85431572
has comment: http://stackoverflow.com/comment/85432796
answer count: 2
has comment: http://stackoverflow.com/comment/85431627
has comment: http://stackoverflow.com/comment/85432426
has body: I have installed tensorflow (1.6.0) in Visual Studio 2017, but I get the following error when I run the code: No module named tensorflow Any help?
downvote count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/85431528
has comment: http://stackoverflow.com/comment/85432125
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85431559
type: UnansweredQuestion
has title: No module named 'tensorflow'
tagged with: python
has answer: http://stackoverflow.com/a/49221454
score: -1
has answer: http://stackoverflow.com/a/49213506

http://stackoverflow.com/q/49247106
answer count: 1
has comment: http://stackoverflow.com/comment/85498349
has title: Find largest circle that fits within a set of points given a starting point (numpy)
type: Question
type: AnsweredQuestion
tagged with: linear-algebra
score: 1
accepted answer: http://stackoverflow.com/a/49247279
has body: Given a starting point (82, 186) and a collection of surrounding points [(105, 186), (95, 157), (81, 159), (64, 173), (52, 188), (127, 195)], how can I determine the largest circle that will fit within those points? Note: The center need not be the starting point cX, cY = (82, 186) points = [(105, 186), (95, 157), (81, 159), (64, 173), (52, 188), (127, 195)] def closest_node(node, nodes): nodes = np.asarray(nodes) deltas = nodes - node dist = np.linalg.norm(deltas, axis=1) min_idx = np.argmin(dist) return nodes[min_idx], dist[min_idx], deltas[min_idx][1]/deltas[min_idx][0] # point, distance, slope (pX, pY), d, m = closest_node((cX, cY), points) cv2.circle(img, (cX, cY), int(d), (255, 0, 255), 1) # circle with center C, touching point P # learning rate a = 0.2 # sign for direction sX = 1 if cX - pX &gt; 0 else -1 sY = 1 if cY - pY &gt; 0 else -1 dx = (d * a) * np.sqrt(1 / (1 + m**2)) # New center nX = cX + sX * dx nY = cY + sY * m * dx cv2.circle(img, (int(nX), int(nY)), int(d + (d * a)), [0, 0, 0], 1) So I am trying to approach the second point iteratively (and then the third) but I think it would be better if there was a vectorized approach. How can I do this? EDIT: A solution using Voronoi from scipy.spatial import Voronoi points = np.array(points) if len(points) &gt;= 4: vor = Voronoi(points) max_d = 0 max_v = None for v in vor.vertices: cv2.circle(img, (int(v[0]), int(v[1])), 3, [200, 200, 0], 1) _, d, _ = closest_node(v, points) if d &gt; max_d: max_d = d max_v = v cv2.circle(img, (int(max_v[0]), int(max_v[1])), int(max_d), [0, 0, 0], 1)
favorite count: 0
has answer: http://stackoverflow.com/a/49247279
tagged with: numpy
tagged with: geometry
has comment: http://stackoverflow.com/comment/85498280
has comment: http://stackoverflow.com/comment/85498303
tagged with: computational-geometry
downvote count: 0
has comment: http://stackoverflow.com/comment/85498221
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85498116

http://stackoverflow.com/comment/85320426
has text: I don't think I could have asked for a more thorough and content-backed answer. Thank you!
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49150105

http://stackoverflow.com/comment/85312151
comment on: http://stackoverflow.com/a/49153775
has text: Maybe `df['consolidated_name'] = [None]*len(df)` should be omit.
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/comment/85403003
score: 0
has text: try `conda install pandas`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49198969

http://stackoverflow.com/a/63119071
downvote count: 0
answers question: http://stackoverflow.com/q/49243719
has body: Asumming you have a spark session spark_session = SparkSession \ .builder \ .enableHiveSupport() \ .getOrCreate() Spark Context can be inferred using spark_context = spark_session._sc or spark_context = spark_session.sparkContext
score: 5
upvote count: 5
type: Answer

http://stackoverflow.com/comment/85528252
comment on: http://stackoverflow.com/a/49262342
score: 0
type: AnswerComment
has text: Should be `-a[1], a[0]`? (frequency before lexicographic)
type: Comment

http://stackoverflow.com/q/49262522
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85529217
linked to: http://stackoverflow.com/q/1369526
has comment: http://stackoverflow.com/comment/85529038
type: Question
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has body: nam=input('enter file name and extention: ',) inf=open(nam,'rb') data = inf.read() J=int.from_bytes(data, byteorder='big') E=(J**int(e))%n E=int(E) np.savetxt(nam + '.enc', E) I am getting a 'IndexError: tuple index out of range' error, and to be quite frank I have no clue why. Any help would be appreciated. Thanks in advance.
has title: Getting an error when using np.savetxt to store a number

http://stackoverflow.com/q/49150726
has title: python unpack zero elements
has comment: http://stackoverflow.com/comment/85305644
score: 1
has body: please consider following code snippet: # state that items contains two or more elements x, y, *_ = items # state that items contains exactly two elements x, y, = items # state that items contains exactly one element x, = items Can I state that items contains exactly zero elements in the similar way? Thanks in advance!
possible better answer: http://stackoverflow.com/a/49150819
tagged with: python
has comment: http://stackoverflow.com/comment/85305895
has answer: http://stackoverflow.com/a/49150819
type: AnsweredQuestion
tagged with: python-3.x
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49150809
has answer: http://stackoverflow.com/a/49150809
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49270354
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85543848
tagged with: python
has comment: http://stackoverflow.com/comment/85544115
has answer: http://stackoverflow.com/a/49272033
score: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/85543889
answer count: 1
has body: I have below command output: data = """ abcd11 11 abcd12 12 abcd13 13 abcd21 14 abcd22 15 abcd23 16 abcd101 17 abcd102 18 abcd103 19 ... so on abcd501 1 abcd502 2 """ Condition1 Numbers (As per data it is string) range must be between 1 to 255, that is not exceed 255, Code: #Check abcd401, abcd402, abcd403 check = set() for line in data.split("\n"): if len(line.split()) &gt; 1: line = line.strip() check.add(line.split()[0]) if not "abcd401" in check and not "abcd402" in check and not "abcd402" in check: print "Not exist" else: print "Its already exist. Program exit" sys.exit() Now Need to assign a Number to abcd401, abcd402, abcd403 Number between 1 to 255. I can always assign abcd401 = 1, abcd402 = 2, abcd403 = 3, but i need to fill 1-255, then starts 1-255, and so on Please help.
has title: How to update string in python in existing data
type: Question

machine-learning
tags question: http://stackoverflow.com/q/49224425
type: Tag
tags question: http://stackoverflow.com/q/49242180
tags question: http://stackoverflow.com/q/49246856
tags question: http://stackoverflow.com/q/49216605
tags question: http://stackoverflow.com/q/49216223
tags question: http://stackoverflow.com/q/49134593
tags question: http://stackoverflow.com/q/49205815
tags question: http://stackoverflow.com/q/49187672
tags question: http://stackoverflow.com/q/49151825
tags question: http://stackoverflow.com/q/49206550
tags question: http://stackoverflow.com/q/49212114
tags question: http://stackoverflow.com/q/49125405
tags question: http://stackoverflow.com/q/49171094
tags question: http://stackoverflow.com/q/49227237
tags question: http://stackoverflow.com/q/49180941
tags question: http://stackoverflow.com/q/49151325
tags question: http://stackoverflow.com/q/49191497
tags question: http://stackoverflow.com/q/49260862
tags question: http://stackoverflow.com/q/49213585
tags question: http://stackoverflow.com/q/49210520
tags question: http://stackoverflow.com/q/49124814
tags question: http://stackoverflow.com/q/49212467
tags question: http://stackoverflow.com/q/49171535
tags question: http://stackoverflow.com/q/49259361
tags question: http://stackoverflow.com/q/49223358
tags question: http://stackoverflow.com/q/49212257
tags question: http://stackoverflow.com/q/49226647
tags question: http://stackoverflow.com/q/49275835
tags question: http://stackoverflow.com/q/49275570
tags question: http://stackoverflow.com/q/49240338
tags question: http://stackoverflow.com/q/49191853
tags question: http://stackoverflow.com/q/49278571
tags question: http://stackoverflow.com/q/49239478
tags question: http://stackoverflow.com/q/49248833
tags question: http://stackoverflow.com/q/49189235
tags question: http://stackoverflow.com/q/49251642
tags question: http://stackoverflow.com/q/49150309
tags question: http://stackoverflow.com/q/49262900
tags question: http://stackoverflow.com/q/49273869
tags question: http://stackoverflow.com/q/49275827
tags question: http://stackoverflow.com/q/49160206
tags question: http://stackoverflow.com/q/49163097
tags question: http://stackoverflow.com/q/49276118
tags question: http://stackoverflow.com/q/49188239
tags question: http://stackoverflow.com/q/49127258
tags question: http://stackoverflow.com/q/49124622
tags question: http://stackoverflow.com/q/49236166
tags question: http://stackoverflow.com/q/49202007
tags question: http://stackoverflow.com/q/49197016
tags question: http://stackoverflow.com/q/49160429
tags question: http://stackoverflow.com/q/49134338
tags question: http://stackoverflow.com/q/49219465
tags question: http://stackoverflow.com/q/49186525
tags question: http://stackoverflow.com/q/49236382
tags question: http://stackoverflow.com/q/49247626
tags question: http://stackoverflow.com/q/49274766
tags question: http://stackoverflow.com/q/49167961
tags question: http://stackoverflow.com/q/49266776
tags question: http://stackoverflow.com/q/49267264
tags question: http://stackoverflow.com/q/49253939
tags question: http://stackoverflow.com/q/49189648
tags question: http://stackoverflow.com/q/49226440
tags question: http://stackoverflow.com/q/49189122
tags question: http://stackoverflow.com/q/49149278
tags question: http://stackoverflow.com/q/49126929
tags question: http://stackoverflow.com/q/49131151
tags question: http://stackoverflow.com/q/49175619
tags question: http://stackoverflow.com/q/49165914
tags question: http://stackoverflow.com/q/49190334
tags question: http://stackoverflow.com/q/49145544
tags question: http://stackoverflow.com/q/49129858
tags question: http://stackoverflow.com/q/49212385
tags question: http://stackoverflow.com/q/49148447
tags question: http://stackoverflow.com/q/49178618
tags question: http://stackoverflow.com/q/49147774
tags question: http://stackoverflow.com/q/49195008
tags question: http://stackoverflow.com/q/49221826
tags question: http://stackoverflow.com/q/49263487
tag name: machine-learning

http://stackoverflow.com/a/49156257
downvote count: 0
has body: You can use re.findall() and regex -\d+. re.findall(r'-\d+', str) Output: ['-110', '-108', '-95', '-92', '-88', '-87', '-85', '-75', '-73', '-69', '-67', '-59', '-51', '-49', '-47', '-42', '-39', '-35', '-36', '-36', '-32', '-27', '-29', '-32']
score: 2
answers question: http://stackoverflow.com/q/49155321
type: Answer
upvote count: 2

http://stackoverflow.com/comment/85513652
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49253750
has text: Thanks for that. I've just tried it out. Can the presence of a digit inside the word/serial number be a 'condition' of the regex? Right now the first regex you have suggested is returning the name of the erasing software as well, in the list of results. That word is 7 letters, uppercase and no digits. Otherwise I am happy to use a list.remove() method to get rid of it.
type: Comment

http://stackoverflow.com/a/49274243
accepted answer of: http://stackoverflow.com/q/49273339
has body: Conditional expressions One option for it is to use conditional expressions. They provide simple way of checking conditions and providing one of values depending on them. In your case it will look like: sorted_things = things.annotate(diff=Case(When(n1=F('n2'), then=True), default=False, output_field=BooleanField())).order_by('diff') Q and ExpressionWrapper There is another, a bit hacky way, to achieve that by combining usage of Q and ExpressionWrapper. In django, Q is intended to be used inside filter(), exclude(), Case etc. but it simply creates condition that apparently can be used anywhere. It has only one drawback: it doesn't define what type is outputting (it's always boolean and django can assume that in every case when Q is intended to be used. But there comes ExpressionWrapper that allows you to wrap any expression and define it's final output type. That way we can simply wrap Q expression (or more than one Q expresisons glued together using &amp;, | and brackets) and define by hand what type it outputs. Be aware that this is undocumented, so this behavior may change in future, but I've checked it using django versions 1.8, 1.11 and 2.0 and it works fine Example: sorted_things = things.annotate(diff=ExpressionWrapper(Q(n1=F('n2')), output_field=BooleanField())).order_by('diff')
upvote count: 4
type: AcceptedAnswer
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/85637341
answers question: http://stackoverflow.com/q/49273339
type: Answer

http://stackoverflow.com/q/49200566
type: Question
has answer: http://stackoverflow.com/a/67525381
has comment: http://stackoverflow.com/comment/85407770
possible better answer: http://stackoverflow.com/a/67525381
score: 3
has comment: http://stackoverflow.com/comment/85411391
upvote count: 5
has comment: http://stackoverflow.com/comment/85408204
has body: I am having a really difficult time trying to Write a function compositions that takes two natural numbers k and n as inputs and returns the set of all tuples of size k that sum to n. I am concerned with finding the different permutations for the same set of numbers. I have found this documentation from python to calculate without using itertools. My questions allows for these libraries to be used import sys import numpy as np import scipy as sp from scipy.special import * def compositions(iterable, r): # combinations('ABCD', 2) --&gt; AB AC AD BC BD CD # combinations(range(4), 3) --&gt; 012 013 023 123 pool = tuple(iterable) n = len(pool) if r &gt; n: return indices = range(r) yield tuple(pool[i] for i in indices) while True: for i in reversed(range(r)): if indices[i] != i + n - r: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] + 1 yield tuple(pool[i] for i in indices) Given input compositions(3, 4) output: all possible combinations 1 + 2 + 1 2 + 1 + 1 1 + 1 + 2 actual output from composition(3,4): {(1, 1, 2,), (1, 2, 1), (2, 1, 1)} Any help would be appreciated.
has title: Function for compositions in Python
tagged with: python
has answer: http://stackoverflow.com/a/49201627
tagged with: statistics
accepted answer: http://stackoverflow.com/a/49201627
type: AnsweredQuestion
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/85407912
has comment: http://stackoverflow.com/comment/85407277
has comment: http://stackoverflow.com/comment/85407315
has comment: http://stackoverflow.com/comment/85407383
has comment: http://stackoverflow.com/comment/85407628
favorite count: 0

http://stackoverflow.com/comment/85412565
has text: @Alexander you didn’t apply my supplied solution correctly. You didn’t use the `include_image_submit` decorator until after the firm has been parced, and it is the crucial link to have the new input type class I defined be actually used. Use it before creating the browser object.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49200317

http://stackoverflow.com/comment/85304808
score: 0
type: AnswerComment
has text: it is giving type error "TypeError: unsupported operand type(s) for +: 'long' and 'str'" on this line adsize_sales_data_new.index=adsize_sales_data.index+'____'
comment on: http://stackoverflow.com/a/49147237
type: Comment

http://stackoverflow.com/comment/85355588
has text: I test dupe solution and for me it working nice, check chat with sample data and output (index has to be unique)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49173597

apache-spark
tags question: http://stackoverflow.com/q/49189075
tags question: http://stackoverflow.com/q/49188977
tags question: http://stackoverflow.com/q/49177352
tags question: http://stackoverflow.com/q/49132151
tags question: http://stackoverflow.com/q/49168338
tags question: http://stackoverflow.com/q/49162854
tags question: http://stackoverflow.com/q/49238777
tags question: http://stackoverflow.com/q/49151668
tags question: http://stackoverflow.com/q/49126700
tags question: http://stackoverflow.com/q/49167656
tags question: http://stackoverflow.com/q/49204024
tags question: http://stackoverflow.com/q/49240923
tags question: http://stackoverflow.com/q/49181179
tags question: http://stackoverflow.com/q/49163141
tags question: http://stackoverflow.com/q/49155388
tags question: http://stackoverflow.com/q/49267331
tags question: http://stackoverflow.com/q/49133004
type: Tag
tags question: http://stackoverflow.com/q/49184050
tags question: http://stackoverflow.com/q/49201341
tags question: http://stackoverflow.com/q/49263438
tags question: http://stackoverflow.com/q/49234677
tag name: apache-spark
tags question: http://stackoverflow.com/q/49243719
tags question: http://stackoverflow.com/q/49216681
tags question: http://stackoverflow.com/q/49263299
tags question: http://stackoverflow.com/q/49235092
tags question: http://stackoverflow.com/q/49189962
tags question: http://stackoverflow.com/q/49169772
tags question: http://stackoverflow.com/q/49260559
tags question: http://stackoverflow.com/q/49232611
tags question: http://stackoverflow.com/q/49191853

http://stackoverflow.com/q/49275921
score: 2
type: AnsweredQuestion
tagged with: pandas
has title: Select first existing row with equal or greater value
tagged with: python
has answer: http://stackoverflow.com/a/49276081
possible better answer: http://stackoverflow.com/a/49276081
has answer: http://stackoverflow.com/a/49276282
has body: df A B C 0 500 515 Jack 1 510 515 Helen 2 520 515 Mathiew 3 530 515 Jordan I want to get a new df1 with next conditions: Select the rows where A = B. If it doesn´t exist any row where A = B, select the first existing row where A > B. In this case, df1 should be: A B C 2 520 515 Mathiew I´ve tried: df1 = df[df["A"] == df["B"]]
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/49276256
answer count: 3
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/49276256

http://stackoverflow.com/comment/85503298
type: Comment
type: QuestionComment
has text: @jaumebonet Yeah!! I tried that too. And I encounter below error: for c in list(self.children.values()): c.destroy() TypeError: <lambda>() missing 1 required positional argument: 'num'
score: 0
comment on: http://stackoverflow.com/q/49249731

http://stackoverflow.com/q/49127258
upvote count: 0
tagged with: random-forest
tagged with: machine-learning
tagged with: python
score: -1
possible better answer: http://stackoverflow.com/a/49127369
has answer: http://stackoverflow.com/a/49127369
type: AnsweredQuestion
tagged with: performance
answer count: 2
has title: Quantifying performance of machine learning methods
has body: I am new to machine learning and I just finished implementing my first method (Random Forests). Now I want to analyze how accurate this method actually is. The first performance metric that I used was to calculate how many correct predictions were made using the following formula: accuracy = correct predictions / total predictions * 100 Now, I want to predict a variable with values of either 1 or 0. Most of my predictions fall in a range between 1 and 0 (0.85, 0.45, 0.95 etc..), hence these were not considered to be a correct prediction - resulting in an accuracy of 0.42% using the above formula. I know that I am doing something very stupid and wrong. Shall I round the predicted values to the nearest integer, and then calculate the metrics? Also, I ran an AUC test and it resulted in an accuracy of 81%.
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49127492
has answer: http://stackoverflow.com/a/49127492

http://stackoverflow.com/a/49226651
has comment: http://stackoverflow.com/comment/85457130
has body: x = np.sum(x,axis=1) min_x = x.min() max_x = x.max() presuming x is 4,2 array use np.sum to sum across the rows, then .min() returns the min value of your array and .max() returns the max value
has comment: http://stackoverflow.com/comment/85457109
type: Answer
answers question: http://stackoverflow.com/q/49226605
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85290514
type: QuestionComment
comment on: http://stackoverflow.com/q/49142338
score: 1
has text: Thanks. You'd be surprised at the times I've posted some constructive criticism here and some people take offense to it. As a matter of precaution now, I always try to soften the blow.
type: Comment

http://stackoverflow.com/q/49166524
tagged with: regex
answer count: 2
upvote count: 3
linked to: http://stackoverflow.com/q/10306690
has body: I have the following regex: r'(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}' When I apply this to a text string with, let's say, "this is www.website1.com and this is website2.com", I get: ['www.website1.com'] ['website.com'] How can i modify the regex to exclude the 'www', so that I get 'website1.com' and 'website2.com? I'm missing something pretty basic ...
downvote count: 0
has comment: http://stackoverflow.com/comment/93224791
has title: Python Regex to Extract Domain from Text
favorite count: 0
has answer: http://stackoverflow.com/a/49166612
linked to: http://stackoverflow.com/q/21211572
type: Question
has answer: http://stackoverflow.com/a/49166634
score: 3
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/49218685
tagged with: tensorflow
favorite count: 0
type: Question
has title: Working on Tensorflow :: ModuleNotFoundError: No module named '_pywrap_tensorflow_internal'
has answer: http://stackoverflow.com/a/53293587
type: UnansweredQuestion
downvote count: 0
has body: I am stuck since hours but the issue is still not resolved. I am using only the CPU version and getting the same No module named 'pywrap_tensorflow_internal' error :: Traceback (most recent call last): File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 18, in swig_import_helper return importlib.import_module(mname) File "C:\Python\Python36\lib\importlib_init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 658, in _load_unlocked File "", line 571, in module_from_spec File "", line 922, in create_module File "", line 219, in _call_with_frames_removed ImportError: DLL load failed with error code -1073741795 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 21, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\Python\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 20, in swig_import_helper return importlib.import_module('pywrap_tensorflow_internal') File "C:\Python\Python36\lib\importlib_init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named '_pywrap_tensorflow_internal' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in import tensorflow File "C:\Python\Python36\lib\site-packages\tensorflow_init_.py", line 24, in from tensorflow.python import * File "C:\Python\Python36\lib\site-packages\tensorflow\python_init_.py", line 49, in from tensorflow.python import …
tagged with: python
score: 3
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/87965405
has comment: http://stackoverflow.com/comment/85441758
has comment: http://stackoverflow.com/comment/86143776

bdd
tag name: bdd
tags question: http://stackoverflow.com/q/49190310
type: Tag

http://stackoverflow.com/comment/85490744
comment on: http://stackoverflow.com/q/49243151
has text: I can confirm with a simple test data set that the issue exists. Working on debugging.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85408931
has text: BTW, I'm getting 1.9424261669996667 and 4.202998832999583 respectively (yep, really slow). iPad running iOS 9, Python 3.6.1, NumPy 1.8.0
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49201735

http://stackoverflow.com/comment/85388839
score: 0
type: AnswerComment
has text: Please precise the question, I do not have a clue.
comment on: http://stackoverflow.com/a/49191643
type: Comment

http://stackoverflow.com/comment/85502855
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/49247557
has text: @StanislavKralin That's one of the worst things in OWL modeling :D This reminds me of the classes in schema.org, there are lots of such classes which encode the logical union in the class name.
type: Comment

http://stackoverflow.com/comment/85477827
type: AnswerComment
has text: That gets me this error: Invalid type for parameter Item.ttl.N, value: 1523493632, type: <class 'int'>, valid types: <class 'str'>
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49184433

http://stackoverflow.com/q/49188934
linked to: http://stackoverflow.com/q/1879971
upvote count: 0
answer count: 1
tagged with: virtualenv
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49197539
type: AnsweredQuestion
tagged with: python-2.7
tagged with: python
score: -1
has title: Make function call from code in Py 3.5 to code running in Py 2 environment
accepted answer: http://stackoverflow.com/a/49197539
has body: I have problem. Most of the code I built and their libraries are supported by py3.6 and I have some old code in py 2.7. The older code has lot of dependencies which rely on py 2.7 to function properly. Exporting the code to py 3.6 is the solution but due to time constraints we are avoiding that. Can I make a function call from code running in Py 3.6 virtual env to the code running in Py 2.7 virtual env. It executes the code and returns the response back. # Py 3.6 virtual env def foo(some_var): # Make call to Code in Py 2.7 Virtual env def get_response_from_bar(): # ....processing..... return response get_response_from_bar()
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/85334766
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49164562
has text: not pretty sure if i understand the model, but the data in the table shows the the variation of temperature of a heated plate at various points (x,y), so i want to estimate the temperature in certain point inside the range given in table.

oauth-2.0
type: Tag
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/49247924
tags question: http://stackoverflow.com/q/49164809

http://stackoverflow.com/q/49191065
type: Question
answer count: 1
has body: I'm implementing an application to process GPS data. In the application users can upload files and those files will be processed in server. I need to validate the user uploaded file extension. But the problem is extensions can be change. .17o, .11o, .12o, .13o, .14o, .15o, .23o, .54o common patterns are .*o, .*n, .*obs, .*nav, .nav, .obs * is always a 2 Digit number This is what I have tried ALLOWED_EXTENSIONS = set(["*+'n'" , "*+'o'"]) How can I change the ALLOWED_EXTENSIONS to accept above mentioned common patterns. I have used flask documentation for the upload file reference I think I have to change this functions def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
type: AnsweredQuestion
score: 0
has title: File uploading in flask and showing error message
has answer: http://stackoverflow.com/a/49192383
tagged with: python
accepted answer: http://stackoverflow.com/a/49192383
tagged with: file-upload

http://stackoverflow.com/q/49179155
has answer: http://stackoverflow.com/a/49183888
accepted answer: http://stackoverflow.com/a/49183888
type: AnsweredQuestion
has body: I tried the question before. But maybe I have to keep it simple. I have a jaccard value which can go from 0 to 1. I have two categories, each going from 1 to 7. Each combination of these category values producing another jaccard value. Is there any method to find some kind of correlation between the category numbers and the jaccard value? So like value 1 of category 1 gives always a high jaccard with value 2 of category 2, or value 2 of category1 gives always a high jaccard, no matter what value of category 2? import numpy as np #[category 1, category 2, jaccard] array1 = np.array([[1,1,0.1627] [1,2,0.2993] [1,3,0.1192] [1,4,0.201 ] [1,5,0.0678] [1,6,0.2354] [1,7,0.1921] [2,1,0.1627] [2,2,0.2993] [2,3,0.1192] [2,4,0.201 ] [2,5,0.0678] [2,6,0.2354] [2,7,0.1921] [3,1,0.1627] [3,2,0.2993] [3,3,0.1192] [3,4,0.201 ] [3,5,0.0678] [3,6,0.2354]])
downvote count: 0
tagged with: pandas
score: 1
upvote count: 1
has title: Python Class Correlation
favorite count: 0
tagged with: scipy
type: Question
tagged with: numpy
answer count: 1
has comment: http://stackoverflow.com/comment/85363922
tagged with: scikit-learn
tagged with: python

http://stackoverflow.com/comment/85562317
has text: You should be iterating over the `files` that `os.walk()` gives you, not the `dirs`...
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49278321
type: QuestionComment

http://stackoverflow.com/comment/85776794
has text: FTR, splash:mouse_click is better than any JS-based click function (via MouseEvent, etc.), because it sends a real mouse click event to the browser window.
type: AnswerComment
comment on: http://stackoverflow.com/a/49279621
score: 3
type: Comment

http://stackoverflow.com/q/49176929
answer count: 1
has body: I am following the example on the page:Multi-input and multi-output models The model setup to predict how many retweets and likes a news headline will receive. So the main_output is predicting the how many retweets and aux_output is predicting the likes? from keras.layers import Input, Embedding, LSTM, Dense from keras.models import Model headline_data=i for i in range(100) additional_data=[[100,200]] labels=[1,2] # Headline input: meant to receive sequences of 100 integers, between 1 and 10000. # Note that we can name any layer by passing it a "name" argument. main_input = Input(shape=(100,), dtype='int32', name='main_input') # This embedding layer will encode the input sequence # into a sequence of dense 512-dimensional vectors. x = Embedding(output_dim=512, input_dim=10000, input_length=100)(main_input) # A LSTM will transform the vector sequence into a single vector, # containing information about the entire sequence lstm_out = LSTM(32)(x) auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out) auxiliary_input = Input(shape=(5,), name='aux_input') x = keras.layers.concatenate([lstm_out, auxiliary_input]) # We stack a deep densely-connected network on top x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) x = Dense(64, activation='relu')(x) # And finally we add the main logistic regression layer main_output = Dense(1, activation='sigmoid', name='main_output')(x) # This defines a model with two inputs and two outputs: model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output]) # We compile the model and assign a weight of 0.2 to the auxiliary loss. # To specify different loss_weights or loss for each different output, # you can use a list or a dictionary. Here we pass a single loss as the loss argument, # so the same loss will be used on all outputs. # Since our inputs and outputs are named (we passed them a "name" argument), We could also have compiled the model via: model.compile(op…
tagged with: keras
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49180806
downvote count: 0
upvote count: 1
has title: Keras Documentation: Multi-input and multi-output models Not able to follow
type: UnansweredQuestion
score: 1

http://stackoverflow.com/q/49249451
has answer: http://stackoverflow.com/a/49249485
accepted answer: http://stackoverflow.com/a/49249485
has title: Where does virtualenvwrapper put python files in Windows?
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/85511536
has answer: http://stackoverflow.com/a/49717355
answer count: 2
has comment: http://stackoverflow.com/comment/85512418
tagged with: virtualenv
tagged with: virtualenvwrapper
has comment: http://stackoverflow.com/comment/86447555
possible better answer: http://stackoverflow.com/a/49717355
type: AnsweredQuestion
score: 0
has body: I used virtualenvwrapper to make a virtual environment on windows and now I need to point my IDE to the python interpreter I created but I cannot find it. I can use workon from cmd but I can't find the actual location of the new interpreter.
tagged with: windows

http://stackoverflow.com/comment/85445083
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49220735
has text: Why are you even concerned about `limit` here or accessing elements by index? For each element in `self.data` just yield it N many times - you don't need to know/care about its length or even if it has one...

http://stackoverflow.com/comment/85405634
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49200045
score: 0
has text: Am trying to find if any element from values found in key append that element in new list called category

http://stackoverflow.com/a/69063850
downvote count: 2
answers question: http://stackoverflow.com/q/49157077
has body: Simple way is: df = pd.read_csv('path to file', compression='zip'). if u need u can to add extra atr: encoding = 'windows-1251' and sep = ''
score: -2
type: Answer
upvote count: 0
has comment: http://stackoverflow.com/comment/136117232

http://stackoverflow.com/a/49235522
type: Answer
answers question: http://stackoverflow.com/q/49235268
score: 0
has body: Using For Loops list1=[['RESULT 1', 'X'], ['RESULT 2', 'Y'], ['RESULT 3', 'X', 'Y'], ['RESULT 4','Z', 'Y'], ['RESULT 5','Z'], ['RESULT 6', 'Z', 'X']] list2=[['X', '12', '56', '2'], ['Y', '100'], ['Z', '22', '78', '00', '01', '5']] for i in list1: for j in range(len(i)): for k in list2: if(i[j]==k[0]): i[j]=k print(list1) Ouptput: [['RESULT 1', ['X', '12', '56', '2']], ['RESULT 2', ['Y', '100']], ['RESULT 3', ['X', '12', '56', '2'], ['Y', '100']], ['RESULT 4', ['Z', '22', '78', '00', '01', '5'], ['Y', '100']], ['RESULT 5', ['Z', '22', '78', '00', '01', '5']], ['RESULT 6', ['Z', '22', '78', '00', '01', '5'], ['X', '12', '56', '2']]]
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49235268

http://stackoverflow.com/comment/85275355
score: 2
type: Comment
comment on: http://stackoverflow.com/q/49135146
has text: I think `labels` is wrong. It treats `k` as `w` and `g` as `l`
type: QuestionComment

http://stackoverflow.com/a/61368165
answers question: http://stackoverflow.com/q/49154090
has body: Looks like you are solving a LeetCode question: https://leetcode.com/problems/remove-duplicates-from-sorted-array/ If yes, this should be your answer: class Solution: def removeDuplicates(self, nums: List[int]) -&gt; int: if len(nums) == 1: return 1 i = 0 for j in range(1, len(nums)): if (nums[i] != nums[j]): i += 1 nums[i] = nums[j] return i + 1 It doesn't matter what you leave beyond the returned length.
type: Answer
score: 0

http://stackoverflow.com/comment/85259954
score: 0
comment on: http://stackoverflow.com/q/49127454
has text: As to modifying the env pyinstaller apps run in, there is a mention in the docs here: http://pyinstaller.readthedocs.io/en/stable/runtime-information.html?highlight=popen#ld-library-path-libpath-considerations
type: Comment
type: QuestionComment

2dsphere
tags question: http://stackoverflow.com/q/49185065
type: Tag
tag name: 2dsphere

http://stackoverflow.com/comment/85416417
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49205577
has text: The problem with the code is that the result of `money - total` is discarded. My guess was that you wanted to update money... but that's subtraction, not multiplication. Can you tell us which line you are having problems with?

http://stackoverflow.com/q/49155334
has title: Python Pandas to sort the highest number for json data
type: Question
has comment: http://stackoverflow.com/comment/85315715
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85354275
has comment: http://stackoverflow.com/comment/85353041
tagged with: python
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/json
has body: The url has data which is in json format. I would like to arrange the data for C in json. It is a long list data and I want to sort by the highest C value to the smallest. However, I just unable to read the json data in Pandas dataframe. url ='http://www.bng.com/Jso/JsonstData?qryl' pd.read_csv(url, index_col=[0,1]) &gt;&gt;&gt;Empty DataFrameColumns: [items:[{ID:0, N:'2ndChance W200123', SIP:'', NC:'CDWW', R:'', I:'', M:'', LT:0.009, C:0.001, VL:0.100, BV:2000.000, B:'0.008', S:'0.009', SV:6186.400, O:0.009, H:0.009, L:0.009, V:0.900, SC:'5', PV:0.008, P:12.500, BL:'100', P_:'X', V_:''}, {ID:1, N:'3Cnergy', SIP:''.1, NC:'502', R:''.1, I:''.1, M:'t', LT:0, C:0, VL:0.000, BV:31.000, B:'0.021', S:'0.032', SV:22.000, O:0, H:0, L:0, V:0.000, SC:'2', PV:0.021, P:0, BL:'100'.1, P_:'X'.1, V_:''}.1, {ID:2, N:'3Cnergy W200528', SIP:''.2, NC:'1E0W', R:''.2, I:''.2, M:'t'.1, LT:0.1, C:0.1, VL:0.000.1, BV:0, B:'', S:'0.004', SV:50.000, O:0.1, H:0.1, L:0.1, V:0.000.1, SC:'5'.1, PV:0.002, P:0.1, BL:'100'.2, P_:'X'.2, V_:''}.2, {ID:3, N:'800 Super', SIP:''.3, NC:'5TG', R:''.3, I:''.3, M:'t'.2, LT:1.100, C:0.000, VL:35.200, BV:8.100, B:'1.100', S:'1.110', SV:8.700, O:1.110, H:1.110, L:1.100, V:38902.000, SC:'A', PV:1.100, P:0.000, BL:'100'.3, P_:'X'.3, V_:''}.3, {ID:4, N:'8Telecom^', SIP:''.4, NC:'AZG', ...] As you can see, it is not a correct Pandas dataframe and I just can't do anything to read the data inside. Please advice
has comment: http://stackoverflow.com/comment/85317767

http://stackoverflow.com/comment/85424322
type: QuestionComment
has text: And for example, can be your matrix filled with only zeros?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49209700

http://stackoverflow.com/a/49212252
has comment: http://stackoverflow.com/comment/129786608
has body: You can run model.predict(x_test) in a subprocess and log its CPU usage simultaneously in the main process. For example, import time import multiprocessing as mp import psutil import numpy as np from keras.models import load_model def run_predict(): model = load_model('1.h5') x_test = np.random.rand(10000, 1000) time.sleep(1) for _ in range(3): model.predict(x_test) time.sleep(0.5) def monitor(target): worker_process = mp.Process(target=target) worker_process.start() p = psutil.Process(worker_process.pid) # log cpu usage of `worker_process` every 10 ms cpu_percents = [] while worker_process.is_alive(): cpu_percents.append(p.cpu_percent()) time.sleep(0.01) worker_process.join() return cpu_percents cpu_percents = monitor(target=run_predict) The values in cpu_percents for the above script would be something like:
type: Answer
has comment: http://stackoverflow.com/comment/109683122
upvote count: 23
has comment: http://stackoverflow.com/comment/109649082
has comment: http://stackoverflow.com/comment/85470731
type: AcceptedAnswer
downvote count: 0
score: 23
accepted answer of: http://stackoverflow.com/q/49197916
has comment: http://stackoverflow.com/comment/85468988
answers question: http://stackoverflow.com/q/49197916

http://stackoverflow.com/comment/92813215
has text: Also, your code relies on the fact that the arguments passed to both `open` functions are the same. What would you do if the arguments are different?
score: 0
comment on: http://stackoverflow.com/a/49224463
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85408990
comment on: http://stackoverflow.com/a/49201725
score: 0
has text: Well I don't have a tesseract.exe file, but a pytesseract.py. I tried with this, and it still doesn't work.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49268568
accepted answer: http://stackoverflow.com/a/49268731
tagged with: sockets
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: tcp
answer count: 1
has title: How to allow or deny remote connections in Python's SocketServer?
has answer: http://stackoverflow.com/a/49268731
tagged with: socketserver
type: Question
has body: I'm creating an extremely simple Vega visualization viewer: it's a one file module that serves a base HTML page containing just the Vega graphic and an HTML5 EventSource of updates. The user (me) is working in a Python shell through ssh, creates an object representing the viewer, which prints its IP and port for the user to paste into their (my) web browser. This HTTP server doesn't serve files or take input from clients, so I don't see any security concerns. The part I'm unsure of is how to set (host, port) such that my web browser can find the HTTP server running in the remote Python. I've been experimenting all afternoon, and I don't know if I'm misunderstanding what's supposed to happen or if the servers I use have changed their access policies. Here's a minimal example: import SimpleHTTPServer import SocketServer Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer((host, port), Handler) print(httpd.server_address) httpd.serve_forever() If I'm running this locally and want to ensure that outside viewers cannot access it, do I set host to "127.0.0.1" because that means a client would have to access it as 127.0.0.1, which can only happen locally? In this case, port can be 0 to get any open port. If I'm running this remotely want to to ensure that outside viewers can access it, do I set host to "" or "0.0.0.0" because that means that a client can access it as any address that makes its way to the server? In this case, I might not be able to set port to 0 because many of those ports might be blocked, or is the OS smarter about this? Basically, how is access control in Python's SocketServer supposed to work?

http://stackoverflow.com/q/49274563
has title: Django change Model's field type from CharField to JSONField
accepted answer: http://stackoverflow.com/a/49275849
has comment: http://stackoverflow.com/comment/137631449
type: Question
has comment: http://stackoverflow.com/comment/85551921
has comment: http://stackoverflow.com/comment/85552123
has answer: http://stackoverflow.com/a/49275849
linked to: http://stackoverflow.com/q/49387552
has comment: http://stackoverflow.com/comment/85551613
score: 0
answer count: 1
tagged with: django
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/85551873
favorite count: 0
has comment: http://stackoverflow.com/comment/85552090
has comment: http://stackoverflow.com/comment/85551730
has comment: http://stackoverflow.com/comment/85552118
type: AnsweredQuestion
has body: I am using Django 1.11 , I have been using CharField in Models, and dumping data in it using json.dumps(). I am using mysql database. I want to change CharField to JSONField, according to this answer. Is there any way so that I can modify my field type without loosing the data? Please note that the data in CharField is json dumped.
linked to: http://stackoverflow.com/q/37007109
tagged with: django-models
has comment: http://stackoverflow.com/comment/85551827

http://stackoverflow.com/comment/85405692
comment on: http://stackoverflow.com/q/49200272
has text: "Better" how? What shortcomings do you observe in the solution you have now?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85433257
type: QuestionComment
comment on: http://stackoverflow.com/q/49205577
has text: also the multiplication part is when im trying to get the total of well,* total* *
score: 0
type: Comment

http://stackoverflow.com/q/49182211
has answer: http://stackoverflow.com/a/49200769
tagged with: heroku
score: 0
answer count: 2
has title: Heroku push rejected, error says python 2.7.14 is unsupported, even though it is
type: Question
has body: I've created an interactive bokeh plot that I'm trying to serve with Heroku. I went through the "Getting Started on Heroku with Python" tutorial, and am also following this example. With appropriate Procfile settings, I can run the Heroku app locally just fine. I've specified the Python version in both runtime.txt AND Pipfile as 2.7.14, and that's my local version as well. But when I try to push to the Heroku server, I get the following error message remote: -----&gt; Python app detected remote: ! The latest version of Python 3 is python-3.6.4 (you are using # runtime.txt remote: python-2.7.14, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.4). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----&gt; Installing # runtime.txt remote: python-2.7.14 remote: ! Requested runtime (# runtime.txt remote: python-2.7.14) is not available for this stack (heroku-16). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected The Heroku docs (at the very link given in the error message!) say that Python 2.7.14 is in fact supported. Is there something I'm missing here, like somewhere else I need to specify the python version? My full code is here for reference. Edit: I wrote Procfile when I meant Pipfile.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49182512
tagged with: python

http://stackoverflow.com/comment/85408232
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49180565
type: Comment
has text: Can i use a function for filter by slug in a dictionary and get the respective valua a a new annotate value?

http://stackoverflow.com/q/49164769
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/49164789
has body: I've created a simple class and named one of the methods next which is failing when called. class Node(): def __init__(self, val): self.val = val self.next = 0 def next(self, obj): self.next = obj Execution code: a = Node(1) b = Node(2) a.next(b) &lt;-TypeError: 'int' object is not callable However, I'm getting TypeError: 'int' object is not callable. Any other names other than next work fine, even built-ins as 'object' / 'range' didn't reproduce the issue.
has answer: http://stackoverflow.com/a/49164792
type: Question
possible better answer: http://stackoverflow.com/a/49164789
has title: Why can't I name a function `next` - 'int' object is not callable
has answer: http://stackoverflow.com/a/49164832
tagged with: python
accepted answer: http://stackoverflow.com/a/49164792
type: AnsweredQuestion

http://stackoverflow.com/q/49187039
answer count: 0
tagged with: mod-wsgi
has comment: http://stackoverflow.com/comment/85382659
tagged with: apache
tagged with: django
has comment: http://stackoverflow.com/comment/85385133
has body: I can run Django locally just fine, but I can't deploy it using Apache. My error logs: [time 2018] [mpm_event:notice] [pid 23027:tid 140623621068672] AH00491: caught SIGTERM, shutting down [time 2018] [wsgi:warn] [pid 23278:tid 139675061790592] mod_wsgi: Compiled for Python/2.7.11. [time 2018] [wsgi:warn] [pid 23278:tid 139675061790592] mod_wsgi: Runtime using Python/2.7.12. [time 2018] [mpm_event:notice] [pid 23278:tid 139675061790592] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations /etc/apache2/sites-enabled/000-default.conf: &lt;VirtualHost *:80&gt; ServerName xxx.yyy.zzz #https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04 Alias /static /home/user/project/app/static &lt;Directory /home/user/project/app/static&gt; Require all granted &lt;/Directory&gt; &lt;Directory /home/user/project/project&gt; &lt;Files wsgi.py&gt; Require all granted &lt;/Files&gt; &lt;/Directory&gt; WSGIDaemonProcess project python-path=/home/user/project python-home=/home/user/project/env WSGIProcessGroup project WSGIScriptAlias / /home/user/project/project/wsgi.py WSGIApplicationGroup %{GLOBAL} ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined &lt;/VirtualHost&gt; I don't have any http.conf file or log.
type: Question
has comment: http://stackoverflow.com/comment/85382894
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85382779
tagged with: python
tagged with: ubuntu
has title: Deploying Django on Apache: Internal server error
has comment: http://stackoverflow.com/comment/85382538
score: 0

http://stackoverflow.com/a/49244141
has comment: http://stackoverflow.com/comment/85527763
has comment: http://stackoverflow.com/comment/85497757
type: Answer
has comment: http://stackoverflow.com/comment/85517079
answers question: http://stackoverflow.com/q/49243768
has body: Your script does not finish since the while loop is never getting false. I don't see the reason, why you define the grid as string instead of a two dimensional list (list of lists) containing integers. As well using the numpy library, which provide 2d-matrices can simplify this. Looping through nested list of integers (just a part of your values as an example), like you have done for the string: grid = [[8, 2, 22, 97, 38], [49, 49, 99, 40, 70], [81, 49, 31, 73, 55], [52, 70, 95, 23, 4]] products = [] for i in range(len(grid)): # looping the rows for j in range(len(grid[i])): # looping the cols if i+3 &lt; len(grid): v = grid[i][j]*grid[i+1][j]*grid[i+2][j]*grid[i+3][j] products.append(v) if j+3 &lt; len(grid[i]): h = grid[i][j]*grid[i][j+1]*grid[i][j+2]*grid[i][j+3] products.append(h) if i+3 &lt; len(grid) and j+3 &lt; len(grid[i]): dr = grid[i][j]*grid[i+1][j+1]*grid[i+2][j+2]*grid[i+3][j+3] products.append(dr) if j+3 &lt; len(grid) and i-3 &gt;= 0: dl = grid[i][j]*grid[i-1][j+1]*grid[i-2][j+2]*grid[i-3][j+3] products.append(dl) print(max(products)) # maximum is 24468444 took 0.002 seconds It's not needed to check both directions up and down, left and right, since it's the same because a*b*c*d = d*c*b*a. The code can be written cleaner for sure, but this is close to your example and hopefully easy to understand. Offtopic: You shoud avoid naming your lists List, because capital letters are used for classes (it's just a convention) and the name List is already defined for the default python class List. It works in this case since the variable name is checked before the class name in this scope, but it's better to avoid the builtin names ;).
accepted answer of: http://stackoverflow.com/q/49243768
type: AcceptedAnswer
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/85516492
has text: Thank you so much. This saved my life :)
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49255686
score: 0

http://stackoverflow.com/a/49149191
answers question: http://stackoverflow.com/q/49132073
has comment: http://stackoverflow.com/comment/85318554
has comment: http://stackoverflow.com/comment/85513900
has comment: http://stackoverflow.com/comment/85513961
has comment: http://stackoverflow.com/comment/85317724
has comment: http://stackoverflow.com/comment/85566180
has comment: http://stackoverflow.com/comment/85318476
score: 0
has comment: http://stackoverflow.com/comment/85563610
has comment: http://stackoverflow.com/comment/85524504
has comment: http://stackoverflow.com/comment/85318251
type: Answer
has body: You could pre-parse the data by removing any leading text from each line before passing it to pandas, for example: import pandas as pd import re with open('data.dat') as f_input: header = next(f_input).split()[1:] next(f_input) next(f_input) data = [line.strip().split() for line in f_input] df = pd.DataFrame(data[:-1], dtype='float', columns=header) This version is able to also extract the column names from the first row. If the upper only appears on the third line (and not randomly throughout the file), you could simply use skiprows to tell Pandas to start reading from the forth line onwards, and as you have a #nx: 3 in the final line, use skipfooter to skip that too: import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('data.dat', sep='\s+', skiprows=3, skipfooter=1, header=None) Tested on Pandas 0.22.0
has comment: http://stackoverflow.com/comment/85523704

http://stackoverflow.com/q/49274532
score: 2
tagged with: ordereddictionary
has comment: http://stackoverflow.com/comment/85551483
has answer: http://stackoverflow.com/a/49274998
has comment: http://stackoverflow.com/comment/85551656
tagged with: python-collections
tagged with: python
tagged with: dictionary
favorite count: 0
has body: I would like to inherit the OrderedDict class to set up a maximum length to the dict. I did : from collections import OrderedDict class limitedDict(OrderedDict): def __init__(self, length): OrderedDict.__init__(self) self.length = length But now I don't see which function to overwrite to catch the "adding a key" event. I Googled for a while without finding the answer. Even special functions are not clearly an answer.
type: Question
has title: Which method is called when adding a key to a dict?
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85551540

http://stackoverflow.com/comment/85410674
comment on: http://stackoverflow.com/q/49202647
has text: The `print()` is there to print a newline each time after the inner loop is done.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49151287
accepted answer: http://stackoverflow.com/a/49157258
favorite count: 0
type: Question
tagged with: python-3.x
downvote count: 0
has title: How to avoid No-SSL-CERTIFICATE error in youtube-dl?
upvote count: 1
tagged with: youtube-dl
tagged with: ssl-certificate
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49157258
has body: import tkinter import youtube_dl ydl_opts = { 'nocheckcertificate:': True } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['https://www.youtube.com/watch?v=C-u5WLJ9Yk4']) print('done') Hi , by executing the above code, I am getting ERROR: Unable to download webpage: (caused by URLError(SSLError(1, '[SSL: CERTIFICAT How to avoid this error? I am using pycharm3, It's working fine through my mac OS terminal. For your reference. https://github.com/rg3/youtube-dl/blob/master/README.md#embedding-youtube-dl
score: 1
answer count: 1
tagged with: ssl
tagged with: python

http://stackoverflow.com/comment/85481874
score: 0
comment on: http://stackoverflow.com/q/49239002
type: Comment
type: QuestionComment
has text: You have to access it via `globals()['df_new dataframe']`...

http://stackoverflow.com/a/49163798
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49163709
has body: Here is one solution. I use pandas for convenience but this is easily adaptable to a non-pandas variant. from io import StringIO from ast import literal_eval import pandas as pd mystr = StringIO("""{'timid':'34567', 'version':'1','binary_data':'fsfdsfsdfasdfasdfsfasfdsa','seqNumber':'101'} {'timid':'32567', 'version':'1','binary_data':'fsfsdfdsfdsfdsfsfsdfpipi','seqNumber':'109'} {'timid':'36567', 'version':'1','binary_data':'fsfdsfsdfafsdfdsfsfasdfsfasfdsa','seqNumber':'100'} """) # read file df = pd.read_csv(mystr, header=None, sep='|') # create list of dictionaries lst = df[0].map(literal_eval).tolist() # sort list res = sorted(lst, key=lambda x: int(x['seqNumber'])) # [{'binary_data': 'fsfdsfsdfafsdfdsfsfasdfsfasfdsa', # 'seqNumber': '100', # 'timid': '36567', # 'version': '1'}, # {'binary_data': 'fsfdsfsdfasdfasdfsfasfdsa', # 'seqNumber': '101', # 'timid': '34567', # 'version': '1'}, # {'binary_data': 'fsfsdfdsfdsfdsfsfsdfpipi', # 'seqNumber': '109', # 'timid': '32567', # 'version': '1'}]
type: Answer

http://stackoverflow.com/comment/85397011
comment on: http://stackoverflow.com/a/49195844
score: 0
type: Comment
has text: @TheDoctor See my updated answer to see if that does the trick
type: AnswerComment

http://stackoverflow.com/comment/85367336
comment on: http://stackoverflow.com/q/49180302
type: Comment
score: 0
has text: @DeepSpace: It's trivial with a loop, just more trivial without one. A novice would never write `any(num1==x for x in range(num2-1, num2+1))`, but they might come up with the expanded-out version of that. (And maybe the no-loop thing isn't supposed to be a restriction to ban that answer, but a hint to make them not go down the path of thinking that way?)
type: QuestionComment

http://stackoverflow.com/comment/85530689
score: 0
comment on: http://stackoverflow.com/q/49263464
has text: @chrisz If you follow the link, in the given data, I am not interested in the last 9 elements starting from "follow" to "compare". I would like to remove all those 9 elements from each nested list.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85593249
type: Comment
type: QuestionComment
score: 0
has text: Sorry, but I do not believe you. Please show the actual test.
comment on: http://stackoverflow.com/q/49271540

http://stackoverflow.com/comment/85325002
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49159840
score: 3
has text: The default here isn't "a dict that looks like `phn_dictionary`". The default is **`phn_dictionary`**.

http://stackoverflow.com/q/49271464
type: Question
has body: CLASS RECORD OF THE STUDENT FROM THE PREVIOUS BATCH WHO TOPPED Name (Roll no) # Location Section Rank (MARKS) Gender Anna (+) USA A1 First (100) Female (04) California V ADDITIONAL RECORDS OF THE STUDENTS FROM THE PREVIOUS BATCH NEXT IN LIST Name (Roll no) # Location Section Rank (MARKS) Gender Bob (-) USA A2 First (99) Male (07) Florida VI Eva (+) USA A4 Second (96) Female (12) Ohio V English (99) Maths(100) Other records are not available currently.Some records may be present which can be given on request. Getting the text file from a PDF using pdftotext. Using below AWK command I am getting the above data. Table data is unevenly space separated. Remove the lines where the whole line is in Uppercase Remove all the last lines after the table content. pdftotext -layout INPUTFILE.pdf INPUTFILE.txt awk '/RESULTS/{flag=1;next}/OTHER DATA/{flag=0}flag' INPUTFILE.txt | column -ts $'\t' -n How do I get the table data in tab delimited format(Below Format)? Code in a generic way, so it works other types of tables also. Name (Roll no) # Location Section Rank (MARKS) Gender Anna (+) USA A1 First (100) Female (04) California V Bob (-) USA A2 First (99) Male (07) Florida VI Eva (+) USA A4 Second (96) Female (12) Ohio V English (99) Maths (100)
type: AnsweredQuestion
answer count: 2
accepted answer: http://stackoverflow.com/a/49274774
has answer: http://stackoverflow.com/a/49274774
downvote count: 0
tagged with: awk
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85585420
favorite count: 0
has title: Extracting table data from unevenly spaced text file
tagged with: sed
possible better answer: http://stackoverflow.com/a/49272585
tagged with: python
tagged with: text-processing
has answer: http://stackoverflow.com/a/49272585
tagged with: ubuntu

http://stackoverflow.com/comment/85452227
has text: Yes, (15, 16, 3) is not allowed.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49224305

http://stackoverflow.com/comment/85567745
comment on: http://stackoverflow.com/q/49278571
has text: @abe-wong. Just a note the say that sklearn's `cross_val_score` doesn't shuffle by default. You will need to pass something like `cv=StratifiedKFold(shuffle=True)` to it if you want to shuffle because your classes are not evenly distributed in your dataset - for example if your data is sorted by class.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85385563
type: QuestionComment
comment on: http://stackoverflow.com/q/49189075
score: 0
has text: Ok, but which is the correct index to access to it?
type: Comment

http://stackoverflow.com/a/49183104
has comment: http://stackoverflow.com/comment/85372177
has body: Here's the function changed to return a value: def create_table(): message = "" message += " " + "\n" # column headers message += " " + "\n" message += " Tech " + "\n" message += " Total " + "\n" message += " Average " + "\n" message += " " + "\n" infile = open("test.csv","r") for line in infile: row = line.split(",") tech = row[0] total = row[1] average = row[2] message += (" %s " % tech) + "\n" message += (" %s " % total) + "\n" message += (" %s " % average) + "\n" message += (" ") + "\n" return message
accepted answer of: http://stackoverflow.com/q/49183032
answers question: http://stackoverflow.com/q/49183032
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/85372756
type: AcceptedAnswer
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/85295140
has text: @Waseem.py You may find the reason at [Indexing Multi-dimensional arrays](https://docs.scipy.org/doc/numpy/user/basics.indexing.html#indexing-multi-dimensional-arrays).
type: Comment
comment on: http://stackoverflow.com/q/49144809
type: QuestionComment
score: 0

iterator
tags question: http://stackoverflow.com/q/49220122
tag name: iterator
tags question: http://stackoverflow.com/q/49178906
tags question: http://stackoverflow.com/q/49143787
tags question: http://stackoverflow.com/q/49220735
type: Tag
tags question: http://stackoverflow.com/q/49157640

http://stackoverflow.com/a/49131102
score: 3
answers question: http://stackoverflow.com/q/49131026
has body: You can use a generator expression within join using enumerate to get the index of each letter. If the index isn't in ind then keep it. &gt;&gt;&gt; ''.join(j for i,j in enumerate(seq_in) if i not in ind) 'AJDSGA' As mentioned in the comments, your lookups will be faster if ind is a set than if it stays a list &gt;&gt;&gt; ind = {0, 1, 2, 3, 8, 10, 11, 12, 13, 14, 16, 17, 18} &gt;&gt;&gt; ''.join(j for i,j in enumerate(seq_in) if i not in ind) 'AJDSGA'
has comment: http://stackoverflow.com/comment/85266671
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49131026
upvote count: 3

http://stackoverflow.com/a/49225229
has body: I would like to propose do next: import sys, random, time from PyQt5 import QtWidgets from PyQt5.QtCore import * from PyQt5 import Qt #+ class getData(QThread): #This Thread should run all the time threadSignalGetData = pyqtSignal(int) def __init__(self, myNumber): super().__init__() self.myNumber = myNumber def run(self): #myNumber = 0 while True: #He 'processData Thread'!! Do Something with mynumber!! Qt.QThread.msleep(1000) self.myNumber += 1 self.threadSignalGetData.emit(self.myNumber) class MsgBoxGetData(Qt.QDialog): def __init__(self): super().__init__() layout = Qt.QVBoxLayout(self) self.label = Qt.QLabel("") layout.addWidget(self.label) close_btn = Qt.QPushButton("Close window GetData") layout.addWidget(close_btn) close_btn.clicked.connect(self.close) self.setGeometry(900, 65, 400, 80) self.setWindowTitle('MsgBox GetData') self.setStyleSheet("""QLabel{ font-family:'Consolas'; color: green; font-size: 16px;}""") class processData(QThread): threadSignalProcessData = pyqtSignal(int, int) def __init__(self, myNumber): super().__init__() self.newNumber = myNumber def run(self): flagProcessData = True while flagProcessData: #Extremly complex code will execute while 'getData' is doing its thing. newNumber = self.newNumber * 10 self.threadSignalProcessData.emit(self.newNumber, newNumber) flagProcessData = False class MsgBoxProcessData(Qt.QDialog): def __init__(self): super().__init__() layout = Qt.QVBoxLayout(self) self.label = Qt.QLabel("") layout.addWidget(self.label) close_btn = Qt.QPushButton("Close window ProcessData") layout.addWidget(close_btn) close_btn.clicked.connect(self.close) self.setGeometry(900, 200, 400, 80) self.setWindowTitle('MsgBox ProcessData') self.setStyleSheet("""QLabel{ font-family:'Consolas'; color: red; font-size: 24px;}""") class Ui(Qt.QWidget): def __init__(self, parent=None): super(Ui, self).__init__(parent) layout = Qt.QVBoxLayout(self) self.lbl = Qt.QLabel("process GUI") layout.addWidget(self.lbl) self.btnA = Qt.QPushButton("Start get…
has comment: http://stackoverflow.com/comment/85620723
has comment: http://stackoverflow.com/comment/85620235
accepted answer of: http://stackoverflow.com/q/49210097
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49210097
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/127972450
comment on: http://stackoverflow.com/a/49280607
type: Comment
type: AnswerComment
score: 0
has text: when returning values from sqlite in python, how can we get them to return the timezone info also, wihtout specifying in the select query?

http://stackoverflow.com/comment/85386416
type: QuestionComment
has text: Try Pathlib if python version above or equal to 3.4, [x.unlink() for x in Pathlib.Path(dir_path).glob('*.drx')] work for you
type: Comment
comment on: http://stackoverflow.com/q/49190108
score: 0

http://stackoverflow.com/comment/121879109
comment on: http://stackoverflow.com/a/62276544
type: Comment
has text: The following worked for me ```from PIL import Image im = Image.open("dragon.png") im```. im.show() is buggy on google colab, just use "im" instead (see https://stackoverflow.com/questions/60034512/cant-show-an-image-using-pil-on-google-colab)
score: 0
type: AnswerComment

http://stackoverflow.com/q/49224006
has comment: http://stackoverflow.com/comment/85484928
has body: I am a beginner in Python. I am trying to find a way to get descriptions for Unicode characters Code: str = "python"+chr(8) for i in str: print(chr(ord(i))) eg: ord(i) = 105 chr(105) = i My problem are non-ASCII Unicode characters like chr(8), I want to retrieve a description like "backspace" in this case.
has comment: http://stackoverflow.com/comment/85455060
has comment: http://stackoverflow.com/comment/85484969
score: 0
upvote count: 1
downvote count: 1
favorite count: 0
has title: How to get the character description
type: Question
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85455430

http://stackoverflow.com/q/49154332
score: 0
tagged with: java
answer count: 1
type: Question
tagged with: difference
has body: Is there any way to compare my XML with the XSD by using Java/Python and write those element names in a text file which are not in synch with the schema.
type: UnansweredQuestion
has title: Validate XML File with the XSD and write the name of the differences in a text file Using Java or any Programming Language
tagged with: python
tagged with: xsd
tagged with: http://stackoverflow.com/tag/xml
has answer: http://stackoverflow.com/a/49155494

http://stackoverflow.com/comment/85316781
has text: @DPdl, still need to combine the columns (as in the previous post), i.e. you should have 2 `intakeDate` columns.
score: 0
comment on: http://stackoverflow.com/q/49154375
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49150100
accepted answer of: http://stackoverflow.com/q/49150016
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49150016
score: 0
has body: This line is wrong: self.topic_selection_window = SelectTopic(self, self.centralWidget(), topics) That's where that additional argument comes from. You've passed self to SelectTopic.__init__(). You don't have to, as that method will get the value under self passed to it implicitly. To clarify, these are the values that __init__() got from your call: An instance of SelectTopic The object you had under the self that you've passed to it The return value of self.centralWidget() The value under topics That's why it complained about getting 4 arguments instead of 3. The line we're talking about should look like this: self.topic_selection_window = SelectTopic(self.centralWidget(), topics) If you want to know a little bit more about how self works, this article is a great start.
has comment: http://stackoverflow.com/comment/85304669

http://stackoverflow.com/a/49203215
score: 0
answers question: http://stackoverflow.com/q/49201142
has body: You have to register the blueprint with the application before the routes will have any effect. Just creating the blueprint doesn't make the routes active. You register the blueprint by calling register_blueprint on your app object: app.register_blueprint(create_testcases_bp)
type: Answer

http://stackoverflow.com/q/49123212
type: AnsweredQuestion
score: 0
has body: I'm a brand new programmer and started out with python as my first language. for user in range (1): rowcol=input() a=[] a=rowcol.split(" ") rowNum=int(a[0]) colNum=int(a[1]) board=[] for row_count in range(rowNum): row=[] row.append(input()) board.append(row) print(board) the first input is "2 2" which determines the rows and columns the next input is "--" and "--" which inputs these characters in both rows the array I have rn displays [['--'], ['--']] I need it to display this [['-','-'], ['-','-']] I don't know how to attempt splitting each element in the array
tagged with: python
has answer: http://stackoverflow.com/a/49123306
has answer: http://stackoverflow.com/a/49123404
accepted answer: http://stackoverflow.com/a/49123404
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/49123306
has title: Splitting Elements in a 2Dlist into sub-elements? Python 3

http://stackoverflow.com/q/49148421
has comment: http://stackoverflow.com/comment/85367582
tagged with: python-2.7
tagged with: tkinter
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/85312659
tagged with: cmd
score: 1
downvote count: 1
favorite count: 0
type: Question
has body: I have been trying to find any way to add command prompt in TKinter gui. So, please any one can help me. `from Tkinter import * import os root = Tk() cmd= Frame(root, width = 400, height = 200) cmd.pack(fill=BOTH, expand=YES) wid = cmd.winfo_id() os.system('cmd -into %d -geometry 80x20 -sb -e python &amp;' % wid) root.mainloop()`
has comment: http://stackoverflow.com/comment/85312881
tagged with: python-3.x
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/665566
has comment: http://stackoverflow.com/comment/85302166
tagged with: python
has comment: http://stackoverflow.com/comment/85303104
has title: how to add windows command prompt in tkinter?

http://stackoverflow.com/a/49211266
has comment: http://stackoverflow.com/comment/85426901
score: 0
type: Answer
has body: form tag should have an attribute action to tell where to take the data of your form to. So in Register.html you should add action="{% url 'nameofyourviewgiveninurls.py'%}" in your form tag
answers question: http://stackoverflow.com/q/49208101

http://stackoverflow.com/q/49189836
has comment: http://stackoverflow.com/comment/85384866
tagged with: sql
answer count: 1
has body: I have a table as such: |Date |Type |MetricA|MetricB| |01-01|House|0 |500 | |01-01|Paid |1 |1000 | |01-01|Paid |1 |4000 | |02-01|House|0 |3000 | |02-01|Paid |10 |13000 | |02-01|House|0 |5000 | |02-01|Paid |5 |10000 | |02-01|Paid |1 |1500 | I want to calculate a 3rd metric (1000*MetricA / MetricB), and I also want MetricB split up per type, so that my final table looks like this: |Date |Metric_House|Metric_Paid|MetricA|NewMetric |01-01|500 |5000 |2 |0.40 |02-01|8000 |24500 |16 |0.653061224 (I hope the table structure makes sense, otherwise I can refer you to a screenshot here: https://i.sstatic.net/x2uRa.png) I figured out how to properly write the Metric_House, Metric_Paid,MetricA column, but I am struggling to write the NewMetric. Sometimes MetricB == 0, then I can get divide by 0. I can write a case function, but then I run into aggregated summation trouble. I have spent hours trying write a query for this and I just can not figure it out :( I tried this: func.sum(case([((i.c.metricb) != 0, 1000*func.sum(i.c.metrica)/i.c.metricb)], else_=0)) Which is SQLAlchemy (Python layer over SQL), but it basically is: SUM(CASE WHEN METRIC != 0 THEN 1000*SUM(METRICA)/SUM(METRICB) ELSE 0 I get a nested error after that query. I am working in a Python framework, and when I ignore the NewMetric column in the query and just add it afterwards with a simple list function, I did it in a few minutes. But I rather have the data processed within SQL rather than outside. What would be the best way of writing this query? Thanks in advance! EDIT: Here is what I have working: stmt = select([i.c.date, cast(func.sum(case([( i.c.type != 'House', i.c.metricb)], else_=0)), Integer).label('metric_paid'), cast(func.sum(case([( i.c.type == 'House', i.c.metricb)], else_=0)), Integer).label('metric_house'), cast(func.sum(i.c.metrica), Float).label('metrica')]).group_by( i.c.date).order_by(asc(i.c.date)) Now here's what I tried (adding this extra expression): case([(sum(i.c.metricb) != 0, 1000*sum(i.c…
tagged with: sqlalchemy
type: Question
has title: Division by zero and CASE WHEN function
tagged with: postgresql
tagged with: python
has comment: http://stackoverflow.com/comment/85386109
has comment: http://stackoverflow.com/comment/85385200
has comment: http://stackoverflow.com/comment/85384963
has comment: http://stackoverflow.com/comment/85384915
has answer: http://stackoverflow.com/a/49219402
accepted answer: http://stackoverflow.com/a/49219402
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/85554780
type: Comment
type: QuestionComment
score: 0
has text: @DebanjanB I'm using a internal website for which I dont have access to html code. I'm using mozilla to inspect element. I want to show the field thats been used. I have uploaded the code and error and only for html I used screenshot.
comment on: http://stackoverflow.com/q/49275041

http://stackoverflow.com/q/49145544
score: 1
accepted answer: http://stackoverflow.com/a/49167111
tagged with: python
type: Question
has body: I am building a simple one-hidden-layer neural network with Tensorflow. For the inputs, every row of data corresponds to 10 answers. The first 2 elements of each row are correct, i.e. the same to the ground truth labels. In contrast, the last 8 elements are opposite to the ground truth label. For example, [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], correct is 1 [0, 0, 1, 1, 1, 1, 1, 1, 1, 1], correct is 0 [0, 0, 1, 1, 1, 1, 1, 1, 1, 1], correct is 0 [1, 1, 0, 0, 0, 0, 0, 0, 0, 0], correct is 1 I would like my neural network to learn that the first two elements/features always give the correct results. Therefore, I wish the network to give bigger weights to the first two features. However, the network will always get stuck at some loss value. More interestingly, the accuracy is taken as the proportion of labels that are correctly predicted out of the total number of labels. The loss function is calculated with the sigmoid function, i.e., $y * log(logit) + (1-y) * log(1-logit))$. Sometimes, as the loss decreased, the accuracy increased. e.g., epoch is: 0 loss is: 7.661093 accuracy value is: 1.0 epoch is: 100 loss is: 7.579134 accuracy value is: 0.54545456 epoch is: 200 loss is: 7.5791006 accuracy value is: 0.54545456 I thought the network could keep increasing the weights of the first two elements until it can completely predict the correct label. Can anyone please tell me what should I do to facilitate the network correctly predicting the label, instead of getting stuck? My code is here: import tensorflow as tf import numpy as np class SigmoidNeuralNetwork(): def __init__(self, learning_rate, training_data, correct_labels, epoch_number): self.learning_rate = learning_rate self.training_data = training_data self.correct_labels = correct_labels self.X = tf.placeholder(tf.float32) self.y = tf.placeholder(tf.float32) self.feature_num = len(self.training_data[0]) self.sample_num = len(self.training_data) self.W = tf.Variable(tf.random_uniform([self.feature_num, 1], -1.0, 1.0), dtype=…
downvote count: 0
upvote count: 1
has title: Tensorflow: loss value is inconsistent with accuracy
answer count: 1
tagged with: neural-network
has answer: http://stackoverflow.com/a/49167111
tagged with: machine-learning
tagged with: tensorflow
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85299765

http://stackoverflow.com/q/49224826
has title: Change sign of elements with an odd sum of indices
has comment: http://stackoverflow.com/comment/85453336
answer count: 2
has comment: http://stackoverflow.com/comment/85464083
tagged with: array-broadcasting
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/85453827
score: -6
downvote count: 7
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49230407
has comment: http://stackoverflow.com/comment/85453529
tagged with: python
has body: arr is a n-dimensional numpy array. How to change sign of every element of arr with an odd sum of indices? For example, arr[0, 1, 2] needs a sign change because it has a sum of indices 0 + 1 + 2 = 3, which is odd. When I convert arr to a list, I notice that every second element in the list are elements that needs a sign change. Another example: Original array: [[[ 0 1 2] [ 3 4 5] [ 6 7 8]] [[ 9 10 11] [12 13 14] [15 16 17]] [[18 19 20] [21 22 23] [24 25 26]]] Array with signs changed: [[[ 0 -1 2] [ -3 4 -5] [ 6 -7 8]] [[ -9 10 -11] [12 -13 14] [-15 16 -17]] [[18 -19 20] [-21 22 -23] [24 -25 26]]]
has answer: http://stackoverflow.com/a/49225247
has comment: http://stackoverflow.com/comment/85453863
tagged with: python-2.7

http://stackoverflow.com/comment/85277710
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49135849
has text: Maybe `df['counter'] = df.groupby(level=0).cumcount() + 1` to count starting with one instead of zero.

http://stackoverflow.com/comment/85525696
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49260004
type: QuestionComment
has text: How are you verifying that your decoded word is in fact a word? Are you checking it against a list of words or an entire language's dictionary? Are you looking for a specific word? Or are you just trying to get this decode function to work at this point?

http://stackoverflow.com/q/49219278
has comment: http://stackoverflow.com/comment/85451828
possible better answer: http://stackoverflow.com/a/49224541
has comment: http://stackoverflow.com/comment/85451889
tagged with: python
has comment: http://stackoverflow.com/comment/85449708
has body: I'm using pyqtgraph to plot tracks of a robot (the path that the bot drove). Now I want to add a marker to the plot to indicate the bots current position and heading. I thought ArrowItem would be the right choice, because it is scale invariant and can be rotated easily. However the local origin of the arrow is at its tip like this but I want it to be in the center like this How can I do that? I would also appreciate different solutions to this problem. Update After applying eyllansec's code I get some rendering problems. A minimal example (one has to zoom or move the view to disable the auto scaling): import pyqtgraph as pg import numpy as np import time class CenteredArrowItem(pg.ArrowItem): def paint(self, p, *args): p.translate(-self.boundingRect().center()) pg.ArrowItem.paint(self, p, *args) if __name__ == '__main__': app = pg.QtGui.QApplication([]) window = pg.GraphicsWindow(size=(1280, 720)) window.setAntialiasing(True) tracker = window.addPlot(title='Tracker') while True: for i in range(300): arrow = CenteredArrowItem(angle=i, headLen=40, tipAngle=45, baseAngle=30) arrow.setPos(i / 300, i / 300) tracker.addItem(arrow) app.processEvents() time.sleep(0.02) tracker.removeItem(arrow) As you may noticed I'm adding and removing the arrow each iteration. This is because arrow.setStyle(angle=i) is not working as it does not update the rotation of the arrow (probably a bug).
has title: pyqtgraph - move origin of ArrowItem to local center
has comment: http://stackoverflow.com/comment/85446436
tagged with: pyqt
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49223444
has comment: http://stackoverflow.com/comment/85451852
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49223444
score: 1
upvote count: 1
tagged with: pyqtgraph
has answer: http://stackoverflow.com/a/49224541
favorite count: 0
tagged with: qt
type: Question

http://stackoverflow.com/comment/85344056
score: 0
comment on: http://stackoverflow.com/q/49166676
type: Comment
has text: Check this https://github.com/gianlucaborello/cassandradump
type: QuestionComment

http://stackoverflow.com/q/49267511
score: 1
linked to: http://stackoverflow.com/q/10154343
tagged with: mysql
tagged with: sqlalchemy
type: Question
has body: I am using sqlalchemy to write to a mysql db where I am indexing some files and storing their contents. I need to write the files and then write the index entries which have a foreign key to the files table. However, sqlalchemy seems to be issuing the INSERT statements out of order. Here is a minimal functional example illustrating the problem using mock random data (less the configuration file, which contains server specific info): Index/ORM.py: #!/bin/env python2.7 from __future__ import print_function import os from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.dialects.mysql import LONGBLOB, INTEGER from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy import create_engine from Index import load_cfg class Base(object): """ Basic MySQL table settings """ __table_args__ = { 'mysql_engine': 'InnoDB', 'mysql_collate': 'latin1_general_cs' } Base = declarative_base(cls=Base) class CoverageIndex(Base): """ Class for coverage_index table objects """ __tablename__ = 'coverage_index' filename = Column(String(45), primary_key=True) #filename = Column(String(45), ForeignKey("files.filename"), primary_key=True) sequence_id = Column(String(45), primary_key=True, index=True) def __init__(self, filename, sequence_id): self.filename = filename self.sequence_id = sequence_id class FileRow(Base): """ Class for files stored in db """ __tablename__ = 'files' filename = Column(String(45), primary_key=True) contents = Column(LONGBLOB) def __init__(self, filename, contents): self.filename = filename self.contents = contents cfg = load_cfg() db_string = 'mysql://%(user)s:%(passwd)s@%(host)s/%(db)s' % cfg['db_config'] engine = create_engine(db_string, echo=True) Base.metadata.create_all(engine) if __name__ == '__main__': pass index.py: #!/usr/bin/env python2.7 from __future__ import print_function import os import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.o…
has title: INSERT commands not in order using sqlalchemy and mysql for large rows
answer count: 1
upvote count: 1
tagged with: python
downvote count: 0
accepted answer: http://stackoverflow.com/a/49267893
favorite count: 0
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49267893

http://stackoverflow.com/a/49227321
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49227291
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85458372
answers question: http://stackoverflow.com/q/49227291
has body: allowDiskUse:True is not valid Python syntax. Perhaps you meant allowDiskUse=True? Note the equals sign instead of a colon.
type: Answer

pixel
tags question: http://stackoverflow.com/q/49241059
type: Tag
tag name: pixel
tags question: http://stackoverflow.com/q/49178389
tags question: http://stackoverflow.com/q/49263046

http://stackoverflow.com/comment/85522357
type: Comment
type: QuestionComment
has text: What happens, any exceptions? You have changed the source code taken from https://stackoverflow.com/questions/15018372/how-to-take-partial-screenshot-with-selenium-webdriver-in-python. Why? `fox.save_screenshot('screenshot.png')` should do the job.
comment on: http://stackoverflow.com/q/49258352
score: 0

http://stackoverflow.com/a/49176695
type: Answer
score: 2
answers question: http://stackoverflow.com/q/49176277
upvote count: 2
downvote count: 0
has body: Textedit and Excel have different default ways of using unicode, which is why the characters look different. The default pandas output is ascii in python2 and utf-8 in python 3. You can modify either that, or excel, to see the degrees symbol.

http://stackoverflow.com/a/49144924
has comment: http://stackoverflow.com/comment/85295470
accepted answer of: http://stackoverflow.com/q/49128032
answers question: http://stackoverflow.com/q/49128032
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: You're calling starmap with a list of just one tuple of arguments. The return value will therefore also be a list containing one element - the tuple returned by one call to solver. So you're effectively saying X, u, t = [(x1, u1, t1)] which is why you get the exception you're getting: you can't unpack one value (the returned tuple) into three variables. If you want to use starmap here you'll need to do something like: [(X,u,t)] = pool.starmap(solver,[args]) instead. But for only one set of arguments it makes more sense to use apply, since it's designed for a single invocation: X,u,t = pool.apply(solver, args)
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85295926

http://stackoverflow.com/comment/85318257
has text: Actually i didnt explain it really good. I want to search if my index is inside the tuples so between 874-893 964-985 etc.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49156725
type: AnswerComment

http://stackoverflow.com/q/49121503
tagged with: queue
favorite count: 0
type: Question
downvote count: 0
tagged with: python
tagged with: flask
has body: import time from flask import Flask, jsonify from multiprocessing import Process, Value app = Flask(__name__) class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) tasks = [ { 'id': 1, 'title': u'Buy groceries', 'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 'done': False }, { 'id': 2, 'title': u'Learn Python', 'description': u'Need to find a good Python tutorial on the web', 'done': False } ] q = Queue() @app.route('/todo/api/v1.0/tasks', methods=['GET']) def get_tasks(): q.enqueue('cat') print("Size: " + str(q.size())) return jsonify({'tasks': tasks}) def record_loop(loop_on): while True: if loop_on.value == True: print("loop running") q.enqueue('dog') print("Size: " + str(q.size())) time.sleep(1) if __name__ == "__main__": recording_on = Value('b', True) p = Process(target=record_loop, args=(recording_on,)) p.start() app.run(debug=True, use_reloader=False) p.join() I have a global class called queue. The queue's data is shared between 2 different functions, but its not working. Why is the queue in the function 'get_tasks()' size always equal 1? I thought queues are thread safe and they can be shared between different processes?
accepted answer: http://stackoverflow.com/a/49121685
has comment: http://stackoverflow.com/comment/85248782
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49121685
has title: Python shared queue - 2 different threads
score: 3
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/85248749
tagged with: concurrency

http://stackoverflow.com/comment/85264757
comment on: http://stackoverflow.com/q/49130053
score: 0
type: Comment
has text: You can use `print_dict(**{'a': 'jack', 'b': 'rose'})` and get the same result, you don't have to pass it as function arguments.
type: QuestionComment

http://stackoverflow.com/q/49155844
type: AnsweredQuestion
has title: Python / Pandas : concatenate two dataframes with multi index
answer count: 2
possible better answer: http://stackoverflow.com/a/49156092
tagged with: pandas
has body: I have two dataframes with same index &amp; columns. (x, y) &gt;&gt;&gt; x A B 0 A0 B0 1 A1 B1 &gt;&gt;&gt; y A B 0 A2 B2 1 A3 B3 I found out how to concatenate two dataframes with multi-index as follows. (z) &gt;&gt;&gt; z = pd.concat([x, y], keys=['x', 'y'], axis=1) &gt;&gt;&gt; z x y A B A B 0 A0 B0 A2 B2 1 A1 B1 A3 B3 But I want to make the following format of dataframe (target ) &gt;&gt;&gt; target A B x y x y 0 A0 A2 B0 B2 1 A1 A3 B1 B3 I have two questions Is there a nice way to get the 'target' dataframe directly from the x, y ? Is there a nice way to get the 'target' datafrme from z by changing the level of columns? Thank you for considering my questions.
has answer: http://stackoverflow.com/a/49156092
downvote count: 0
accepted answer: http://stackoverflow.com/a/49155891
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49155891
score: 5
upvote count: 5
tagged with: python

http://stackoverflow.com/comment/85333349
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49162542
has text: try: `df['ticker'] = np.select(conds, choices, default = 'test')`, if the last 2 records are filled with the value `test`, it means that none of the conditions provided were satisfied in those rows. Otherwise, I'm not sure...
type: AnswerComment

http://stackoverflow.com/comment/85411659
type: QuestionComment
score: 0
has text: I was debugging. Pulled my code out of the function. Opened 1 .lab file. My code didn't seem to work without it! So I'm not entirely sure truth be told!
comment on: http://stackoverflow.com/q/49202669
type: Comment

http://stackoverflow.com/q/49190459
accepted answer: http://stackoverflow.com/a/49190741
has body: The qeustion is how should i create a dictionary out of two different length lists. I dont have dictionary. I want to create dictionary. I would like to create a dictionary out of two lists that have different length when i apply split method. Forexample names Out[41]: ['Georgie Porgie', 'Queen St. Cafe', 'Dumplings R Us', 'Mexican Grill', 'Deep Fried Everything'] cuisines Out[42]: ['Canadian,Pub Food', 'Malaysian,Thai', 'Chinese', 'Mexican', 'Pub Food'] cuisines_splited Out[43]: [['Canadian', 'Pub Food'], ['Malaysian', 'Thai'], ['Chinese'], ['Mexican'], ['Pub Food']] I would like to create a dictionary, using cuisines_splited as keys and names as values. I have tried so far this but it doesnot give the right answer. cuisine_to_names = {} for cuis, name in zip(cuisines_splited, names): for i in cuis: cuisine_to_names[i] = name cuisine_to_names Out[46]: {'Canadian': 'Georgie Porgie', 'Chinese': 'Dumplings R Us', 'Malaysian': 'Queen St. Cafe', 'Mexican': 'Mexican Grill', 'Pub Food': 'Deep Fried Everything', 'Thai': 'Queen St. Cafe'} The desired output is: {'Canadian': ['Georgie Porgie'], 'Pub Food': ['Georgie Porgie', 'Deep Fried Everything'], 'Malaysian': ['Queen St. Cafe'], 'Thai': ['Queen St. Cafe'], 'Chinese': ['Dumplings R Us'], 'Mexican': ['Mexican Grill']}
has answer: http://stackoverflow.com/a/49190741
downvote count: 1
favorite count: 0
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85387318
possible better answer: http://stackoverflow.com/a/49190864
score: 1
tagged with: python
tagged with: dictionary
has title: Dictionary from 2 different length lists in Python
type: Question
tagged with: list
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49190864

http://stackoverflow.com/a/49204815
has body: First you need to use self to denote your class instead of BeadBag inside your class. start from here. import random class BeadBag(object): def __init__(self, d): self.d = d self.words = d.keys() def draw(self): rand = random.choice(self.words) #self.d will be your dict. do whatever you want. def replace(self, color): cvalue = self.d[color] # rest of the code.
answers question: http://stackoverflow.com/q/49204684
type: Answer
score: 0

http://stackoverflow.com/comment/85454396
type: Comment
type: QuestionComment
has text: _Always_ include the version-agnostic `python` tag.
score: 0
comment on: http://stackoverflow.com/q/49225195

http://stackoverflow.com/q/49157831
has title: PyCharm Warnings and Expected Types: When To Care?
score: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
tagged with: pycharm
upvote count: 2
accepted answer: http://stackoverflow.com/a/49158890
has body: There are so many posts and questions about PyCharm and warnings and yet there seems to be very little consensus on when PyCharm is actually telling you something useful and when it's not, particularly regarding "expected types" warnings. Posting to the IntelliJ / PyCharm support boards often doesn't provide much of a roadmap, I'm finding. So I kept the title of this question a bit generic but I'll provide a very specific example with two different warnings, where fixing one leads to an error in execution. I'm hoping there is perhaps a general answer for this class of warning. Perhaps the answer is just that PyCharm isn't very good at this kind of detection. Context So consider here the following code: def load_agent(pacman, no_graphics): python_path_string = os.path.expandvars("$PYTHONPATH") if python_path_string.find(';') == -1: python_path_dirs = python_path_string.split(':') else: python_path_dirs = python_path_string.split(';') python_path_dirs.append('.') for module_dir in python_path_dirs: if not os.path.isdir(module_dir): continue module_names = [f for f in os.listdir(module_dir) if f.startswith('agents_')] There is more code in my for block but it's not relevant to the issue here. I'll also say my code does work. But my concern is whether or not I should ignore warnings about types. The Problems I'll start with the last line. If you try to do anything odd with what you pass startswith() at the Python REPL you are told: startswith first arg must be str or a tuple of str, not bytes Makes sense. So then why does PyCharm say the following about this line (the 'agents_' argument, specifically: Expected type 'Union[bytes, Tuple[bytes, ...]], got 'str' instead Further, line 9 above (python_path_dirs.append('.')) provides a PyCharm warning as well (for the '.', specifically): Expected type 'bytes' (matched generic type '_T'), got 'str' instead Solution Attempts For the issue on line 9, I know I can put a b in front of the string. Doing so however causes other probl…
tagged with: python
has answer: http://stackoverflow.com/a/49158890
type: AnsweredQuestion

http://stackoverflow.com/comment/85555196
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49276429
has text: I think this `timedelta(hours=1)` should work. Not sure about it

http://stackoverflow.com/a/52382965
has body: First check in your command prompt by entering Code !pip view pytesseract If it return some info that means you have it in your system , you also need to see the PIL module also. Now Coming on to your main Question: In order to pytesseact you need to be on pytesseract.pytesseract.tesseract_cmd path:- And more over you need to be on the path as well where the image is located. So what possibly you can do is as below import pytesseract import cv2 import os os.chdir(FullPath_where_your_"tesseract.exe" is located) image = cv2.imread('full_path_of_your_image') pytext = pytesseract.image_to_string(image) print(pytext) Do let me know in case its not working Happy learning !!
type: Answer
answers question: http://stackoverflow.com/q/49203212
score: 0

http://stackoverflow.com/comment/85293266
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49143239
type: Comment
has text: @johnashu, No, it is not the only way, as I tried to show. A tuple is perfectly fine as a dict key. And is generally preferable as you can simply use the immutable objects in question to build a key, you do not need to use string concat to build something new. Cheers.

http://stackoverflow.com/comment/85488721
type: Comment
has text: I tried now to put it before "html = browser.page_source", but that still downloads the values which load instantly, even though the browser at the time has already visibly loaded the right value.
comment on: http://stackoverflow.com/a/49225167
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85304041
comment on: http://stackoverflow.com/q/49149575
score: 0
type: Comment
type: QuestionComment
has text: did you do that like this `pip install opencv-contrib-python` or like this `pip install opencv-python`

http://stackoverflow.com/comment/85327627
type: QuestionComment
has text: I don't think there are any whitespaces. I'm reading the data from the table to create the form that allows for deletion. Here is the way the radio button is being formed: . I would think the whitespace would show there if there was any.
score: 0
comment on: http://stackoverflow.com/q/49160809
type: Comment

http://stackoverflow.com/comment/85614044
comment on: http://stackoverflow.com/a/49202105
type: Comment
score: 1
type: AnswerComment
has text: @vncs please share the answer you found, as I would like to understand why the answer above is **not** satisfactory.

http://stackoverflow.com/comment/105255114
type: AnswerComment
has text: great answer. I wanted to that outside a for-loop: just to let other know, the `code` is something like `active = cb_obj.active;glyph0.visible = active.includes(0);glyph1.visible = active.includes(1);`
score: 0
comment on: http://stackoverflow.com/a/49221388
type: Comment

http://stackoverflow.com/q/49224621
tagged with: python-2.7
upvote count: 0
score: -3
answer count: 1
downvote count: 3
has title: Python datetime.datetime.fromtimestamp() Bug
favorite count: 0
tagged with: datetime-format
type: Question
has comment: http://stackoverflow.com/comment/85453079
accepted answer: http://stackoverflow.com/a/49224730
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49224730
has comment: http://stackoverflow.com/comment/85452858
has comment: http://stackoverflow.com/comment/85453052
tagged with: python
has body: python version: 2.7.12 When I use the datetime.datetime.fromtimestamp() function to transfer the float timestamp to the date format, I found this function can transfer the two different timestamps into the same date. enter image description here
has comment: http://stackoverflow.com/comment/85452899
has comment: http://stackoverflow.com/comment/85452902

http://stackoverflow.com/q/49139458
has comment: http://stackoverflow.com/comment/85284316
has comment: http://stackoverflow.com/comment/85284315
tagged with: sql
score: 1
has comment: http://stackoverflow.com/comment/85284351
has comment: http://stackoverflow.com/comment/85325132
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85284418
upvote count: 1
has comment: http://stackoverflow.com/comment/85327910
has title: How can I remove characters from this created tuple? (Python and appJar)
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85327458
has comment: http://stackoverflow.com/comment/85284348
has comment: http://stackoverflow.com/comment/85319355
has answer: http://stackoverflow.com/a/49142657
type: UnansweredQuestion
has body: I created a tuple from an SQL statement and am trying to print it now in a text box but get some of the items having these {} symbols. EDIT: Items that have multiple words like {The Matrix} get the characters whilst singular items like Inception have no extra characters. This is an example of the results of an SQL statement: [('The Matrix',), ('Inception',), ('Happy Gilmore',), ('Big Daddy',), ('Love Actually',), ('Airplane!',), ('Hot Fuzz',), ('Wonder',), ('Pulp Fiction',)] resultmovies = c.fetchall() print(resultmovies) counter = 0 for item in resultmovies: program.infoBox("Your Movie list", (resultmovies[counter]), parent = None) counter += 1
tagged with: python

http://stackoverflow.com/comment/85418517
score: 0
comment on: http://stackoverflow.com/q/49197240
type: QuestionComment
has text: @juanpa.arrivillaga, I was just suggesting to use an image instead since it's harder to read the full traceback here in the comments.
type: Comment

http://stackoverflow.com/comment/88448412
comment on: http://stackoverflow.com/a/49138817
type: Comment
has text: If this answers solved your problem, could you select it as the correct answer please?
score: 0
type: AnswerComment

http://stackoverflow.com/a/49190207
downvote count: 0
has body: So, you have a list of coordinates (x, y) and a variance var. You could generate new coordinates in a random fashion like this: (x, y) --&gt; (random(x-var, x+var), random(y-var, y+var))
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49190016
type: Answer

http://stackoverflow.com/q/49179124
favorite count: 0
type: Question
tagged with: python-3.x
downvote count: 4
tagged with: python-internals
has title: Why/how do -1j and 0-1j become different strings?
upvote count: 5
linked to: http://stackoverflow.com/q/13387782
accepted answer: http://stackoverflow.com/a/49179241
has answer: http://stackoverflow.com/a/49179241
has comment: http://stackoverflow.com/comment/85363815
type: AnsweredQuestion
has body: Why and how are -1j and 0 - 1j turned into different strings? &gt;&gt;&gt; a = -1j &gt;&gt;&gt; b = 0 - 1j &gt;&gt;&gt; a (-0-1j) &gt;&gt;&gt; b -1j They're the same value of the same type: &gt;&gt;&gt; a == b True &gt;&gt;&gt; type(a), type(b), type(a) is type(b) (&lt;class 'complex'&gt;, &lt;class 'complex'&gt;, True) But both str and repr turn them into different strings: &gt;&gt;&gt; str(a), str(b) ('(-0-1j)', '-1j') &gt;&gt;&gt; repr(a), repr(b) ('(-0-1j)', '-1j') Why and how does that happen? Note: This is in Python 3.6.4. In Python 2.7.14 they're both turned into '-1j'.
duplicate of: http://stackoverflow.com/q/13387782
has comment: http://stackoverflow.com/comment/85363796
score: 1
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85364083

http://stackoverflow.com/comment/85412369
has text: @RickM. I gave a link to the MSDN docs. The link probably tells you have to do it in native C++ and in .NET scripting, and not how to do it in Python. But if so, you can then google for how to call those functions from Python. The answer will probably be PyWIn32/PyCOM, unless you want to, e.g., use IronPython instead of normal CPython, but I may be wrong.
type: Comment
comment on: http://stackoverflow.com/q/49203359
type: QuestionComment
score: 0

arrays
tags question: http://stackoverflow.com/q/49229900
tags question: http://stackoverflow.com/q/49157772
tags question: http://stackoverflow.com/q/49224051
tags question: http://stackoverflow.com/q/49259210
tag name: arrays
tags question: http://stackoverflow.com/q/49203629
tags question: http://stackoverflow.com/q/49176042
tags question: http://stackoverflow.com/q/49245963
tags question: http://stackoverflow.com/q/49121764
tags question: http://stackoverflow.com/q/49204280
tags question: http://stackoverflow.com/q/49222880
tags question: http://stackoverflow.com/q/49204115
tags question: http://stackoverflow.com/q/49135539
tags question: http://stackoverflow.com/q/49246127
tags question: http://stackoverflow.com/q/49186622
type: Tag
tags question: http://stackoverflow.com/q/49195747
tags question: http://stackoverflow.com/q/49206353
tags question: http://stackoverflow.com/q/49200272
tags question: http://stackoverflow.com/q/49174657
tags question: http://stackoverflow.com/q/49192901
tags question: http://stackoverflow.com/q/49135233
tags question: http://stackoverflow.com/q/49163970
tags question: http://stackoverflow.com/q/49178954
tags question: http://stackoverflow.com/q/49229610
tags question: http://stackoverflow.com/q/49237844
tags question: http://stackoverflow.com/q/49178977
tags question: http://stackoverflow.com/q/49218285
tags question: http://stackoverflow.com/q/49172770
tags question: http://stackoverflow.com/q/49217244
tags question: http://stackoverflow.com/q/49126624
tags question: http://stackoverflow.com/q/49177489
tags question: http://stackoverflow.com/q/49180779
tags question: http://stackoverflow.com/q/49180018
tags question: http://stackoverflow.com/q/49266464
tags question: http://stackoverflow.com/q/49262362
tags question: http://stackoverflow.com/q/49183806
tags question: http://stackoverflow.com/q/49193238
tags question: http://stackoverflow.com/q/49216299
tags question: http://stackoverflow.com/q/49186968
tags question: http://stackoverflow.com/q/49196429
tags question: http://stackoverflow.com/q/49279208
tags question: http://stackoverflow.com/q/49151683
tags question: http://stackoverflow.com/q/49239463
tags question: http://stackoverflow.com/q/49200619
tags question: http://stackoverflow.com/q/49204669
tags question: http://stackoverflow.com/q/49266385
tags question: http://stackoverflow.com/q/49225933
tags question: http://stackoverflow.com/q/49269042
tags question: http://stackoverflow.com/q/49161223
tags question: http://stackoverflow.com/q/49185444
tags question: http://stackoverflow.com/q/49244438
tags question: http://stackoverflow.com/q/49129604
tags question: http://stackoverflow.com/q/49135101
tags question: http://stackoverflow.com/q/49133317
tags question: http://stackoverflow.com/q/49148915
tags question: http://stackoverflow.com/q/49178952
tags question: http://stackoverflow.com/q/49202368
tags question: http://stackoverflow.com/q/49160714
tags question: http://stackoverflow.com/q/49234225
tags question: http://stackoverflow.com/q/49153905
tags question: http://stackoverflow.com/q/49140247
tags question: http://stackoverflow.com/q/49219335
tags question: http://stackoverflow.com/q/49218316
tags question: http://stackoverflow.com/q/49163512
tags question: http://stackoverflow.com/q/49224228
tags question: http://stackoverflow.com/q/49223198
tags question: http://stackoverflow.com/q/49238332
tags question: http://stackoverflow.com/q/49241502
tags question: http://stackoverflow.com/q/49203868
tags question: http://stackoverflow.com/q/49268333
tags question: http://stackoverflow.com/q/49157647
tags question: http://stackoverflow.com/q/49137698
tags question: http://stackoverflow.com/q/49244003
tags question: http://stackoverflow.com/q/49158565
tags question: http://stackoverflow.com/q/49182440
tags question: http://stackoverflow.com/q/49146201
tags question: http://stackoverflow.com/q/49164134
tags question: http://stackoverflow.com/q/49175416
tags question: http://stackoverflow.com/q/49181070

http://stackoverflow.com/q/49186703
has answer: http://stackoverflow.com/a/49186850
has answer: http://stackoverflow.com/a/49186819
answer count: 5
has title: Iterate through list starting at 3
tagged with: python
has answer: http://stackoverflow.com/a/49186812
has body: I want to assign 0-6 depend on the starting day. For example, if Wednesday is the starting day, I should set Wednesday to be 0 then Thursday to be 1, and Friday to be 2 etc... Here is what I have tried def date_manipulate(startday): #df['Month']=df.index.strftime("%B") temp_week=['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] week={} currentday=0 offset=temp_week.index(startday) for day in temp_week: if temp_week: pointer=temp_week.index(day)+offset%len(temp_week) if (pointer&gt;=8): pointer-=7 week[temp_week[pointer]]=currentday currentday+=1 else: break return week This do not return the right number(ie:Wednesday is 7), It's iterating 9 times instead of 7 for some reason. I also tried slicing index starting at position 3 [3:] and this will skip the first 2 which is also not what I want. Ultimately, I'm just trying to change the start day of the week to be what I define instead of the fix Sunday hence the function. Once the I get the function working, I will do some sort of if statement to loop through the default week and replace it with this new dictionary. Thanks!
has answer: http://stackoverflow.com/a/49186894
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49186878
downvote count: 0
upvote count: 1
score: 1
accepted answer: http://stackoverflow.com/a/49186812
has answer: http://stackoverflow.com/a/49186878
favorite count: 0
tagged with: python-3.x
type: Question

http://stackoverflow.com/q/49200946
upvote count: 0
has title: Python variable in css
has body: For a project, I'm trying to get an absolute position of an image (to a background image) in an HTML file while the calculation for the position is done in Python. This is what I passed into Flask with Python: return render_template('map.html',posx=pos_x, posy=pos_y) while pos_x and pos_y have values between 0 and 1260 (the height and width of the backround); and this is what i wrote in css and html .img-container { position: relative; } .img-container .top { position: absolute; top: posx; left: posy; z-index: 3 } &lt;/style&gt; &lt;td&gt; &lt;div class="img-container"&gt; &lt;img class="top" src="/static/images/map_test1.png" height="70" width="70" alt=""&gt; &lt;img class="bottom" src="/static/images/map_test.png" alt=""&gt; &lt;/div&gt;
tagged with: http://stackoverflow.com/tag/html
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/49201136
favorite count: 0
type: Question
tagged with: python
score: -1
tagged with: flask
tagged with: css
has answer: http://stackoverflow.com/a/49201136
type: AnsweredQuestion

http://stackoverflow.com/comment/85315629
has text: @Alasdair It can be an answer.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49153709

http://stackoverflow.com/q/49204847
has comment: http://stackoverflow.com/comment/85415124
has body: This code I've written does solves the hanoi problem when I have all the values in the source array. However, when it is being solved halfway with values in the helper array, it doesn't seem to work. How can I code it in such a way that it checks if the helper array has value and work from there. The recursive function currently runs once after source is empty # Source, helper, target are arrays. n = height def solve(n, source, helper, target): if n &gt; 0: # First we move a tower of size n-1 from the peg source to the helper peg. solve(n - 1, source, target, helper) if source: # Move the largest disk to the target target.append(source.pop()) # Move the tower from helper to target solve(n - 1, helper, source, target) source = [4] target = [] helper = [3,2,1] solve(len(source),source,helper,target) print source, helper, target
tagged with: python
type: Question
type: UnansweredQuestion
answer count: 1
has title: Tower of Hanoi solving with helper values
has comment: http://stackoverflow.com/comment/85415047
has answer: http://stackoverflow.com/a/49205142
score: 0

http://stackoverflow.com/q/49243582
has title: How to inherit scenePos from QGraphicsItem
type: Question
has comment: http://stackoverflow.com/comment/85492477
tagged with: python
has comment: http://stackoverflow.com/comment/85506306
linked to: http://stackoverflow.com/q/46382141
has body: I want to write a simple vector editor for myself. My ellips objects painting is in wrong coordinates. How to fix it? I guess, I should use QGraphicsEllipseItem, QGraphicsObject, etc. Is it correct thought? code is below main.py # -*- coding: utf-8 -*- from PyQt5 import QtWidgets from ui_mainwindow import Ui_MainWindow from PyQt5.QtCore import Qt from PyQt5.QtGui import QBrush, QPen from PyQt5.QtWidgets import QGraphicsScene, QGraphicsItem from random import randrange class mainCanvasScene(QGraphicsScene): figures = [] def __init__(self, parent=None): super(QGraphicsScene, self).__init__(parent) self.setSceneRect(0, 0, 800, 600) def getStartPos(self, mouseEvent): self.startx = mouseEvent.x() # mouseEvent.scenePos().x() self.starty = mouseEvent.y() # mouseEvent.scenePos().y() print('start pos:', self.startx, self.starty) def getEndPos(self, mouseEvent): self.pen = QPen(Qt.red, 3) self.brush = QBrush(Qt.gray) self.endx = mouseEvent.x() # mouseEvent.scenePos().x() self.endy = mouseEvent.y() # mouseEvent.scenePos().x() self.objectWidth = self.endx - self.startx self.objectHeight = self.endy - self.starty self.update() print('end pos:', self.endx, self.endy) print('size: ', self.objectWidth, self.objectHeight) print() def endPaint(self, mouseEvent): self.figures.append(self.addEllipse(self.startx, self.starty, self.objectWidth, self.objectHeight, self.pen, self.brush)) # Ui_MainWindow.listFigures.addItem(self.figures[-1]) class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): shapes = [] shapes.append(1) def __init__(self, parent=None): super(MainWindow, self).__init__() self.setupUi(self) self.toolBar.actionTriggered['QAction*'].connect(self.circle.click) self.view.scene = mainCanvasScene() self.view.setScene(self.view.scene) # mouse events self.view.mousePressEvent = self.view.scene.getStartPos self.view.mouseMoveEvent = self.view.scene.getEndPos self.view.mouseReleaseEvent = self.view.scene.endPaint def on_circle_released(self): self.shapes.append(self.view.scene.add…
tagged with: pyqt
score: 0
type: UnansweredQuestion
answer count: 1
tagged with: pyqt5
has answer: http://stackoverflow.com/a/49245415

http://stackoverflow.com/q/49255742
has body: PEP8 suggests no spaces around equal operators in function parameters. For example: Correct: def func(a=0): print('PEP8 compliant spacing') Incorrect: def func(a = 0): print('Invalid PEP8 spacing') PyCharm's auto-formatter fails to pick up incorrect spacing when typing is included. For example, PyCharm does not correctly format the following function: def func(a: int = 0): print('Invalid PEP8 spacing') To: def func(a: int=0): print('PEP8 compliant spacing') Has anyone found a way to have PyCharm's auto-formatter pick up spacing violations where typing is present?
has answer: http://stackoverflow.com/a/49255954
accepted answer: http://stackoverflow.com/a/49255954
possible better answer: http://stackoverflow.com/a/76513945
has title: PyCharm PEP8 Violation for typed parameters
favorite count: 0
type: Question
tagged with: python
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/76513945
type: AnsweredQuestion
answer count: 2
tagged with: pycharm
downvote count: 0
tagged with: pep8

http://stackoverflow.com/a/49177470
score: 0
has body: what about just: output=input[:3] output will contain the first three strings in input
type: Answer
answers question: http://stackoverflow.com/q/49163449

http://stackoverflow.com/a/49261504
has comment: http://stackoverflow.com/comment/85602398
has comment: http://stackoverflow.com/comment/85536444
has comment: http://stackoverflow.com/comment/85612594
answers question: http://stackoverflow.com/q/49261389
type: Answer
has comment: http://stackoverflow.com/comment/85527148
has comment: http://stackoverflow.com/comment/85609314
downvote count: 0
has comment: http://stackoverflow.com/comment/85601671
has body: Remove the newline on end: name = input("Q?").rstrip('\n') + "txt" Or do it like so: # thanks to Delirious Lettuce: f'{input("Filename?").rstrip('\n')}.txt'.replace("\n","") name = f'{input("Filename?")}.txt'.replace("\n","") print(name) What stumps though is, that the input() normally removes the return that closes its input. I wonder why you get one ... for me name = f'{input("Filename?")}.txt' works and name comes out as 'tata.txt' if I input 'tata' and hit return.
has comment: http://stackoverflow.com/comment/85601512
score: 3
upvote count: 3

http://stackoverflow.com/comment/85449271
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49222813
score: 0
has text: Thank you all! i learned from my mistake LOL

http://stackoverflow.com/q/49232844
accepted answer: http://stackoverflow.com/a/49234209
answer count: 4
has answer: http://stackoverflow.com/a/49237797
has answer: http://stackoverflow.com/a/49234209
type: Question
tagged with: perl
downvote count: 0
possible better answer: http://stackoverflow.com/a/49234008
upvote count: 1
has answer: http://stackoverflow.com/a/49233636
has answer: http://stackoverflow.com/a/49234008
favorite count: 0
has title: Delete a column from a tab separated file based on numerical content of column?
type: AnsweredQuestion
tagged with: bash
has body: I have a tab-separated file, see below: The first column contains the position number, 1-end and the rest have some frequency numbers. Position A B C D 1 117 0 1 0 2 4 0 0 16 3 0 5 11 0 4 0 0 0 5 5 0 15 0 0 6 100 0 108 0 7 0 0 147 0 I would like to reformat this file to have two columns, the first is the position column kept as is, and the second contains the highest frequency for each position. ideal output: Position HighFreq 1 117 2 16 3 11 4 5 5 15 6 108 7 147 what I have so far is a function that selects the highest number and prints: awk '{max=$1; for(i=2;i&lt;=NF; i++) {if($i&gt;max){max=$i;}};printf"%f\n",max}' file.tsv I'm trying to write a bash solution for this problem, but Perl/Python is most welcome!
tagged with: http://stackoverflow.com/tag/csv
score: 1
tagged with: python

http://stackoverflow.com/a/49245902
type: Answer
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
has body: You'll need shift + concat. Here's the concise version - def get_lags(df, n_lags): return pd.concat( [df] + [df.shift(i).add_suffix('_Lag{}'.format(i)) for i in n_lags], axis=1 ) And here's a more memory-friendly version, using a for loop - def get_lags(df, n_lags): df_list = [df] for i in n_lags: v = df.shift(i) v.columns = v.columns + '_Lag{}'.format(i) df_list.append(v) return pd.concat(df_list, axis=1)
accepted answer of: http://stackoverflow.com/q/49245827
answers question: http://stackoverflow.com/q/49245827

http://stackoverflow.com/q/49211957
has comment: http://stackoverflow.com/comment/85428440
upvote count: 2
downvote count: 0
answer count: 1
tagged with: keras
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49212166
tagged with: convolution
type: UnansweredQuestion
tagged with: python
score: 2
has title: How to calculate the number of parameters of 1d convolutional neural networks?
has body: I am referring to the implementation of "Text classification using CNN" on this link https://richliao.github.io/supervised/classification/2016/11/26/textclassifier-convolutional. Here in section "A simplified Convolutional", they have used the following layer of keras: Conv1D(128, 5, activation='relu') As per my understanding, no of parameters should be 5*100*128=64,000. But the model summary is showing 64,128 parameters. Could someone help me to understand where am i wrong in my calculation?

http://stackoverflow.com/comment/85548864
type: QuestionComment
type: Comment
has text: Then the second argument to `map` needs to be an iterable, but each time you iterate over it it should return the full argument set. Think a list of lists, for example
comment on: http://stackoverflow.com/q/49272622
score: 0

http://stackoverflow.com/a/49222465
accepted answer of: http://stackoverflow.com/q/49217965
has comment: http://stackoverflow.com/comment/85464105
downvote count: 0
answers question: http://stackoverflow.com/q/49217965
has body: A new record for any model can be created from python by calling the create function of that model. For example: move = self.env['account.move'].create({'field_1': value, 'field_2': value}) Make sure you pass all required fields in account .move
type: Answer
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/85569294
has text: hello Rakesh I have sent you the python file via rakesh.ram.ar@gmail.com please look at it assist thanks
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49274631
type: AnswerComment

http://stackoverflow.com/q/49255389
favorite count: 0
type: Question
has body: I want to be able to display the kivy logger live in a read only TextInput widget, is this possible? Currently I just have all of my widgets updating a TextInput widget with whatever information I give it, but this is a bit clunky and i'm not catching any of the kivy logging. Thanks in advance.
tagged with: textinput
type: UnansweredQuestion
tagged with: python
tagged with: kivy
tagged with: logging
has comment: http://stackoverflow.com/comment/85598300
has comment: http://stackoverflow.com/comment/129163617
answer count: 0
tagged with: widget
score: 1
downvote count: 0
upvote count: 1
has title: Kivy: View live log in app
has comment: http://stackoverflow.com/comment/85529419

http://stackoverflow.com/a/49209862
score: 2
answers question: http://stackoverflow.com/q/49209826
type: AcceptedAnswer
downvote count: 0
has body: Use boolean indexing: #create index by column Type df1 = df.set_index('Type') #compare column WW12 for not equal and get at least one True per rows df2 = df[df1.ne(df1['WW12'], 0).any(1).values] #if want compare by second column (first is Index here) #df2 = df[df1.ne(df1.iloc[:, 0], 0).any(1).values] If want compare second column only: df2 = df[df.iloc[:, 1:].ne(df.iloc[:, 1], axis=0).any(axis=1)] print (df2) Type WW12 WW13 WW14 WW15 WW16 WW17 WW18 \ 3 BB 1.457286 1.457286 1.457286 1.457286 1.457286 1.863929 1.863929 7 BB 1.863929 1.863929 1.863929 1.863929 2.878857 2.878857 2.878857 WW19 WW20 3 1.863929 1.863929 7 2.878857 2.878857 Explanation: Select second column by position: print (df.iloc[:, 1]) 0 1.999857e+00 1 2.400000e+07 2 1.424593e+03 3 1.457286e+00 4 2.400000e+07 5 2.400000e+07 6 1.424593e+03 7 1.863929e+00 8 2.400000e+07 Name: WW12, dtype: float64 Remove first column by positions and compare it by second column: print (df.iloc[:, 1:].ne(df.iloc[:, 1], axis=0)) WW12 WW13 WW14 WW15 WW16 WW17 WW18 WW19 WW20 0 False False False False False False False False False 1 False False False False False False False False False 2 False False False False False False False False False 3 False False False False False True True True True 4 False False False False False False False False False 5 False False False False False False False False False 6 False False False False False False False False False 7 False False False False True True True True True 8 False False False False False False False False False Compare by any for at least one True per row: print (df.iloc[:, 1:].ne(df.iloc[:, 1], axis=0).any(axis=1)) 0 False 1 False 2 False 3 True 4 False 5 False 6 False 7 True 8 False dtype: bool
has comment: http://stackoverflow.com/comment/85427004
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/49209826
has comment: http://stackoverflow.com/comment/85426913

http://stackoverflow.com/comment/85406821
type: Comment
type: AnswerComment
has text: image = Image.open("boi.jpg") crop = image.crop((0,0,200,200)) crop.save("boicropped.jpg") I do not think extension is required, also double quotes may be needed to open that file. This worked for me.
comment on: http://stackoverflow.com/a/49200645
score: 0

http://stackoverflow.com/comment/85372859
type: QuestionComment
score: 0
has text: This loads without issue in Py2.7 once you remove the trailing comma...
comment on: http://stackoverflow.com/q/49183289
type: Comment

http://stackoverflow.com/q/49163663
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85334284
has comment: http://stackoverflow.com/comment/85334301
has comment: http://stackoverflow.com/comment/85334296
downvote count: 0
has comment: http://stackoverflow.com/comment/85334245
upvote count: 1
has body: Very new here, and I am trying to modify some python code to normalize directory/file names for Windows using regular expression. I have searched and found lots of code examples, but haven’t quite figured out how to put it all together. This is what I am trying to accomplish: I need to remove all invalid Windows characters so directory/file names do not include: &lt; > : " / \ | ? * Windows also doesn’t seem to like spaces at the end of a directory/file name. Windows also doesn’t like periods at the end of directory names. So, I need to get rid of ellipsis without affecting the extension. To clarify, when I say ellipsis, I am referring to a pattern of three periods, and NOT the single unicode character “Horizontal Ellipsis (U+2026)”. I have researched and found multiple ways of doing individual parts of this, but I cannot see to get it all together and playing nice. return unicode(re.sub(r'[&lt;&gt;:"/\\|?*]', "", filename) This cleans up the names, but not the pattern of two or more periods. return unicode(re.sub(r'[&lt;&gt;:"/\\|?*.]', "", filename) This cleans up the names, but also affects the file extension. [^\w\-_\. ] This also seemed to be a viable alternative. It is a bit more restrictive than necessary, but I did find it easy to just keep adding specific characters I wanted to ignore. \.{2,} This is the piece I can’t seem to get to integrate with any of these methods. I understand that this should match two or more “.”, but leave a single “.” alone. But there are some situations where I “might” be left with a period at the end of a Windows directory name, which won’t work. .*[.](?!mp3$)[^.]*$ I searched and found this specific snippet, which looks promising to match/ignore a specific extension. In my case, I want .mp3 left alone. Maybe a different way to go about things. And I think it might eliminate a potential problem of having a period at the end of a directory name. Thank you for your time! Edit: Additional Information Added def normalize_filename(sel…
score: 1
has answer: http://stackoverflow.com/a/49163998
accepted answer: http://stackoverflow.com/a/49163998
answer count: 1
tagged with: python
tagged with: regex
favorite count: 0
type: Question
tagged with: substitution
has title: Reg.sub regex help in Python to normalize directory/file to play nice with Windows
has comment: http://stackoverflow.com/comment/85333354
has comment: http://stackoverflow.com/comment/85333374
tagged with: unicode
has comment: http://stackoverflow.com/comment/85366409
has comment: http://stackoverflow.com/comment/85366566

http://stackoverflow.com/comment/85540013
comment on: http://stackoverflow.com/q/49268117
score: 0
has text: Hold on, I'll spend a little more time
type: Comment
type: QuestionComment

serverless-framework
tag name: serverless-framework
type: Tag
tags question: http://stackoverflow.com/q/49148771

http://stackoverflow.com/comment/85411289
type: QuestionComment
has text: [no difference](https://tio.run/##bY1BCsMgFET3/xR/2YKb2DQtQk8iIppYIrQa1C5K8OwmhhC66GaYGYY30zeN3tFSon8b6dNogoz@E3ojB9snfODcsJmyC2nZNZOu@tvq7zmDki8b64RTgq0AfeSGYCcAnInJDAcINVtFMfz/xbXgSuDTB1RoHe74vDW6NvtBBpiCden0wz@XsgA)
type: Comment
score: 1
comment on: http://stackoverflow.com/q/49202895

http://stackoverflow.com/comment/85469723
comment on: http://stackoverflow.com/a/49231635
score: 0
type: AnswerComment
has text: Oh that's because I want to loop through the pages.
type: Comment

http://stackoverflow.com/comment/85269605
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49132433
score: 2
has text: I am curious to know how you've gotten to this point.

http://stackoverflow.com/a/72418300
answers question: http://stackoverflow.com/q/49123132
type: Answer
score: 0
has body: The pandas documentation for ExcelWriter suggests that the "writer should be used as a context manager". Here's an example of such usage to write multiple dataframe objects to an Excel file: import pandas as pd dfList = [pd.DataFrame([[i + 1, i + 2, i + 3],['a', 'b', 'c']], columns=['col1', 'col2', 'col3']) for i in range(5)] with pd.ExcelWriter('Sample.xlsx') as writer: for i, df in enumerate(dfList): df.to_excel(writer, sheet_name=f'Sheet {i}', index=False)

http://stackoverflow.com/q/49226287
type: UnansweredQuestion
answer count: 1
has body: How to use MxNet metrics api to calculate accuracy of the multiclass logistic regression classifier with vector labels? Here is an example for labels: Class1: [1,0,0,0] Class2: [0,1,0,0] Class3: [0,0,1,0] Class4: [0,0,0,1] The naive way to use this function would produce wrong result as argmax will squash the model output into an index having max probability value def evaluate_accuracy(data_iterator, ctx, net): acc = mx.metric.Accuracy() for i, (data, label) in enumerate(data_iterator): data = data.as_in_context(ctx) label = label.as_in_context(ctx) out = net(data) p = nd.argmax(out, axis=1) acc.update(preds=p, labels=label) return acc.get()[1] My current solution is little hacky: def evaluate_accuracy(data_iterator, ctx, net): acc = mx.metric.Accuracy() for i, (data, label) in enumerate(data_iterator): data = data.as_in_context(ctx) label = label.as_in_context(ctx) out = net(data) p = nd.argmax(out, axis=1) l = nd.argmax(label, axis=1) acc.update(preds=p, labels=l) return acc.get()[1]
has title: MxNet metrics API to compute accuracy for multiclass logistic regression with vector labels
tagged with: python
score: 0
tagged with: mxnet
linked to: http://stackoverflow.com/q/49217210
linked to: http://stackoverflow.com/q/45798125
tagged with: logistic-regression
tagged with: multiclass-classification
type: Question
has answer: http://stackoverflow.com/a/49242277

pythonnet
tags question: http://stackoverflow.com/q/49146308
type: Tag
tag name: pythonnet

http://stackoverflow.com/comment/85433709
type: QuestionComment
has text: Have you seen [this](https://stackoverflow.com/a/35534047/1994235)? It shows two way communication between the main thread and another thread which is similar to what you are after.
score: 0
comment on: http://stackoverflow.com/q/49210097
type: Comment

http://stackoverflow.com/q/49178618
has comment: http://stackoverflow.com/comment/85362734
accepted answer: http://stackoverflow.com/a/49180204
has comment: http://stackoverflow.com/comment/85362662
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85365766
answer count: 1
tagged with: machine-learning
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85364292
has answer: http://stackoverflow.com/a/49180204
has comment: http://stackoverflow.com/comment/85364123
downvote count: 1
has comment: http://stackoverflow.com/comment/85362894
type: AnsweredQuestion
score: 0
has body: First I want to generate a plot, colorized by how close the average data is to the goal. (the real program is a machine learning algorithm trying to learn weights). I want to generate a histogram for each data point in the final plot, but I can't seem to generate the plots independently. Any help would be greatly appreciated. import matplotlib.pyplot as plt import numpy as np def generateData(goal): x=[_ for _ in range(20)] y=[10+np.random.exponential()*5 for _ in range(100)] return x,y def drawHistogram(data,nBins): plt.figure(2) plt.hist(diffs,nBins) plt.draw() plt.show() sweep=np.linspace(10,20,4) for goal in sweep: for gw2 in sweep: diffs=[] for i in range(10): data=generateData(goal) diffs.append(goal-np.mean(data[1])) #generate plot plt.figure(1) clr=(abs(np.mean(diffs))/goal,0,0) plt.plot([goal], [gw2], marker="s", mew='1', ms='35', color=clr) drawHistogram(diffs,5) ##Comment this line out to see what the final graph should look like plt.figure(1) plt.draw() plt.show()
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85362932
has comment: http://stackoverflow.com/comment/85365166
has title: Multiple Figures in Matplotlib - Nested Loop

http://stackoverflow.com/comment/85378433
has text: Hey bro, thank you but It was the first thing I did, but it also not work correctly... It's loading but never-ending and my computer start to brake
comment on: http://stackoverflow.com/a/49185740
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49247894
favorite count: 0
tagged with: recursion
has title: recursive function for extract elements from deep nested lists/tuples
type: Question
has answer: http://stackoverflow.com/a/49247975
has body: I want to write a function that extracts elements from deep nested tuples and lists, say I have something like this l = ('THIS', [('THAT', ['a', 'b']), 'c', ('THAT', ['d', 'e', 'f'])]) And I want a flat list without 'THIS' and 'THAT': list = ['a', 'b', 'c', 'd', 'e', 'f'] Here's what I have so far: def extract(List): global terms terms = [] for i in word: if type(i) is not str: extract(i) else: if i is not "THIS" and i is not "THAT": terms.append(i) return terms But I keep getting list = ['d', 'e', 'f'], it looks like the terms = [] is set again after looping to 'c'.
has answer: http://stackoverflow.com/a/49247980
has comment: http://stackoverflow.com/comment/85499882
tagged with: python
type: UnansweredQuestion
tagged with: python-3.x
answer count: 4
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/49248005
downvote count: 0
tagged with: nested
has answer: http://stackoverflow.com/a/49248211

http://stackoverflow.com/comment/85459285
has text: Also, "delete duplicate elements" is misleading—sets can't have duplicate elements; there's only going to be one `'c'` in the output, no matter how you do it.
comment on: http://stackoverflow.com/q/49227864
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49223976
tagged with: initializer
downvote count: 0
has title: Default Initialization for Tensorflow LSTM states and weights?
tagged with: recurrent-neural-network
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/49225281
answer count: 2
has answer: http://stackoverflow.com/a/49225281
accepted answer: http://stackoverflow.com/a/49254630
tagged with: python
has answer: http://stackoverflow.com/a/49254630
tagged with: lstm
type: AnsweredQuestion
has body: I am using the LSTM cell in Tensorflow. lstm_cell = tf.contrib.rnn.BasicLSTMCell(lstm_units) I was wondering how the weights and states are initialized or rather what the default initializer is for LSTM cells (states and weights) in Tensorflow? And is there an easy way to manually set an Initializer? Note: For tf.get_variable() the glorot_uniform_initializer is used as far as I could find out from the documentation.
score: 1

http://stackoverflow.com/comment/104684746
type: AnswerComment
comment on: http://stackoverflow.com/a/55237888
score: 0
has text: lovely for a short solution.
type: Comment

http://stackoverflow.com/comment/85384639
score: 1
has text: So I developed a work-around: `elem = driver.find_element_by_class_name("lnkClassInfo") print (elem.get_attribute("href")) elem_url = elem.get_attribute("href") driver.get(elem_url) driver.find_element_by_class_name("btn-gradient").click()` Doing so leads the driver to fully open the overlay in the same tab, thus allowing me to interact with it. Still curious about how to interact with the overlay though.
type: Comment
comment on: http://stackoverflow.com/a/49177115
type: AnswerComment

http://stackoverflow.com/q/49266070
score: 3
upvote count: 3
has title: Comparing Power Law with other Distributions
answer count: 1
favorite count: 0
type: Question
has body: I'm using Jeff Alstott's Python powerlaw package to try fitting my data to a Power Law. Jeff's package is based on the paper by Clauset et al which discusses the Powerlaw. First, some details on my data: It is discrete (word count data); It is heavily skewed to the left (high skewness) It is Leptokurtic (excess kurtosis is greater than 10) What I have done so far df_data is my Dataframe, where word_count is a Series containing word count data for around 1000 word tokens. First I've generated a fit object: fit = powerlaw.Fit(data=df_data.word_count, discrete=True) Next, I compare the powerlaw distribution for my data against other distributions - namely, lognormal, exponential, lognormal_positive, stretched_exponential and truncated_powerlaw, with the fit.distribution_compare(distribution_one, distribution_two) method. As a result of the distribution_compare method, I've obtained the following (r,p) tuples for each of the comparisons: fit.distribution_compare('power_law', 'lognormal') = (0.35617607052907196, 0.5346696007) fit.distribution_compare('power_law', 'exponential') = (397.3832646921206, 5.3999952097178692e-06) fit.distribution_compare('power_law', 'lognormal_positive') = (27.82736434863289, 4.2257378698322223e-07) fit.distribution_compare('power_law', 'stretched_exponential') = (1.37624682020371, 0.2974292837452046) fit.distribution_compare('power_law', 'truncated_power_law') =(-0.0038373682383605, 0.83159372694621) From the powerlaw documentation: R : float The loglikelihood ratio of the two sets of likelihoods. If positive, the first set of likelihoods is more likely (and so the probability distribution that produced them is a better fit to the data). If negative, the reverse is true. p : float The significance of the sign of R. If below a critical value (typically .05) the sign of R is taken to be significant. If above the critical value the sign of R is taken to be due to statistical fluctuations. From the comparison results between powerlaw, exponential…
tagged with: power-law
downvote count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/49269095
has answer: http://stackoverflow.com/a/49269095
type: AnsweredQuestion

http://stackoverflow.com/q/49192901
answer count: 3
has answer: http://stackoverflow.com/a/49200243
upvote count: 0
tagged with: arrays
has body: size = len(home) total_score = [] score = [] for counter in range(0, size): print("Enter the Scores for", name[counter],":") score[0].append = int(input("Judge 1: ")) score[0] = validate(0,10,score[0]) score[1] = int(input("Judge 2: ")) score[1] = validate(0,10,score[1]) when I run the above code i get the following error and I have tried everything to correct it. score[0].append = int(input("Judge 1: ")) IndexError: list index out of range
has answer: http://stackoverflow.com/a/49193071
downvote count: 1
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49192992
has comment: http://stackoverflow.com/comment/85390547
has title: Index out of range for an array

http://stackoverflow.com/comment/85297633
comment on: http://stackoverflow.com/q/49146308
score: 0
has text: hmm not a best solution but why not make a console program to wrap your dll and then call console program from python ?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85355772
type: AnswerComment
comment on: http://stackoverflow.com/a/49174902
type: Comment
has text: It's one way, I'm sure it's not the only one though!
score: 0

http://stackoverflow.com/comment/85493009
score: 1
type: Comment
has text: `itertools.product`
type: QuestionComment
comment on: http://stackoverflow.com/q/49244438

http://stackoverflow.com/comment/85497019
has text: When you say that the 6th element of of `data` is a directory, could you clarify what this could be? To clarify things on my end, suppose `tone` and `ttwo` are already two lists containing lists of strings, as above, and `tline` is a list containing lists of numbers, but there are over a thousand related lists in each one. I have to get these all into `data` in such a way that the assert statement will find the 6th element in all three lists, without changing the element which is in that position in any of them.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49246151

http://stackoverflow.com/q/49218905
has body: I'm looking for help to speed up my code, the purpose of the code is to generate high res images from sensor data, based on the distance and angle between the sensor and the pixels in the picture. I have data from 100 sensors at more than 200 different positions of those sensors (they are moving around in the picture). For my computer at this time it takes ~90seconds to do this for just 50 sensors at one positions - the 200 positions takes to long... Please give suggestions on how to improve this (also if I have taken a strange approach). import numpy as np xstart=-200 xstop=20 xstep=0.05 ystart=-1500 ystop=-1300 ystep=0.05 deg_limit = 10 rad_limit=np.radians(deg_limit) Xrange=np.arange(xstart,xstop,xstep) Yrange=np.arange(ystart,ystop,ystep) sensor1=np.zeros((3)) sensor1[0]=-100 sensor1[1]=-1400 sensor1[2]=4 sensor2=sensor1.copy()+[1,0,0] sensor3=sensor1.copy()+[0,1,0] sensor4=sensor1.copy()+[2,0,0] sensor5=sensor1.copy()+[0,2,0] sensor6=sensor1.copy()+[3,0,0] sensor7=sensor1.copy()+[0,3,0] sensor8=sensor1.copy()+[0,4,0] sensor9=sensor1.copy()+[4,0,0] sensor10=sensor1.copy()+[0,5,0] sensors=[sensor1,sensor2,sensor3,sensor4,sensor5,sensor6,sensor7,sensor8,sensor9,sensor10] vector=np.zeros((3)) image=np.zeros((len(Yrange),len(Xrange))) distanceimage=image.copy() angleimage=image.copy() testvector=[1/2,1/3,-1/10]#np.cross((sensor2-sensor1),(sensor3-sensor1)) testvector=testvector/np.sqrt(testvector[0]**2+testvector[1]**2+testvector[2]**2) for _ in range(0,5): #outer loop for reading the sensorpositions and sampled values #inner loop for looping through the sensprs for sensor in sensors: xdist=Xrange-sensor[0] ydist=(Yrange-sensor[1]) zdist=0-sensor[2] #Here should be a requirement that checks for the angle from #the point to the pixel and only adds to the image if the angle #within a certain range distanceimage=np.sqrt((xdist*xdist)+(ydist*ydist)[:,np.newaxis]+zdist*zdist) angleimage=(np.arccos((testvector[0]*xdist+testvector[1]*ydist[:,np.newaxis])/(distanceimage))) …
has comment: http://stackoverflow.com/comment/85444199
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85448921
answer count: 0
type: UnansweredQuestion
has title: Efficient distance calculations for big meshgrid Python
tagged with: python
score: 0

http://stackoverflow.com/comment/85352845
type: Comment
type: QuestionComment
has text: can you provide the code that does not work and a trceback of the errors?
comment on: http://stackoverflow.com/q/49173955
score: 4

http://stackoverflow.com/comment/85345567
type: QuestionComment
comment on: http://stackoverflow.com/q/49169824
score: 0
has text: Why all of the downvotes?
type: Comment

http://stackoverflow.com/comment/85507638
type: AnswerComment
comment on: http://stackoverflow.com/a/49251754
type: Comment
has text: Oh figured it out. Forgot to use process. Thanks for your help
score: 0

http://stackoverflow.com/a/49272441
type: Answer
has comment: http://stackoverflow.com/comment/85548516
has comment: http://stackoverflow.com/comment/85547914
downvote count: 0
upvote count: 1
score: 1
has body: No, it's not. It seems like you are looking to use list comprehension syntax to single-linify multiple method calls. You can't do this. Instead, what you can do is aggregate your list elements into a dataframe and append in one go. It is also inefficient to df.append within a loop versus building a dataframe from list of lists and appending just once. df = df.append(pd.DataFrame(pos, columns=player_df.columns)) This assumes pos is a list of lists with columns aligned with df. If you need to add an extra column "in one line", try this: df = df.append(pd.DataFrame(pos, columns=player_df.columns)).assign(newcol=1)
has comment: http://stackoverflow.com/comment/85550257
answers question: http://stackoverflow.com/q/49272364

http://stackoverflow.com/comment/85368820
comment on: http://stackoverflow.com/q/49180047
type: Comment
type: QuestionComment
has text: Hmm... I also noticed it that the run times are longer but again there's no documentation for it.
score: 0

http://stackoverflow.com/q/49241733
tagged with: algorithm
tagged with: cluster-analysis
has body: The intention is to merge clusters which have similarity higher than the Jaccard similarity based on pairwise comparison of cluster representative. My logic here is that because the child nodes are all under the parent node for a cluster, it means that the parent node is somewhat like a representative of the cluster.
tagged with: machine-learning
type: UnansweredQuestion
tagged with: python
has title: Can the parent nodes of clusters formed using disjoint set forest be used as cluster representative?
answer count: 1
has answer: http://stackoverflow.com/a/49294793
score: 0
tagged with: data-mining
type: Question

http://stackoverflow.com/comment/85271895
type: AnswerComment
has text: @ttyridal indeed, edited. re. 2nd: none that I know of.
comment on: http://stackoverflow.com/a/49133246
type: Comment
score: 0

http://stackoverflow.com/comment/85428309
type: QuestionComment
comment on: http://stackoverflow.com/q/49211791
has text: yes, I forked the exact same data as well. I prefer to have a single json file to be consistent with the original project that I forked and because I need to start from it as base for my work
score: 0
type: Comment

http://stackoverflow.com/q/49218390
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/55237888
tagged with: python-3.5
has answer: http://stackoverflow.com/a/61338036
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/49218864
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/51207656
type: Question
has answer: http://stackoverflow.com/a/51207656
has answer: http://stackoverflow.com/a/54080869
has body: I am trying to use the library secrets on Python 3.5 on Ubuntu 16.04. It does not come with the python installation and I am not able to install it through pip. Is there a way to get it to work on python 3.5?
answer count: 5
tagged with: python
tagged with: cryptography
has comment: http://stackoverflow.com/comment/85440600
has title: Unable to install 'secrets' on python 3.5 (pip, ubuntu 3.5)
upvote count: 11
score: 11
possible better answer: http://stackoverflow.com/a/55237888

http://stackoverflow.com/comment/85296314
has text: I see you calling pickle.dump, but you never called pickle.load -- could that be the issue?
comment on: http://stackoverflow.com/q/49145328
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49127808
has body: I am trying to install ibm_db module for python using pip install but getting below error. " C:\Users\n087514>pip install ibm_db Collecting ibm-db Using cached https://repo-man.aetna.com/nexus/repository/ae-pypi-group/packages/f8/6f/5f8186cb31021409235a948be5e29d77761ef92747a101360003747c4105/ibm_db-2.0.8.tar.gz Installing collected packages: ibm-db Running setup.py install for ibm-db ... error Complete output from command "c:\program files (x86)\python 3.5\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\n087514\AppData\Local\Temp\pip-build-_w1_snzp\ibm-db\setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record C:\Users\n087514\AppData\Local\Temp\pip-g_xrj1vq-record\install-record.txt --single-version-externally-managed --compile: Traceback (most recent call last): File "", line 1, in File "C:\Users\n087514\AppData\Local\Temp\pip-build-_w1_snzp\ibm-db\setup.py", line 17, in os.rename('tests','test_2') FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'tests' -> 'test_2' ---------------------------------------- Command ""c:\program files (x86)\python 3.5\python.exe" -u -c "import setuptools, tokenize;file='C:\Users\n087514\AppData\Local\Temp\pip-build-_w1_snzp\ibm-db\setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record C:\Users\n087514\AppData\Local\Temp\pip-g_xrj1vq-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\n087514\AppData\Local\Temp\pip-build-_w1_snzp\ibm-db\" Anyone has any idea what needs to be done? Thanks in advance!
tagged with: pip
tagged with: db2
tagged with: python
has answer: http://stackoverflow.com/a/49128557
upvote count: 0
downvote count: 2
answer count: 1
tagged with: python-module
favorite count: 0
has title: Unable to get Python "ibm_db" module using pip install
type: Question
type: UnansweredQuestion
score: -2

http://stackoverflow.com/a/49205515
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49192536
accepted answer of: http://stackoverflow.com/q/49192536
type: Answer
has body: Although I'm not sure Caffe might output an error if you don't define all those four methods, you will definitely need Setup and Forward: Setup: exactly what you've said. For example, in my Accuracy layers, I usually save some metrics (true and false positives/negatives, f-scores) for my whole testing set and the softmax probabilities of each sample, in case I want to combine/fuse different networks/methods later. Here is where I open the file where I'll write those information; Forward: here is where you will calculate your accuracy per se, comparing the prediction with the label for each sample in your batch. Usually this layer will have two inputs, the label (ground truth that will be probably feed by the data/input layer) and a layer that outputs the prediction/scores/probabilities of each sample in your batch per class (I usually use a SoftMax Layer); Reshape and Backward: don't worry about these. You won't need to worry about the backward pass nor reshape your blob. Here is an example of an accuracy layer: # Remark: This class is designed for a binary problem with classes '0' and '1' # Saving this file as accuracyLayer.py import caffe TRAIN = 0 TEST = 1 class Accuracy_Layer(caffe.Layer): #Setup method def setup(self, bottom, top): #We want two bottom blobs, the labels and the predictions if len(bottom) != 2: raise Exception("Wrong number of bottom blobs (prediction and label)") #Initialize some attributes self.correctPredictions = 0.0 self.totalImgs = 0 #Forward method def forward(self, bottom, top): #The order of these depends on the prototxt definition predictions = bottom[0].data labels = bottom[1].data self.totalImgs += len(labels) for i in range(len(labels)): #len(labels) is equal to the batch size pred = predictions[i] #pred is a tuple with the normalized probability #of a sample i.r.t. two classes lab = labels[i] if pred[0] &gt; pred[1]: #this means it was predicted as class 0 if lab == 0.0: self.correctPredictions += 1.0 else: #else, predicted as class…
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49147353
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: mysql
tagged with: scrapy
tagged with: scrapy-pipeline
type: Question
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/49150259
accepted answer: http://stackoverflow.com/a/49150259
has body: I'm scraping a website for its external links using scrapy and storing those links to MYSQl db. i used a snippet in my code. when i run spider i see the links being scrapped but gives error 2018-03-07 13:33:27 [scrapy.log] ERROR: not all arguments converted during string formatting It is clear that links are not being converted to string due to the dots,slashes, commas and dash. So how can i pass the links and store them without error.TIA pipeline.py from scrapy import log from twisted.enterprise import adbapi import MySQLdb.cursors class MySQLStorePipeline(object): def __init__(self): self.dbpool = adbapi.ConnectionPool('MySQLdb', db='usalogic_testdb', user='root', passwd='1234', cursorclass=MySQLdb.cursors.DictCursor, charset='utf8', use_unicode=True) def process_item(self, item, spider): # run db query in thread pool query = self.dbpool.runInteraction(self._conditional_insert, item) query.addErrback(self.handle_error) return item def _conditional_insert(self, tx, item): # create record if doesn't exist. # all this block run on it's own thread tx.execute("select * from test where link = %s", (item['link'], )) result = tx.fetchone() if result: log.msg("Item already stored in db: %s" % item, level=log.DEBUG) else: tx.execute(\ "insert into test (link) " "values (%s)", (item['link']) ) log.msg("Item stored in db: %s" % item, level=log.DEBUG) def handle_error(self, e): log.err(e) When when given run command the ITEMS.py class CollectUrlItem(scrapy.Item): link = scrapy.Field() settings.py ITEM_PIPELINES = { 'rvca4.pipelines.MySQLStorePipeline': 800, }
has title: Scrapy-MySQL pipeline does not save data

http://stackoverflow.com/q/49224425
tagged with: tensorflow
favorite count: 0
type: Question
has title: TensorFlow-GPU causes python crash
has body: I've some trouble with tensorflow-gpu 1.6.0. I'm doing the final assignment of "bayesan methods in machine learning" class on coursera. https://www.coursera.org/learn/bayesian-methods-in-machine-learning When I run the code on GPU with tensorflow-gpu (pip install tensorflow-gpu), python crashes, but if I run the same code on CPU with the standard tensorflow (pip isntall tensorflow), the code runs fast without errors or crashes. Obviously I unistalled the gpu version before I installed the standard version and vice versa. About the python crash, the debugger shows this message: Unhandled exception at 0x00007FFDAB4DB79E (ucrtbase.dll) in python.exe This is the starter code: import numpy as np import matplotlib.pyplot as plt from IPython.display import clear_output import tensorflow as tf import GPy import GPyOpt import keras from keras.layers import Input, Dense, Lambda, InputLayer, concatenate, Activation, Flatten, Reshape from keras.layers.normalization import BatchNormalization from keras.layers.convolutional import Conv2D, Deconv2D from keras.losses import MSE from keras.models import Model, Sequential from keras import backend as K from keras import metrics from keras.datasets import mnist from keras.utils import np_utils from tensorflow.python.framework import ops from tensorflow.python.framework import dtypes import utils import os %matplotlib inline sess = tf.InteractiveSession() K.set_session(sess) latent_size = 8 vae, encoder, decoder = utils.create_vae(batch_size=128, latent=latent_size) sess.run(tf.global_variables_initializer()) vae.load_weights('CelebA_VAE_small_8.h5') K.set_learning_phase(False) latent_placeholder = tf.placeholder(tf.float32, (1, latent_size)) decode = decoder(latent_placeholder) This code causes python crash when is executed on GPU but NOT on CPU: plt.figure(figsize=(10, 10)) for i in range(25): plt.subplot(5, 5, i+1) image = sess.run(decode, feed_dict={latent_placeholder: np.random.normal([0]*latent_size,[1]*latent_size)[:, np.newaxis…
tagged with: python
has comment: http://stackoverflow.com/comment/85477599
has comment: http://stackoverflow.com/comment/85457251
has comment: http://stackoverflow.com/comment/85478322
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49237601
score: 3
has answer: http://stackoverflow.com/a/49237601
upvote count: 3
answer count: 1
downvote count: 0
tagged with: machine-learning
tagged with: keras

http://stackoverflow.com/a/49253760
downvote count: 0
has comment: http://stackoverflow.com/comment/85517805
has body: You are trying to get a set with a set as an element. In the line final_set = {temp_set,nb_maximal}. Set elements should be hashable, but sets are not hashable. You can return a tuple or a list instead: final_list = [temp_set, nb_maximal]. In fact, just putting return temp_set, nb_maximal will implicitly build a tuple. I think is the way to go, more explicit return type, more clean, etc. For more information about hashability, there are plenty of SO questions, for example: what-do-you-mean-by-hashable-in-python By the way, it seems you have a bug, since 'Elfriede' and 'Clovis' in your example are involved in 4 activities, and your function is returning 'Bachir' and 'Amina' which are involved in 2 activities. Here you have an alternative implementation of your function: def suractifs(names, group): # build a list of tuples with the name in the first coordinate and # the number of appearances in activities in the second coordinate act_list= [(n, len([a for a, s in group.iteritems() if i in s])) for i, n in names.iteritems()] # sort the list in decresing order of the activities act_list.sort(key=lambda t : -t[1]) # get one of the names with most activities a = act_list[0] # return only the filtered list of names that have the maximum #number of activities return set( t[0] for t in act_list if t[1] == a[1]), a[1] An alternative implementation using Counter as Pitto suggested: from collections import Counter def suractifs3(names, group): names_in_acts = sum( (list(s) for s in group.itervalues()), []) act_list = Counter(names_in_acts).most_common() act_list.sort(key=lambda t : -t[1]) a = act_list[0] return set(names[t[0]] for t in act_list if t[1] == a[1]), a[1]
score: 1
answers question: http://stackoverflow.com/q/49253612
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/85519672
has comment: http://stackoverflow.com/comment/85556031

http://stackoverflow.com/comment/85305860
comment on: http://stackoverflow.com/q/49147413
type: Comment
has text: I did and got fps ~28-30 on OSX...
score: 0
type: QuestionComment

http://stackoverflow.com/q/49274295
tagged with: visualization
has title: How to visualize the text analysis using CNN and tensorflow
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49276128
has answer: http://stackoverflow.com/a/49353040
has body: I am new to tensorflow, I am using CNN model descrined by http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/ I am getting around 60% accuracy for 5 class and 80% accuracy for 2 class classification Now I want to visualize which word impact most to a particular classification, can anybody tell me how to do it
tagged with: python
tagged with: text
score: 0
answer count: 2
tagged with: conv-neural-network

http://stackoverflow.com/comment/85332945
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49163626
type: Comment
has text: Nice! I didn't know about the `repeat` function for cloning out records. However in my original example the Projects field is string valued, so that e.g. the first record's value would be `'ProjectA, ProjectB'`. Would you just create a shadow field that splits this string out into a list value, and then apply the above approach?

http://stackoverflow.com/a/49193754
type: Answer
has body: dict = {'attmlk1': 'CWT', 'attmmma1': 'CWT', 'attanna1': 'CWT', 'attmsl1': 'RNJ', 'kyqang1': 'RNJ'} def f(x): x = str(x) s = dict[x] return s value_list = ['attmlk1','attctl1'] df.loc[df.CREATEDBY.isin(value_list), 'Vendor'] = df.loc[df.CREATEDBY.isin(value_list), 'CREATEDBY'] df['Vendor'] = df['Vendor'].apply(lambda x: f(x))
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85392123
answers question: http://stackoverflow.com/q/49154800
accepted answer of: http://stackoverflow.com/q/49154800
has comment: http://stackoverflow.com/comment/85396310
has comment: http://stackoverflow.com/comment/85396713

http://stackoverflow.com/comment/85444124
comment on: http://stackoverflow.com/q/49220237
has text: Can you post a bit more code so we can make this reproducable
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85361061
score: 0
has text: Do you see the `{}` in the database, when running a `select` from the console (`sqlite3 Database.db`)?
type: Comment
comment on: http://stackoverflow.com/q/49177369
type: QuestionComment

http://stackoverflow.com/comment/85466148
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49231405
type: Comment
has text: Doesn't your experiment demonstrate that the answer is "yes"? Note that those characters can also refer to the start and end of *lines*, in multiline mode.

http://stackoverflow.com/q/49193128
has title: Selenium does not work on ubuntu virtual machine
tagged with: selenium-webdriver
tagged with: python-3.x
score: 0
has comment: http://stackoverflow.com/comment/85398847
type: UnansweredQuestion
answer count: 1
tagged with: selenium
type: Question
has body: I'm trying to run the following code on virtual machine with ubuntu 16.04: import time import time from selenium import webdriver driver = webdriver.Chrome('./chromedriver') But an error is returned, what do I do wrong? Error: Traceback (most recent call last): File "test_driver.py", line 4, in &gt; &lt;module&gt; &gt; driver = webdriver.Chrome('./chromedriver') # Optional argument, if not specified will search path. File &gt; "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/chrome/webdriver.py", &gt; line 68, in __init__ &gt; self.service.start() File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/common/service.py", &gt; line 76, in start &gt; stdin=PIPE) File "/usr/lib/python3.5/subprocess.py", line 947, in __init__ &gt; restore_signals, start_new_session) File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child &gt; raise child_exception_type(errno_num, err_msg) OSError: [Errno 8] Exec format error I'm using python 3.5.2 and selenium-standalone@6.12.0
tagged with: ubuntu-16.04
has answer: http://stackoverflow.com/a/49193337
tagged with: python

http://stackoverflow.com/comment/85375574
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49184828
has text: OK, so **again** what is the problem *exactly*? Because now it sounds like the issue is getting user input...
score: 0

http://stackoverflow.com/q/49138119
possible better answer: http://stackoverflow.com/a/49138285
downvote count: 0
tagged with: dataframe
tagged with: python
has title: Pandas deleting rows in order
has body: Given a particular df: ID Text 1 abc 1 xyz 2 xyz 2 abc 3 xyz 3 abc 3 ijk 4 xyz I want to apply condition where: Grouping by ID, if abc exists then delete row with xyz. The outcome would be: ID Text 1 abc 2 abc 3 abc 3 ijk 4 xyz Usually I would group them by Id and apply np.where(...). However, I don't think this approach would work for this case since it's based on rows. Many thanks!
score: 2
type: AnsweredQuestion
tagged with: pandas
has answer: http://stackoverflow.com/a/49138285
has answer: http://stackoverflow.com/a/49138226
has comment: http://stackoverflow.com/comment/85281451
has comment: http://stackoverflow.com/comment/85281491
favorite count: 0
type: Question
answer count: 2
upvote count: 2
accepted answer: http://stackoverflow.com/a/49138226
tagged with: group-by

http://stackoverflow.com/comment/85491109
comment on: http://stackoverflow.com/q/49225456
type: QuestionComment
score: 0
type: Comment
has text: It's still not working, I'm not sure where to put float(row); please can you show me where.

http://stackoverflow.com/q/49211313
linked to: http://stackoverflow.com/q/1360101
favorite count: 0
type: Question
tagged with: python-3.x
has body: There is one same question in StackOverflow with this link: How to generate temporary URLs in Django But the accepted answer code is for Python 2 and I converted it to Python 3: import hashlib, zlib import pickle as pickle import urllib.request, urllib.parse, urllib.error my_secret = "michnorts" def encode_data(data): """Turn `data` into a hash and an encoded string, suitable for use with `decode_data`.""" text = zlib.compress(pickle.dumps(data, 0)).encode('base64').replace('\n', '') m = hashlib.md5(my_secret + text).hexdigest()[:12] return m, text def decode_data(hash, enc): """The inverse of `encode_data`.""" text = urllib.parse.unquote(enc) m = hashlib.md5(my_secret + text).hexdigest()[:12] if m != hash: raise Exception("Bad hash!") data = pickle.loads(zlib.decompress(text.decode('base64'))) return data hash, enc = encode_data(['Hello', 'Goodbye']) print(hash, enc) print(decode_data(hash, enc)) But it have error : text = zlib.compress(pickle.dumps(data, 0)).encode('base64').replace('\n', '') AttributeError: 'bytes' object has no attribute 'encode' How should I fix this?
answer count: 2
has comment: http://stackoverflow.com/comment/100276174
has answer: http://stackoverflow.com/a/58385130
possible better answer: http://stackoverflow.com/a/58385130
downvote count: 0
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49211835
accepted answer: http://stackoverflow.com/a/49211835
type: AnsweredQuestion
upvote count: 1
score: 1
has title: Generate temporary URLs in Django 2 Python 3

http://stackoverflow.com/comment/85261030
score: 0
type: Comment
has text: On my system it works with the list that you just posted. Does it tell you the line in which it finds the error?
comment on: http://stackoverflow.com/a/49126168
type: AnswerComment

http://stackoverflow.com/comment/85259995
has text: Tks all... Both ideas have good advantages
comment on: http://stackoverflow.com/q/49127168
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85317169
type: AnswerComment
has text: Although you should really consider firstly if this should be a method, since it doesn't use any data from the Student object, and secondly if you need it at all given that it's trivially replaced by a call to `max()`.
comment on: http://stackoverflow.com/a/49155823
type: Comment
score: 0

http://stackoverflow.com/a/49133346
type: Answer
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/49133313
downvote count: 0
has body: The easiest method involves groupby + transform: df[df.drug.eq('B').groupby(df.pid).transform('any')] pid drug 0 1 A 1 1 B 2 1 C 6 3 B 7 3 C 8 3 D In pursuit of a faster solution, call groupby on df, not a Series: df[~df.groupby('pid').drug.transform(lambda x: x.eq('B').any())] pid drug 3 2 A 4 2 C 5 2 E 9 4 D 10 4 E 11 4 F

http://stackoverflow.com/q/49220019
has title: What does this print(' '*len(msg), end='') call do?
score: 1
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85443860
favorite count: 0
type: Question
has body: I am studying Python using a book. But there is an example code I don't understand: from time import sleep for i in range(100): msg = '\rProgress %d%%' %(i+1) print(' '*len(msg), end='') #I don't understand this statement. print(msg, end='') sleep(0.1) Actually, I commented out that statement, I got the same result. Why do I need that statement?
type: UnansweredQuestion
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/49220103
has comment: http://stackoverflow.com/comment/85443978

http://stackoverflow.com/comment/85399375
comment on: http://stackoverflow.com/q/49196837
score: 0
has text: check out `boto3` module for python for AWS communications..https://boto3.readthedocs.io/en/latest/
type: Comment
type: QuestionComment

http://stackoverflow.com/a/52121801
answers question: http://stackoverflow.com/q/49175855
type: Answer
has body: I know this question is somewhat old, but it might help someone else. I just went through this same problem. You will have to build numpy from source in debug mode. Download the numpy sources from the latest release on their Github repo, extract them, and run: python_d.exe setup.py build --debug install This way you will have the debug version of numpy avaiable to your debug version of python, and the import will work. Note that the release version of python now won't be able to import numpy. I haven't been able to get both debug and release versions of numpy working at the same time.
score: 0

http://stackoverflow.com/comment/85501386
has text: Your code doesn't add a `/` to `source`. Is that in the CSV entries? Or is this not your actual code? Or is the error actually telling you that `directoryspam` is missing rather than `directory/spam`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49248432

http://stackoverflow.com/q/49195403
upvote count: 1
has comment: http://stackoverflow.com/comment/85445588
favorite count: 0
type: Question
has body: I have been getting the following error in python UnicodeEncodeError: 'latin-1' codec can't encode character '\u018f' in position 0: ordinal not in range(256) While trying to force hack an encrypted pdf using pypdf2 and itertools library files. Here is my code: The weird thing is the code works fine while using a different machine...the python version is 3.6.4 both mine and the machine I tried on. Things I have tried are: I tried running the code on a different machine and it worked fine. Which now makes me think that I had not installed python properly I freshly installed python v 3.6.4 and pycharm (latest community version). When that failed I tried anaconda(latest version) which also failed, leading me back to python v 3.6.4 import PyPDF2 as pdf import itertools testFile = pdf.PdfFileReader("File01_Enc.pdf") print(testFile.isEncrypted) # for n in range(100001): # if n &lt;= 100: # print(n) # t = str(n) # x = testFile.decrypt(t) # if x == 2 or x == 1: # print("The password is: " + str(t) # break pwds = itertools.combinations("0123456789", 6) for p in pwds: print(''.join(p)) x = testFile.decrypt(''.join(str(p))) if x &gt; 0: print("The password is: " + ''.join(str(p))) break
tagged with: python-itertools
score: 1
has comment: http://stackoverflow.com/comment/124389404
tagged with: python
has title: UnicodeEncodeError while trying to decrypt (pypdf2) file object using python
answer count: 0
tagged with: pypdf
has comment: http://stackoverflow.com/comment/87450699
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/124358823
downvote count: 0

http://stackoverflow.com/a/49214872
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49214237
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49214237
has body: Building a scraper for appstore can be done in a few ways. Take apple store for example, the two address below belong to the chart page of Apple app store. You see how CA changed to CN. That is a country code. https://www.apple.com/ca/itunes/charts/ https://www.apple.com/cn/itunes/charts/ you can create a function of some sort and use different parameter based on function input. And the code below will only get you started, you still need to concate the entire URL not just parts of it. type_params = {'Canada': {'ca'}, 'China': {'cn'}} url = 'https://www.apple.com/' params = {CA} params.update(type_params[type]) headers = {'User-Agent': ...} resp = requests.get(url, headers=headers, params=params)

http://stackoverflow.com/q/49261006
has answer: http://stackoverflow.com/a/49261264
downvote count: 0
has title: Load all pickled objects
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85526284
duplicate of: http://stackoverflow.com/q/20716812
possible better answer: http://stackoverflow.com/a/49261255
has comment: http://stackoverflow.com/comment/85525984
has answer: http://stackoverflow.com/a/49261255
tagged with: pickle
tagged with: python
has body: import pickle ListNames = [["Name1","City1","Email1"],["Name2","City2","Number2"]] ListNumbers = [1,2,3,4,5,6,7,8] with open ("TestPickle.pickle","wb") as fileSaver: pickle.dump(ListNames,fileSaver) pickle.dump(ListNumbers,fileSaver) with open ("TestPickle.pickle","rb") as fileOpener: print(pickle.load(fileOpener)) The output is: [['Name1', 'City1', 'Email1'], ['Name2', 'City2', 'Number2']] How do I get pickle to load the ListNumbers too I know I can just print pickle.load again but what if I have an unknown number of items in my pickle file with a number of Datatypes (e.g: lists, tuples, dictionaries, strings....) Thanks
accepted answer: http://stackoverflow.com/a/49261333
type: AnsweredQuestion
score: 3
answer count: 3
linked to: http://stackoverflow.com/q/15463387
has answer: http://stackoverflow.com/a/49261333
upvote count: 3
linked to: http://stackoverflow.com/q/20716812

http://stackoverflow.com/comment/85268286
score: 0
type: Comment
type: QuestionComment
has text: @Aziz I have updated it
comment on: http://stackoverflow.com/q/49131534

http://stackoverflow.com/comment/85375537
has text: @juanpa.arrivillaga - that was just an example, I want the user to enter whatever value like 'V20LC' and then prints the corresponding values from cases dictionary.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49184828
type: Comment

http://stackoverflow.com/comment/85531188
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49263727
type: AnswerComment
has text: Yes -- but the loop I posted ends at `n-2`. Look at the documentation: `range` does *not* include the given "stop" value. range(1, 4) produces the values (1, 2, 3).

http://stackoverflow.com/a/79278650
downvote count: 0
has body: A nice way to do it inside the model and with no query to the db is to override the init method of the model class CustomModel(models.Model): count = models.IntegerField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._original_count = self.count def clean(self): value = self._original_count ...
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49192483
score: 1

http://stackoverflow.com/comment/85327385
has text: Thanks...for this solution...tried it and actually works.
type: Comment
comment on: http://stackoverflow.com/a/49139478
score: 0
type: AnswerComment

http://stackoverflow.com/q/49219586
tagged with: opengl
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/28014922
linked to: http://stackoverflow.com/q/28075743
tagged with: pyopengl
favorite count: 0
type: Question
tagged with: graphics
has comment: http://stackoverflow.com/comment/85442982
upvote count: 2
tagged with: 3d
accepted answer: http://stackoverflow.com/a/49219788
has title: Making a Solar System in OpenGL
has comment: http://stackoverflow.com/comment/85464393
has answer: http://stackoverflow.com/a/49219788
tagged with: python
has body: I am trying to make a solar system in OpenGL but the planet is not revolving around sun. That is revolving around some other axis. How to fix this? First, I am drawing a sun, Then, there is rotation, translation and again rotation of first planet. So it should revolve around the sun and rotate on it's own axis, but that's not happening. I also want to make the circle on which planet will revolve. How to make the circles in XZ plane (possibly) from __future__ import division from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * year = 0 day = 0 def init(): glClearColor (0.0, 0.0, 0.0, 0.0) glShadeModel (GL_FLAT) def display(): global day, year glClear (GL_COLOR_BUFFER_BIT) glColor3f (1.0, 1.0, 0, 1) glPushMatrix() glutSolidSphere(1.0, 20, 16) # draw sun glRotatef(year, 0.0, 1.0, 0.0) year = (year + 1) % 360 glPushMatrix() glTranslatef(2.0, 0.0, 0.0) glRotatef(day, 0.0, 1.0, 0.0) day = (day + 1) % 360 glColor3f (0, 0, 1.0); glutWireSphere(0.2, 10, 8) # draw smaller planet glPopMatrix() glPushMatrix() glTranslatef(4.0, 0.0, 0.0) glRotatef(day, 0.0, 1.0, 0.0) glColor3f (1, 0, 0.0, 1) glutWireSphere(0.2, 10, 8) glPopMatrix() glPopMatrix() glutSwapBuffers() # delay for i in range(100000): pass def reshape(w, h): glViewport (0, 0, w, h) glMatrixMode (GL_PROJECTION) glLoadIdentity () gluPerspective(70.0, w/h, 1.0, 20.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) glutInit() glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB) glutInitWindowSize(800, 800) glutInitWindowPosition (100, 100) glutCreateWindow("Transformation") init () glutDisplayFunc(display) glutIdleFunc(display) glutReshapeFunc(reshape) glutMainLoop()
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/85491072
type: AnswerComment
has text: Oh my god, thanks bro! I've been sleeping in my car and caught a cold so my head is a bit cloudy.
score: 0
comment on: http://stackoverflow.com/a/49243598
type: Comment

http://stackoverflow.com/q/49143334
downvote count: 0
upvote count: 1
has answer: http://stackoverflow.com/a/49143400
favorite count: 0
type: Question
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49143430
has body: Suppose now I have the following pandas data frame: id text 1 A B C 2 B D 3 A D And I want to get the following result: id A B C D 1 1 1 1 0 2 0 1 0 1 3 1 0 0 1 I don't how to describe this transformation, it looks like one-hot encoding but they should be totally different. Anyone knows how to do this transformation and what's the name of such transformation?
answer count: 2
tagged with: pandas
type: UnansweredQuestion
has title: How do I convert text into multiple columns in python?

http://stackoverflow.com/comment/85525649
score: 0
has text: Note: You have a typo, `'sessionAttrbiutes'` should probably be `'sessionAttributes'`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49260949

http://stackoverflow.com/q/49131554
has comment: http://stackoverflow.com/comment/85273776
score: 0
tagged with: homebrew
has title: how to migrate all pip2 packages to pip3 not having anymore pip2
answer count: 1
has body: I recently updated my packages on a macOS High Sierra using brew update &amp;&amp; brew upgrade in where now python and pip are symlinks to python3, pip3. From brew info python Unversioned symlinks python, python-config, pip etc. pointing to python3, python3-config, pip3 etc., respectively, have been installed. I tend to install all my packages within my $HOME directory by using: pip install --user &lt;package&gt;, so my first instinct to reinstall the packages was to do a pip freeze to get the list of packages and then just try to install them using pip3 but after the upgrade I notice I don't have pip2 anymore. Is there a way without having to install python2, to list user instaled packages, something like pip freeze so that later I could just reinstall them using pip (now pip3)?, (I still have the $HOME/Library/Python/2.7 directory with all its contents)
tagged with: pip
has answer: http://stackoverflow.com/a/49654021
has comment: http://stackoverflow.com/comment/85300431
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85300516
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85276686

http://stackoverflow.com/q/49157048
downvote count: 0
upvote count: 7
possible better answer: http://stackoverflow.com/a/49157907
has answer: http://stackoverflow.com/a/49161914
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49157907
has title: How to group dataframe by hour using timestamp with Pandas
has body: I have the following dataframe structure that is indexed with a timestamp: neg neu norm pol pos date time 1520353341 0.000 1.000 0.0000 0.000000 0.000 1520353342 0.121 0.879 -0.2960 0.347851 0.000 1520353342 0.217 0.783 -0.6124 0.465833 0.000 I create a date from the timestamp: data_frame['date'] = [datetime.datetime.fromtimestamp(d) for d in data_frame.time] Result: neg neu norm pol pos date time 1520353341 0.000 1.000 0.0000 0.000000 0.000 2018-03-06 10:22:21 1520353342 0.121 0.879 -0.2960 0.347851 0.000 2018-03-06 10:22:22 1520353342 0.217 0.783 -0.6124 0.465833 0.000 2018-03-06 10:22:22 I want to group by hour, while getting the mean for all the values, except the timestamp, that should be the hour from where the group started. So this is the result I want to archive: neg neu norm pol pos time 1520352000 0.027989 0.893233 0.122535 0.221079 0.078779 1520355600 0.028861 0.899321 0.103698 0.209353 0.071811 The closest I have gotten so far has been with this answer: data = data.groupby(data.date.dt.hour).mean() Results: neg neu norm pol pos date 0 0.027989 0.893233 0.122535 0.221079 0.078779 1 0.028861 0.899321 0.103698 0.209353 0.071811 But I cant figure out how to keep the timestamp that takes in account he hour where the grouby started.
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49210167
tagged with: timestamp
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49210167
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
score: 7
linked to: http://stackoverflow.com/q/11391969

http://stackoverflow.com/a/49261231
accepted answer of: http://stackoverflow.com/q/49247602
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85537783
upvote count: 1
answers question: http://stackoverflow.com/q/49247602
has comment: http://stackoverflow.com/comment/85537720
has comment: http://stackoverflow.com/comment/85538089
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85538514
has comment: http://stackoverflow.com/comment/85537962
has body: Well, if I have to be honest, I don't know where are some of the paths that you use, because I can't find them. I have redone your code to try to help: from lxml import html import requests import json asin = 'B0718Y23CQ' page_response = requests.get('https://www.amazon.com/product-reviews/'+ asin) parser = html.fromstring(page_response.content) reviews_html = parser.xpath('//div[@class="a-section review"]') reviews_arr = [] for review in reviews_html: review_dic = {} review_dic['title'] = review.xpath('.//a[@data-hook="review-title"]/text()') review_dic['rating'] = review.xpath('.//a[@class="a-link-normal"]/@title') review_dic['author'] = review.xpath('.//a[@data-hook="review-author"]/text()') review_dic['date'] = review.xpath('.//span[@data-hook="review-date"]/text()') review_dic['purchase'] = review.xpath('.//span[@data-hook="avp-badge"]/text()') review_dic['review_text'] = review.xpath('.//span[@data-hook="review-body"]/text()') review_dic['helpful_votes'] = review.xpath('.//span[@data-hook="helpful-vote-statement"]/text()') reviews_arr.append(review_dic) print(json.dumps(reviews_arr, indent = 4)) The output scheme is: { "title": [ "I find it very useful, I use for anything I need" ], "rating": [ "5.0 out of 5 stars" ], "author": [ "Nicoletta Delon" ], "date": [ "on January 2, 2018" ], "purchase": [ "Verified Purchase" ], "review_text": [ "I like this a lot. I use it a lot. It's a medium to small size but it holds a lot." ], "helpful_votes": [ "\n One person found this helpful.\n " ] } Now you have to clean the results, remove them from the lists, prevent that the element can be empty and I think you'll have what you need. To get all the reviews, you have to iterate the pages, adding ?pageNumber=1 to the link, and iterating the number. You can use proxies for prevent the blocking of the ip, in case you're going to make many requests.

http://stackoverflow.com/q/49150413
upvote count: 2
has answer: http://stackoverflow.com/a/49155872
type: UnansweredQuestion
tagged with: flask
tagged with: jinja2
downvote count: 1
has answer: http://stackoverflow.com/a/49153137
has comment: http://stackoverflow.com/comment/85307776
score: 1
has title: how to display google map in between the dashboard
tagged with: python
favorite count: 0
has body: while running flask server throwing this error Uncaught TypeError: Cannot read property 'firstChild' of null at Object._.Og (js?key=AIzaSyAbZKo3h1LVhyoURgxcSUG9BGVvZtZpg0U:88) at new Sg (js?key=AIzaSyAbZKo3h1LVhyoURgxcSUG9BGVvZtZpg0U:89) I'm new google maps in Python-Flask.google map is not showing while running the Flask localhost server.but,it showing while running the template.i'm not aware where i have mistaken in my source code. I need only show the map in between the empty place. here is the dashboard where place be the map here yesterday i posted answer that is working.but it's showing like Uncaught TypeError: Cannot read property 'firstChild' of null at Object._.Og (js?key=AIzaSyAbZKo3h1LVhyoURgxcSUG9BGVvZtZpg0U:88) at new Sg (js?key=AIzaSyAbZKo3h1LVhyoURgxcSUG9BGVvZtZpg0U:89) where is the problem Here is the google map code: {% extends "base.html" %} {% block head %} {{super()}} {% endblock %} {% block navbar %} {{super()}} {% endblock %} {% block content %} Locations>create locations {% endblock %} Here is the Python code: @app.route('/page/locations') def location(): if session['username']: return render_template('map.html',user=session['username']) else: print ('login first!') return redirect('/dashboard')
type: Question
answer count: 2
tagged with: google-maps

http://stackoverflow.com/comment/85336732
comment on: http://stackoverflow.com/q/49165370
has text: @codekaizer: it's obvious when you know why it's happening, and you could have tryed it yourself if you liked, no need to ask the OP ;-). If we go that way we could comment on any question asking if the OP is sure it's correct.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49164451
score: 1
has comment: http://stackoverflow.com/comment/85334798
has body: @Marti157's answer gives you the bare bones of how to do it (after replacing "some text" with your message). It involves a clever trick where rather than listing out all the letters of the alphabet, you give the ASCI code for 'a', which is 97, and add i, a number that starts at 0 and goes up for every repetition of the loop. So this shows you you don't actually need a list to do exactly what you set out to do. But a list could be useful in a number of ways, so let's generate one using the same trick @Marti157 used: alphabet = [chr(97+i) for i in range(26)] You can do it in one line! This is one of the cool things about Python. Of course, this is probably a dummy example and in the end you'll have a more specific list which you'll want to specify manually. Like so: file_list = ["main", "about", "myhobbies", "catscatscats"] Once you have a list, the loop that generates the files for you (using the alphabet list and your message) is: for letter in alphabet: f = open(letter+".html", "w") f.write(message) f.close() The next thing you'll want to do to really make this functional is vary the content of the html file according to the item in the list. For this, let's use '@' as a placeholder within your message text, that we'll later replace with a different letter of the alphabet for each file. alphabet = [chr(97+i) for i in range(26)] message = """ This is page @ This is @ Heading This is @ paragraph. """ for letter in alphabet: f = open(letter+".html", "w") f.write(message.replace("@", letter)) f.close() Now w.html should read: This is page w This is w Heading This is w paragraph. Hopefully this will get you excited about the possibilities for automating this kind of thing with Python! File management If you are struggling to find the files generated, I'd first look in the directory your Python script is saved. Or, if you're typing it directly in terminal, you might want to check your working directory (quit Python first) using pwd. (I'm assuming it's a Unix terminal, ie…
type: Answer
accepted answer of: http://stackoverflow.com/q/49162712
has comment: http://stackoverflow.com/comment/85334857
answers question: http://stackoverflow.com/q/49162712
has comment: http://stackoverflow.com/comment/85335682
has comment: http://stackoverflow.com/comment/85335279
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85335123
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85335273

http://stackoverflow.com/a/49200309
upvote count: 20
type: Answer
has comment: http://stackoverflow.com/comment/85406203
has comment: http://stackoverflow.com/comment/85406180
has comment: http://stackoverflow.com/comment/119263307
accepted answer of: http://stackoverflow.com/q/49200272
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/119269965
downvote count: 1
score: 19
has body: You seem to be using NumPy, so why not just do this - &gt;&gt;&gt; 2 ** np.arange(4) array([1, 2, 4, 8]) This is broadcasted exponentiation.
answers question: http://stackoverflow.com/q/49200272

http://stackoverflow.com/a/59906404
answers question: http://stackoverflow.com/q/49122527
score: 0
has body: I got the same error in LightGBM Python. In my case, the size of the test dataset was 0 rows. So make sure the size of test/train dataset is not 0 rows.
type: Answer

http://stackoverflow.com/q/49276183
has answer: http://stackoverflow.com/a/49277174
answer count: 6
has body: I have a list like this one: l1 = [{'id':'78798798','gender':'Male'}, {'id':'78722228','gender':'Female'}, {'id':'33338','gender':'Male'}] I need to check the length of a list obtained using a list comprehension and filtered by 'gender'. I try len([x for x in l1 if x['gender'] == "Male"]) but return an error Then i try: [[(k,v) for k,v in d.items()] for d in l1 if l1['gender'] == 'Male'] but return the same error and also [[(k,v) for k,v in d.items() if k['gender'] == 'Male'] for d in l1] How can i achieve my goal? Thanks in advance
has title: Python list comprehension with dicts and filters
has comment: http://stackoverflow.com/comment/85554764
tagged with: list
downvote count: 3
has answer: http://stackoverflow.com/a/49276296
has comment: http://stackoverflow.com/comment/85554819
has comment: http://stackoverflow.com/comment/85554738
has answer: http://stackoverflow.com/a/49276347
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85554767
has answer: http://stackoverflow.com/a/49276295
has answer: http://stackoverflow.com/a/49276629
has comment: http://stackoverflow.com/comment/85554744
has comment: http://stackoverflow.com/comment/85554954
has comment: http://stackoverflow.com/comment/85554896
tagged with: list-comprehension
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85554932
has answer: http://stackoverflow.com/a/49276265
type: UnansweredQuestion
tagged with: dictionary-comprehension
has comment: http://stackoverflow.com/comment/85554844

http://stackoverflow.com/q/49121764
score: 0
accepted answer: http://stackoverflow.com/a/49121807
has answer: http://stackoverflow.com/a/49121807
answer count: 1
has title: Negate all list values in a 2D array
type: Question
tagged with: numpy
tagged with: python-3.x
tagged with: arrays
has body: The following two versions of my script work as intended: matrix = [[1, -2, 3], [-4, 5, -6], [7, -8, 9]] def negate(amatrix): for alist in matrix: for i in range(len(alist)): alist[i] = -alist[i] return amatrix print(negate(matrix)) Yields: [[-1, 2, -3], [4, -5, 6], [-7, 8, -9]] as does this version: matrix = [[1, -2, 3], [-4, 5, -6], [7, -8, 9]] def negate(amatrix): newmatrix = [] for alist in amatrix: newlist = [-x for x in alist] newmatrix.append(newlist) return newmatrix print(negate(matrix)) I am trying to use a comprehension to change the values in place, like the first version. I have this: matrix = [[1, -2, 3], [-4, 5, -6], [7, -8, 9]] def negate(amatrix): for alist in matrix: alist = [-x for x in alist] return amatrix print(negate(matrix)) This third version does negate the individual values in each of the lists, but the changes are not saved in the matrix, i.e., I want the list values changed in place. Is there a way to use a comprehension to negate the individual list values in place, or do I have to use the indexed version (the first version above)?
tagged with: python
tagged with: list-comprehension
type: AnsweredQuestion

http://stackoverflow.com/a/49170293
has body: It's a mixin which is used on classes which do define an execute method, e.g.: class ModbusClientProtocol(protocol.Protocol, ModbusClientMixin): A mixin adds methods to other classes and is not supposed to be used by itself. If you wanted to type-annotate it properly, it would have to be something like: class Executable(ABC): @abstractmethod def execute(self): pass class ModBusClientMixin: def read_coils(self: Executable, address, count=1, **kwargs): # ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ # Expects self to conform to Executable interface, # i.e. to be used in a class that implements execute(). self.execute() Since Python heavily relies on duck-typing and type annotations are a relatively recent addition, they're often omitted and replaced by verbose documentation, or it is expected that developers recognise the purpose of mixins, or that it's such an internal implementation detail that it hasn't been explicitly documented.
answers question: http://stackoverflow.com/q/49170173
has comment: http://stackoverflow.com/comment/85345906
has comment: http://stackoverflow.com/comment/85346089
upvote count: 3
has comment: http://stackoverflow.com/comment/85346036
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85345899
has comment: http://stackoverflow.com/comment/85346001
score: 3
accepted answer of: http://stackoverflow.com/q/49170173
has comment: http://stackoverflow.com/comment/85345884
type: Answer

http://stackoverflow.com/q/49154895
has answer: http://stackoverflow.com/a/49155154
has answer: http://stackoverflow.com/a/49155034
has answer: http://stackoverflow.com/a/74555722
tagged with: python
answer count: 4
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/49155154
upvote count: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/49155126
favorite count: 0
type: Question
has title: Python - Sum and count specific values with pandas pivot_table
has body: I have a pandas dataframe like ACCOUNT AMOUNT STATUS 1 -2 1 2 2 0 2 -1 0 1 2 1 1 2 1 This is would like to get converted into an dataframe like ACCOUNT STATUS COUNT&gt;0 COUNT&lt;0 AMOUNT&gt;0 AMOUNT&lt;0 1 1 2 1 4 2 2 0 1 1 2 1 So basically split if AMOUNT is > or &lt; than 0 and then count and sum the result. I currently have the following, but can't get the split AMOUNT right. Data = pd.pivot_table(trans, values =['Status', 'AMOUNT'], index = ['ACCOUNT'], aggfunc = {'Status':np.mean, 'AMOUNT': [np.sum, 'count'] } )
accepted answer: http://stackoverflow.com/a/49155034

http://stackoverflow.com/q/49257094
favorite count: 0
type: Question
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85517609
has answer: http://stackoverflow.com/a/49257131
tagged with: numpy
type: AnsweredQuestion
tagged with: python-2.7
downvote count: 0
has body: I have two 3D matrices (A and B), both containing NaN in random elements. I am comparing these two matrices and in places where at least one of them contains NaN I want both of them to contain NaN. In other words, if the both of them don't already contain NaN at that index, I want to replace that index value with NaN. Is there an efficient way to do this with a python function? import numpy as np # Create the fake variables A and B. Here is what A and B look like initially: A = np.array([[1, 2, np.nan], [4, np.nan, 6], [np.nan, 8, 9]]) B = np.array([[1, 2, 3], [4, 5, np.nan], [np.nan, 8, 9]]) # What I want A and B to look like in the end: A array([[ 1., 2., nan], [ 4., nan, nan], [ nan, 8., 9.]]) B array([[ 1., 2., nan], [ 4., nan, nan], [ nan, 8., 9.]])
upvote count: 1
answer count: 1
has title: Compare Two Matrices Containing NaN and Mask the Element Values in Both Matrices Where at Least One of Them Contains NaN in Python
has comment: http://stackoverflow.com/comment/85518116
accepted answer: http://stackoverflow.com/a/49257131

http://stackoverflow.com/q/49257427
has comment: http://stackoverflow.com/comment/85546129
tagged with: python
has comment: http://stackoverflow.com/comment/85529469
tagged with: caching
has title: Python: Flask cache unable to work in specific time range
has body: the Flask app I create only able to work if it outside the time range but return error if it is within the time range (the if path) from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.cache import Cache from datetime import datetime, time app.config['CACHE_TYPE'] = 'simple' app.cache = Cache(app) @app.route('/thtop', methods=['GET']) @app.cache.cached(timeout=60) def thtop(): now = datetime.now() now_time = now.time() if now_time &gt;= time(3,30) and now_time &lt;= time(16,30): rv = app.cache.get('last_response') else: rv = 'abcc' app.cache.set('last_response', rv, timeout=3600) return rv If the time in the if path, it unable to show the string abcc but shown Internal Server Error. In WSGI error log, it also shown Exception on /thtop [GET]#012Traceback (most recent call last):#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app#012 response = self.full_dispatch_request()#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1361, in full_dispatch_request#012 response = self.make_response(rv)#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1439, in make_response#012 raise ValueError('View function did not return a response')#012ValueError: View function did not return a response What is wrong when I am caching? UPDATE Use flask_caching module but still same failures from flask.ext.sqlalchemy import SQLAlchemy from flask_caching import Cache from datetime import datetime, time cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/thtop', methods=['GET']) @cache.cached(timeout=60) def thtop(): now = datetime.now() now_time = now.time() if now_time &gt;= time(3,30) and now_time &lt;= time(14,30): rv = cache.get('last_response') else: rv = 'abcc' cache.set('last_response', rv, timeout=3600) return rv The difference I observed in both different module when I run in console, starting from def thtop(), app.cache.get('last_response') return nothing. However, cache.get('last_response') re…
has comment: http://stackoverflow.com/comment/85541064
type: AnsweredQuestion
upvote count: 3
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49259006
has comment: http://stackoverflow.com/comment/85545999
has comment: http://stackoverflow.com/comment/85547547
tagged with: flask
has answer: http://stackoverflow.com/a/49331597
accepted answer: http://stackoverflow.com/a/49331597
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85528509
possible better answer: http://stackoverflow.com/a/49259006
has comment: http://stackoverflow.com/comment/85548129
score: 3

http://stackoverflow.com/q/49200384
score: 0
answer count: 2
accepted answer: http://stackoverflow.com/a/49200475
has answer: http://stackoverflow.com/a/49200475
type: Question
has title: How to compare less than or equals with only date of field having timestamp with timezone field
possible better answer: http://stackoverflow.com/a/49200852
tagged with: django
tagged with: django-models
tagged with: python
has body: i am using default auth_user table with field date_joined as type as timestamp with time zone. All i want to check use the lte and gte comparison on only its date not with the time and zone. def get_fm_objects(self, filters): fm = FacilityManager.objects.all().order_by('-id') if filters['from_date']: fm = fm.filter(user__date_joined__gte=filters['from_date']) if filters['to_date']: fm = fm.filter(user__date_joined__lte=filters['to_date']) return fm here FacilityManager is another model and filters['from_date'] and filters['to_date'] are my input dates(it only contains date. eg:2018-1-10). i have a row in auth_user table with date_joined as 2018-01-11 00:56:39.735756+05:30 but when i give From and To date as 2018-01-11 it returns nothing. looking for answers. Thanks in advance.
has answer: http://stackoverflow.com/a/49200852
tagged with: django-views
type: AnsweredQuestion

http://stackoverflow.com/a/49144238
type: AcceptedAnswer
has body: How about limit to rows of the first table (following::table[1]) that follow the text Whole Market Top Gainers: &gt;&gt;&gt; gain = ... &gt;&gt;&gt; expr = ('//h2[contains(.,"Whole Market Top Gainers")]' '/following::table[1]/tbody/tr') &gt;&gt;&gt; rows = gain.xpath() &gt;&gt;&gt; [[td.text_content().strip() for td in row] for row in rows] [['AJC', 'ACACIA COAL LTD', '0.002', '0.001rise', '100.00rise', '92,525'], ['MEM', 'MEMPHASYS LTD', '0.002', '0.001rise', '100.00rise', '1,000,000'], ['AUH', 'AUSTCHINA HOLDINGS', '0.007', '0.002rise', '40.00rise', '1,433,311'], ['AO1', 'ASSETOWL LIMITED', '0.100', '0.025rise', '33.33rise', '249,180'], ['BAS', 'BASS OIL LTD', '0.004', '0.001rise', '33.33rise', '15,390,472'], ['RNL', 'RISION LIMITED', '0.004', '0.001rise', '33.33rise', '6,100,812'], ['PAB', 'PATRYS LIMITED', '0.061', '0.013rise', '27.08rise', '86,337,514'], ['IQ3', 'IQ3CORP LIMITED', '0.250', '0.050rise', '25.00rise', '6,000'], ['SMA', 'SMARTTRANS HOLDINGS', '0.005', '0.001rise', '25.00rise', '70,000'], ['SEI', 'SPECIALITY METALINT', '0.035', '0.006rise', '20.69rise', '12,162,844']] # td.text_content().strip().replace('rise', '') to remove `rise`
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49143689
type: Answer
answers question: http://stackoverflow.com/q/49143689
score: 1

http://stackoverflow.com/comment/85303150
comment on: http://stackoverflow.com/q/49149348
score: 0
has text: Hey, I am sorry, its my bad...
type: QuestionComment
type: Comment

class
tags question: http://stackoverflow.com/q/49155418
tags question: http://stackoverflow.com/q/49139164
tags question: http://stackoverflow.com/q/49155657
tags question: http://stackoverflow.com/q/49248527
tags question: http://stackoverflow.com/q/49129604
tags question: http://stackoverflow.com/q/49142747
tags question: http://stackoverflow.com/q/49193553
type: Tag
tags question: http://stackoverflow.com/q/49162957
tags question: http://stackoverflow.com/q/49193843
tags question: http://stackoverflow.com/q/49237781
tags question: http://stackoverflow.com/q/49214241
tags question: http://stackoverflow.com/q/49206732
tags question: http://stackoverflow.com/q/49217175
tags question: http://stackoverflow.com/q/49254848
tags question: http://stackoverflow.com/q/49181822
tags question: http://stackoverflow.com/q/49143001
tags question: http://stackoverflow.com/q/49199585
tags question: http://stackoverflow.com/q/49139727
tags question: http://stackoverflow.com/q/49150889
tags question: http://stackoverflow.com/q/49236210
tags question: http://stackoverflow.com/q/49161846
tags question: http://stackoverflow.com/q/49270330
tags question: http://stackoverflow.com/q/49217069
tag name: class
tags question: http://stackoverflow.com/q/49162406
tags question: http://stackoverflow.com/q/49265512
tags question: http://stackoverflow.com/q/49180872
tags question: http://stackoverflow.com/q/49215951
tags question: http://stackoverflow.com/q/49177228
tags question: http://stackoverflow.com/q/49256431
tags question: http://stackoverflow.com/q/49179377
tags question: http://stackoverflow.com/q/49258892
tags question: http://stackoverflow.com/q/49173633
tags question: http://stackoverflow.com/q/49151528
tags question: http://stackoverflow.com/q/49202684
tags question: http://stackoverflow.com/q/49204684
tags question: http://stackoverflow.com/q/49193134
tags question: http://stackoverflow.com/q/49277706
tags question: http://stackoverflow.com/q/49221230
tags question: http://stackoverflow.com/q/49136737
tags question: http://stackoverflow.com/q/49217006
tags question: http://stackoverflow.com/q/49252151
tags question: http://stackoverflow.com/q/49167442
tags question: http://stackoverflow.com/q/49273317
tags question: http://stackoverflow.com/q/49216688
tags question: http://stackoverflow.com/q/49142362
tags question: http://stackoverflow.com/q/49179509
tags question: http://stackoverflow.com/q/49208142
tags question: http://stackoverflow.com/q/49222472

http://stackoverflow.com/a/49203683
has comment: http://stackoverflow.com/comment/85420872
has comment: http://stackoverflow.com/comment/85434559
type: Answer
has body: So heres a way that will work, I might re-factor a bit more if I was doing it but you'll get the idea and you can go from there. I've commented out your return_ax logic for simplicity. You don't need the lambda on your groupby.apply because you've already defined the function as _plot_ellipse. You can pass apply a python callable as well as kwargs (these will be passed to your callable). The line would look like df = df.groupby("label").apply(_plot_ellipse, n_std = 1, return_ax = False) In your function the first argument passed by pandas will be the group. So you don't need to reference the x and y variable in your function parameters. Also to get a DataFrame back from an apply function you need to return a DataFrame in this case you'll modify your group and then return the group. The passed group gets an attribute called name from pandas (group name) which in your case will just be the label. I changed the first lines of your function to this so the same code can be kept xdata = grp.x ydata = grp.y label = grp.name Then I've modified your code for _is_in_ellipse passing in the labels and then either keeping the label or changing it to -1. After I've reassigned grp.label to be the result Your full example with modifications is below. import numpy as np import matplotlib.pyplot as plt from matplotlib import patches import pandas as pd def _plot_ellipse(grp, n_std, ax = None, return_ax = False, **kwargs): xdata = grp.x ydata = grp.y label = grp.name def _eigsorted(cov): vals, vecs = np.linalg.eigh(cov) order = vals.argsort()[::-1] return vals[order], vecs[:, order] points = np.stack([xdata, ydata], axis = 1) # Combine points to 2-column matrix center = points.mean(axis = 0) # Calculate mean for every column (x,y) # Calculate covariance matrix for coordinates (how correlated they are) cov = np.cov(points, rowvar = False) # rowvar = False because there are 2 variables, not nrows variables vals, vecs = _eigsorted(cov) angle = np.degrees(np.arctan2(*vecs[:,0][::-1])) wid…
accepted answer of: http://stackoverflow.com/q/49199338
downvote count: 0
upvote count: 1
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49199338

http://stackoverflow.com/a/49245183
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49245150
has body: Pass that data into the Ajax as follow: data: { "my_Data": my_Data } And this way, you will be able to get the param as follow: data = request.form['my_Data'] $.ajax()

http://stackoverflow.com/a/49180067
has comment: http://stackoverflow.com/comment/85368427
upvote count: 1
has comment: http://stackoverflow.com/comment/85366685
score: 1
has comment: http://stackoverflow.com/comment/85367108
type: Answer
answers question: http://stackoverflow.com/q/49179910
has body: As others have already said, the reason you're having to press enter twice when running the code print(input()==0 or hash(tuple(map(int,input().split())))) is simply because you're calling the input function twice. This behavior can be reproduced with a simple example &gt;&gt;&gt; input(), input() pressed enter once pressed enter twice ('pressed enter once', 'pressed enter twice') &gt;&gt;&gt; Since you only want to ask the user for input once, you need to save the result of the first call to input in a variable: &gt;&gt;&gt; var = input(); print(var == 0 or hash(tuple(map(int, var.split())))) 3527539 &gt;&gt;&gt; Also, as others have already said, I'm not really sure why you tried to write your code all on one line. Yes writing concise code is not a bad goal, so long as that code remains readable. Often times it's simply better (and in your case, necessary) to divide you code among multiple lines.
downvote count: 0

http://stackoverflow.com/a/49272239
has body: Your algorithm can be written without a dictionary, utilising list.count. Below is an example. words, pattern = input().lower().split(',') words = [i.strip() for i in words.split()] pattern = pattern.strip() print("Word '{}' appear {} time(s)".format(pattern, words.count(pattern))) # hello then now then, then # Word 'then' appear 2 time(s)
accepted answer of: http://stackoverflow.com/q/49272147
has comment: http://stackoverflow.com/comment/85547987
type: Answer
answers question: http://stackoverflow.com/q/49272147
has comment: http://stackoverflow.com/comment/85549381
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85548635

http://stackoverflow.com/q/49162498
has comment: http://stackoverflow.com/comment/85330756
has comment: http://stackoverflow.com/comment/85342543
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49166033
has comment: http://stackoverflow.com/comment/85330778
accepted answer: http://stackoverflow.com/a/49166033
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85337347
has title: what is causing "AttributeError: 'numpy.ndarray' object has no attribute 'diff'"
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
has body: I am new to numpy and I am NOT understanding the documentation as regards diff. the code below throws the error. I am baffled any help would be appreciated. Traceback (most recent call last): File "/home/dave/Desktop/mcmtest/testhv calc.py", line 11, in &lt;module&gt; r = np.log(close_prices).diff() AttributeError: 'numpy.ndarray' object has no attribute 'diff' here is the test code. import numpy as np from numpy import sqrt,mean,log,diff import pandas as pd close_prices = [178.97,175.5,171.07,171.85,172.43,172.99,167.37,164.34,162.71,\ 156.41,155.15,159.54,163.03,156.49,160.5,167.78,167.43,166.97,167.96,171.51,171.11] print (close_prices) r = np.log(close_prices).diff() print(r)
score: 5
upvote count: 6
has comment: http://stackoverflow.com/comment/85330910
tagged with: python

http://stackoverflow.com/q/49184828
tagged with: python
has comment: http://stackoverflow.com/comment/85375488
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85375444
score: 0
has title: how do i iterate through one dictionaries and return values from another dictionary?
answer count: 1
has comment: http://stackoverflow.com/comment/85375453
tagged with: loops
has body: So, I am looking for a solution to this problem - I have two dictionaries that I am working on, I want to be able to pass the key of the one dictionary and iterate through the values of the second dictionary that corresponds to the value of the first dictionary. Here is am example - products = {"V14LC": "A", "V15LC": "A", "V20LC": "B", "V20LCACSPV": "B", "VPRC": "A", "V25LC": "B,I", "V28LC": "B,28,I"} cases = {"case1": "BDH", "case5": "BCD", "case5c": "BCC", "case8D": "DD", "case8DC": "CDD", "case12": "CDH", "case14": "DEH", "case15": "CCDD"} input - V20LC (this has the value of "B") so i should look for that value in the second dictionary (cases) and return all the keys that have that value. output needed - case1, case5, case5c (because it has a "b" as a substring of its values).
has comment: http://stackoverflow.com/comment/85375428
type: Question
has comment: http://stackoverflow.com/comment/85375456
has comment: http://stackoverflow.com/comment/85375421
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85375574
has answer: http://stackoverflow.com/a/49184899
has comment: http://stackoverflow.com/comment/85375537

http://stackoverflow.com/q/49179818
tagged with: python-3.6
has body: I am coding python3 in vscode.i install code-runner in vscode and use the plugin to run my python code.But when i wanted to print some utf8 string,there is the error. [Running] python "/develop/python/secondLesson.py" Traceback (most recent call last): File "/develop/python/secondLesson.py", line 2, in print('\u5475\u5475') UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128) [Done] exited with code=1 in 0.049 seconds My file is utf8,and when i run the code in my terminal , my code is OK.
score: 2
has answer: http://stackoverflow.com/a/49183800
linked to: http://stackoverflow.com/q/9942594
has comment: http://stackoverflow.com/comment/85689395
downvote count: 0
answer count: 1
favorite count: 0
type: Question
tagged with: visual-studio-code
upvote count: 2
type: UnansweredQuestion
has title: Python3 UnicodeEncodeError in vscode with code runner
tagged with: python
tagged with: plugins

http://stackoverflow.com/a/49186055
score: 1
has comment: http://stackoverflow.com/comment/85377978
type: AcceptedAnswer
downvote count: 0
has body: Here is a way you can go about this from copy import deepcopy def shift(board, ix, direction): if direction is 'up': return shift_col(board, ix, direction) if direction is 'down': return shift_col(board, ix, direction) if direction is 'left': return shift_row(board, ix, direction) if direction is 'right': return shift_row(board, ix, direction) def shift_col(board, col_ix, direction): temp = [row[col_ix] for row in board] if direction is 'up': temp = temp[1:len(temp)] + [temp[0]] if direction is 'down': temp = [temp[-1]] + temp[0:-1] for ix, i in enumerate(board): i[col_ix] = temp[ix] return board def shift_row(board, row_ix, direction): if direction is 'right': temp = [board[row_ix][-1]] + board[row_ix][0:-1] if direction is 'left': temp = board[row_ix][1:len(board[row_ix])] + [board[row_ix][0]] board[row_ix] = temp return board Then we can use this in the following way board = [['W', 'W', 'W', 'W'], ['W', 'W', 'W', 'W'], ['B', 'B', 'B', 'B'], ['B', 'B', 'B', 'B']] # Shifts the board for a row or column index # in the specified direction. # up/down: ix is for columns # left/right: ix is for rows board = shift(deepcopy(board), 2, 'down') for i in board: print(i)
upvote count: 1
has comment: http://stackoverflow.com/comment/85378086
type: Answer
accepted answer of: http://stackoverflow.com/q/49185800
answers question: http://stackoverflow.com/q/49185800

http://stackoverflow.com/comment/85468517
type: Comment
comment on: http://stackoverflow.com/a/49214404
score: 0
type: AnswerComment
has text: Hi @Romain, you were right, Now it's working for me too. Thank You,

http://stackoverflow.com/a/49248423
answers question: http://stackoverflow.com/q/49245779
type: Answer
score: 0
has body: Your PATH may be pointing to the wrong python environment. Depending on which one is conflicting, you may have to do some exploring to find the culprit. My guess is that Spyder is not using your created conda environment where Pytorch is installed. To change the path in Spyder, open the Preferences window. Within this window, select the Python interpreter item on the left. The path to the Python executable will be right there. I'm using a Mac, so the settings navigation may be different for you, but it's around there somewhere.

http://stackoverflow.com/comment/86673392
type: Comment
type: QuestionComment
has text: I think this is because of **deprecation of TLS 1.0 and TLS 1.1 support by GitHub** in February 2018. See https://githubengineering.com/crypto-removal-notice/
comment on: http://stackoverflow.com/q/49253773
score: 0

http://stackoverflow.com/q/49146314
favorite count: 0
has title: How to give multiple parameters to django's url in various patterns
type: Question
score: -2
downvote count: 2
tagged with: django
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49146436
upvote count: 0
has answer: http://stackoverflow.com/a/49146436
answer count: 1
has body: I use Django 1.11. I'm thinking about url design like this I want to use the part surrounded by {} as a parameter. v1/ v1/{param1} v1/{param1}/category/{param2} v1/category/{param2} I tried to make the url pattern as below url(r'^v1/?$', some_view.SomeClass.as_view()), url(r'^v1/(?P&lt;param1&gt;.*)/?', some_view.SomeClass.as_view()), url(r'^v1/(?P&lt;param1&gt;.*)/category/(?P&lt;param2&gt;.*)/?', some_view.SomeClass.as_view()), url(r'^v1/category/(?P&lt;param2&gt;.*)/?', some_view.SomeClass.as_view()), After accessing v1/param1/category/param2. Then param1/category/param2 will come in the argument {param1} How do I get it done?

http://stackoverflow.com/comment/85449685
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49219028
has text: @jezrael YES! THANK YOU :)
type: Comment

http://stackoverflow.com/q/49138985
tagged with: pandas
upvote count: 1
has body: Just want to preface that this question evolved from a previous question of mine which can be found here. I had a few follow-up's that ultimately changed the original question so here we are.. Assume we have the following dataframe: d = {'keywords' :['cheapest cheap shoes', 'luxury shoes', 'cheap hiking shoes','liverpool']} keywords = pd.DataFrame(d,columns=['keywords']) In [7]: keywords Out[7]: keywords 0 cheapest cheap shoes 1 luxury shoes 2 cheap hiking shoes 3 liverpool A dictionary is then created which houses keywords that I would like to match to the values within the DataFrame labels = {'cheape' : 'budget', 'cheap' : 'budget', 'luxury' : 'expensive', 'hiking' : 'sport', 'pool': 'pool'} The original answer that was provided to me helped solved the issue with matching keys in the dictionary d = {'keywords' :['cheapest cheap shoes', 'luxury shoes', 'cheap hiking shoes','liverpool']} keywords = pd.DataFrame(d,columns=['keywords']) labels = {'cheape' : 'budget', 'cheap' : 'budget', 'luxury' : 'expensive','hiking' : 'sport', 'pool': 'pool'} df = pd.DataFrame(d) def matcher(k): x = (i for i in labels if i in k) return ' | '.join(map(labels.get, x)) df['values'] = df['keywords'].map(matcher) keywords values 0 cheapest cheap shoes budget | budget 1 luxury shoes expensive 2 cheap hiking shoes budget | sport 3 liverpool pool However, I was running into an issue with matches resulting from partial matches. In the output above note how cheape will match to "cheapest" and pool will match to "liverpool" So my question is: Is there a way for me to exact match my dictionary to the values in keyword so that the partial matches are skipped? My desired outcome would be: keywords values 0 cheapest cheap shoes budget 1 luxury shoes expensive 2 cheap hiking shoes budget | sport 3 liverpool N/A Side note - the dictionary will expand to include keys that are tied to the same value. This is to capture any spelling variations or misspellings e.g. {'car' : 'Automobile', 'cars' : 'Autom…
tagged with: textmatching
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49139493
has answer: http://stackoverflow.com/a/49139321
possible better answer: http://stackoverflow.com/a/49139321
accepted answer: http://stackoverflow.com/a/49139493
has title: Exact Match Words 'Keys' in a Dictionary to Pandas DataFrame Column & return appropriate value
tagged with: python
tagged with: dictionary
linked to: http://stackoverflow.com/q/49121526
type: AnsweredQuestion
score: 0
answer count: 2

http://stackoverflow.com/comment/85414999
score: 0
has text: Could you post the output of `df2.head(10)` and `df.head(10)`, and clarify whether by "chart graph" you mean a bar plot?
comment on: http://stackoverflow.com/q/49204861
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49243787
has comment: http://stackoverflow.com/comment/85491940
has comment: http://stackoverflow.com/comment/85491839
answers question: http://stackoverflow.com/q/49243734
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85491717
downvote count: 1
has comment: http://stackoverflow.com/comment/85491825
score: 10
type: Answer
has body: You can use an OrderedDict like this: from collections import OrderedDict sorted_dict = OrderedDict([(el, unsorted_dict[el]) for el in ordination]) What it does is create a list of tuples (pairs) using the ordination as first element and the value in unsorted_dict as second, then the OrderedDict uses this list to create a dictionary ordered by insertion. It has the same interface as a dict and introduces no external dependencies. EDIT: In python 3.6+ an ordinary dict will preserve insertion ordering as well.
has comment: http://stackoverflow.com/comment/85491861
has comment: http://stackoverflow.com/comment/85491955
upvote count: 11
accepted answer of: http://stackoverflow.com/q/49243734
has comment: http://stackoverflow.com/comment/85492335

http://stackoverflow.com/a/49216807
has comment: http://stackoverflow.com/comment/85500176
has comment: http://stackoverflow.com/comment/85472689
has comment: http://stackoverflow.com/comment/85499896
has comment: http://stackoverflow.com/comment/85497347
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49216593
has comment: http://stackoverflow.com/comment/85501719
has comment: http://stackoverflow.com/comment/85498476
score: 0
accepted answer of: http://stackoverflow.com/q/49216593
has comment: http://stackoverflow.com/comment/85438434
has body: In[2]: def pig_latinize(word): ...: cluster_dex = 0 ...: vowels = set('AEIOUaeiou') ...: for i, char in enumerate(word, start=1): ...: if not char.isalpha() or char in vowels: ...: break ...: cluster_dex = i ...: if cluster_dex == 0: ...: suffix = 'hay' ...: elif cluster_dex == len(word): ...: cluster_dex = 1 ...: suffix = 'way' ...: else: ...: suffix = 'ay' ...: return '{}{}{}'.format(word[cluster_dex:], word[:cluster_dex], suffix) ...: ...: ...: def pig_latin(words): ...: return ' '.join(pig_latinize(word) for word in words.split()) ...: In[3]: pig_latin("Tom's") == "om'sTay" Out[3]: True In[4]: pig_latin('the ap!ple is green') == 'ethay ap!plehay ishay eengray' Out[4]: True In[5]: pig_latin("Kate's care") == "ate'sKay arecay" Out[5]: True In[6]: pig_latin('myth') == 'ythmway' Out[6]: True In[7]: pig_latin('cry') == 'rycway' Out[7]: True EDIT: This shows a possible way of turning these functions into the class from the description you gave &gt;&gt;&gt; class PigLatin(object): ... VOWELS = set('AEIOUaeiou') ... ... def __init__(self, to_convert): ... self.convert_words(to_convert) ... ... def convert_words(self, to_convert): ... if not isinstance(to_convert, list): ... # if to_convert is a string, split into separate words ... to_convert = to_convert.split() ... self.pig_latin = ' '.join( ... self.p_latin_converter(word) for word in to_convert) ... ... def p_latin_converter(self, word): ... cluster_dex = 0 ... for i, char in enumerate(word, start=1): ... if not char.isalpha() or char in self.VOWELS: ... break ... cluster_dex = i ... if cluster_dex == 0: ... suffix = 'hay' ... elif cluster_dex == len(word): ... cluster_dex = 1 ... suffix = 'way' ... else: ... suffix = 'ay' ... return '{}{}{}'.format(word[cluster_dex:], word[:cluster_dex], suffix) ... # *** An object of this method initializes the string it wants to # convert when it is created. *** &gt;&gt;&gt; p = PigLatin("Tom's") # initialize with a sting # pig_latin attribute is then set with the converted text …
type: Answer
has comment: http://stackoverflow.com/comment/85438342
has comment: http://stackoverflow.com/comment/85497550

http://stackoverflow.com/a/49178647
has body: I think I understand what you're asking. Dictionaries in Python are like associative arrays in PHP. Why not use an associative array of an associative array? dict = array( img1 =&gt; array('src' =&gt; src1, 'alt'=&gt; alt1), img2 =&gt; array('src' =&gt; src2, 'alt'=&gt; alt2), ..., )
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49177489
type: Answer
has comment: http://stackoverflow.com/comment/85369486
accepted answer of: http://stackoverflow.com/q/49177489
score: 0

http://stackoverflow.com/comment/85357603
type: AnswerComment
comment on: http://stackoverflow.com/a/49175797
has text: Thank you for taking your time to answer. I receive the following error: ` sudo python script.py Traceback (most recent call last): File "script.py", line 8, in <module> with open('output.csv', 'w', newline='') as f_output: TypeError: 'newline' is an invalid keyword argument for this function
score: 0
type: Comment

http://stackoverflow.com/a/49241113
has body: print(str(list).replace('[','{').replace(']','}')) this converts the list to a string and replaces "[]" with "{}"
has comment: http://stackoverflow.com/comment/85489535
downvote count: 0
has comment: http://stackoverflow.com/comment/85485967
score: 5
has comment: http://stackoverflow.com/comment/85486670
has comment: http://stackoverflow.com/comment/85486715
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49241035
has comment: http://stackoverflow.com/comment/85486075
has comment: http://stackoverflow.com/comment/85485898
has comment: http://stackoverflow.com/comment/85486073

http://stackoverflow.com/comment/85444308
type: QuestionComment
comment on: http://stackoverflow.com/q/49220359
has text: [Yes it is](https://stackoverflow.com/questions/15340582/python-extract-pattern-matches).
score: 0
type: Comment

http://stackoverflow.com/q/49155132
score: 0
answer count: 1
linked to: http://stackoverflow.com/q/3277503
has title: Reading a txt file and adding fixed headers/columns to a new csv file
accepted answer: http://stackoverflow.com/a/49155580
has body: I have a text file that looks like this 1 (2.10, 3) (4, 5) (6, 7) (2, 2) 2 (2.10, 3) (4, 5) (6, 7) (2, 2) 3 (6, 7) (2, 2) (30.2, 342) (6, 7) I want to read the txt file and create a csv file in this format with header and remove the brackets a,b,c,d,e,f,g,h,i 1,2.10,3,4,5,6,7,2,2 2,2.10,3,4,5,6,7,2,2 3,6,7,2,2,30.2,342,6,7 Here's the code import csv import re with open('test.txt', 'r') as csvfile: csvReader = csv.reader(csvfile) data = re.findall(r"\S+", csvfile.read()) array = [] array.append(data) print (array) file2 = open("file.csv", 'w') writer = csv.writer(file2) writer.writerows(array) The output 1,"(2.10,",3),"(4,",5),"(6,",7),"(2,",2),2,"(2.10,",3),"(4,",5),"(6,",7),"(2,",2),3,"(6,",7),"(2,",2),"(30.2,",342),"(6,",7) I tried removing the bracket using array.append(str(data).strip('()')) but no luck
type: Question
has answer: http://stackoverflow.com/a/49155580
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: rows
has comment: http://stackoverflow.com/comment/85319713
has comment: http://stackoverflow.com/comment/85314768
has comment: http://stackoverflow.com/comment/85315207
has comment: http://stackoverflow.com/comment/85322266

http://stackoverflow.com/comment/85337721
type: AnswerComment
has text: @CIsForCookies: See also [Why do ints require three times as much memory in Python?](https://stackoverflow.com/questions/23016610/why-do-ints-require-three-times-as-much-memory-in-python) for a look at some of the internals. Although I still haven't found why Python only uses 30 bits of each "digit", and whether the digits are a base 2^30 or base-10^9 representation. Either way requires manual carry propagation that can't compile to `add`/`adc`, but rather `add` / `cmp` / `adc` or similar. (e.g. [like this extended-precision asm Fibonacci](https://codegolf.stackexchange.com/a/135618/30206))
comment on: http://stackoverflow.com/a/49154022
score: 1
type: Comment

http://stackoverflow.com/q/49141002
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85292306
answer count: 1
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/49196211
type: Question
has answer: http://stackoverflow.com/a/49196211
tagged with: python
has comment: http://stackoverflow.com/comment/85309500
has title: TensorFlow LSTM for 4-D Tensor
tagged with: lstm
has body: if I have an input with shape [None, None, None, 10], I want to do something like the following, input = tf.placeholder([None, None, None, 10], dtype=tf.float32) length = tf.placeholder([None, None], dtype=tf.int32) cell = tf.nn.rnn_cell.BasicLSTMCell(num_units=10) def fn(inp): output, _ = tf.dynamic_rnn(cell, inp[0], sequence_length=inp[1]) return output tf.map_fn(fn, (input, length), dtype=tf.float32) But it does not work for the automatic gradient derivation, which produces error like the following, Cannot use 'XXX' as input to 'gradients/YYY/while/TensorArrayWrite/TensorArrayWriteV3_grad/TensorArrayReadV3/f_acc' because 'XXX' is in a while loop. Is this a limitation of TensorFlow that it cannot handle the nested while_loop (dynamic_rnn and map_fn both run a while_loop behind the scene), or there is a way to work around this ?

http://stackoverflow.com/comment/85535656
score: 1
has text: For the port used for the single connection for a request, check on ``connectionSocket``, not ``serverSocket``. That for ``serverSocket`` would always be 80, being the listener socket only.
comment on: http://stackoverflow.com/q/49265102
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49204234
answers question: http://stackoverflow.com/q/49203098
score: 0
has body: I solved it! The problem was that the reshape call should've been flattened = tf.reshape(pool2, [-1, 1, 1 * 30 * 32])
accepted answer of: http://stackoverflow.com/q/49203098
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/49212682
has comment: http://stackoverflow.com/comment/85429909
downvote count: 0
answer count: 1
has body: I have a very, very large dataframe that resembles this: +---+--------+--------+--------+--------+ | | code_1 | code_2 | code_3 | code_4 | +---+--------+--------+--------+--------+ | 1 | abc | def | ghi | jkl | | 2 | zzz | zzz | zzz | zzz | | 3 | def | zzz | zzz | zzz | | 4 | abc | abc | abc | abc | | 5 | lol | lol | lol | lol | +---+--------+--------+--------+--------+ I need to go through each row and match the set a codes against a set of approved codes. For the example above, the set of approved codes is ['abc', 'def'] If a given rows has any matches against the approved codes I would like to return True to add to a new column, otherwise return False. Given the approved codes above, the output would be as follows: +---+--------+--------+--------+--------+------------+ | | code_1 | code_2 | code_3 | code_4 | is_primary | +---+--------+--------+--------+--------+------------+ | 1 | abc | def | ghi | jkl | TRUE | | 2 | zzz | zzz | zzz | zzz | FALSE | | 3 | def | zzz | zzz | zzz | TRUE | | 4 | abc | abc | abc | abc | TRUE | | 5 | lol | lol | lol | lol | FALSE | +---+--------+--------+--------+--------+------------+ Right now my method for performing this task is as follows: def assign_primary(row, codes): is_primary = any(i in row.values for i in codes) if is_primary: return True return False df['is_primary'] = df.apply(lambda row: assign_primary( row, ['abc', 'def']), axis=1) This works, but is impossibly slow on my large data set. I am matching 15 cols against an approved code list of 100 over 2 million rows. I'm looking for faster implementations if anyone has methods for doing this.
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49212697
upvote count: 2
linked to: http://stackoverflow.com/q/48510555
has answer: http://stackoverflow.com/a/49212697
has title: Faster method for finding any matching values in subset of pandas columns against a list
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: pandas

http://stackoverflow.com/q/49184811
has answer: http://stackoverflow.com/a/49255508
tagged with: python
has comment: http://stackoverflow.com/comment/85385990
has comment: http://stackoverflow.com/comment/85403924
has comment: http://stackoverflow.com/comment/85375524
has body: I have created the function below which returns a vector based on two input vectors. I have a pandas dataframe with different columns and I would like to apply that function to some columns of my dataframe (one pandas column would be the first vector of my function (nominal), another one the second vector of my function(CPI) and I would assign the result of my function to a new pandas column). How could I do it? Thank you very much for your help, Pierre nominal=[10,10,10,10,10,10,10,10,10,10,10,10] CPI=[0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02,0.02] def nominal_to_real(nominal,CPI): real=[] product=1 for i in range(len(nominal)): product*=(CPI[i]+1)**(1/12) real.append(nominal[i]/product) return real
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85376561
tagged with: function
answer count: 1
has title: Apply a function on a pandas column
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85375507
has comment: http://stackoverflow.com/comment/85385839
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49255508
has comment: http://stackoverflow.com/comment/85375362
tagged with: pandas
has comment: http://stackoverflow.com/comment/85386032
score: 1

http://stackoverflow.com/comment/85294077
comment on: http://stackoverflow.com/a/49143918
score: 1
type: Comment
type: AnswerComment
has text: Thank you! That fixed it for me

http://stackoverflow.com/comment/85344247
has text: can you give any sample o/p ?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49169465

http://stackoverflow.com/comment/85365587
type: Comment
has text: @JanMusil I don't know why you're seeing "stairs". Post a complete example of code and data that I can run that shows that, and maybe I can help you. Or, better, post it as a new question, and the whole SO community can help you.
type: AnswerComment
comment on: http://stackoverflow.com/a/49179763
score: 0

http://stackoverflow.com/comment/87908874
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49158400
has text: I almost had it working by renaming `C:\ProgramData\Anaconda2\DLLs\sqlite3.dll` to `sqlite3_old.dll`. For a while it was picking up the right version, but now it's gone back to the wrong version. I'm obviously going to have to find all the `sqlite3.dll`s on my machine and delete or rename them until there is only one left.

http://stackoverflow.com/a/49199269
type: Answer
score: 0
has body: Out of curiosity I tried putting the most recent date as the start of the selection, and the less recent date as the end. To my surprise this worked but the Time series data was in reverse order. In: aapl.loc[pd.Timestamp('2010-12-30'):pd.Timestamp('2010-11-01')] So... duh I realised my Timeseries data must be in reverse order. The question now becomes, how do I sort a DatetimeIndex df into the correct order? Desired order would have nth date as the last row, and the earliest date as the first row. ******EDIT****** aapl.index = pd.to_datetime(aapl.index) aapl = aapl.sort_index(ascending=True) aaplrange = aapl.loc[pd.Timestamp('2010-11-01'):pd.Timestamp('2010-12-30')] Works!
answers question: http://stackoverflow.com/q/49197131

http://stackoverflow.com/a/49173672
has body: This is a property of the Fourier transformation that also appears in the FFT. Actually, if you plot the full data, you'll see a second peak. You might want to check numpy.fft.fftfreq at what frequency this actually is. The frequecies in an FFT usuall go [0, df,..., fmax, -fmax, ..., -df]. So your first peak is at omega, the second at -omega. This is because it is a complex analysis, meaning the Fourier Kernel is exp( -1j * omega * t). As sin( omega * t) = 1 / 2j * ( exp( 1j * omega * t) - exp( -1j * omega * t)), you'll get the two peaks. In the opposite direction, with a peak amplitude A you'll have your signal as A * exp( 1j * omega * t) + (-A * exp( 1j * (-omega) * t). If you expand this you'll get 1j * 2 * A * sin( omega * t ). Hence A is and must be half the amplitude of your sine wave.
answers question: http://stackoverflow.com/q/49172828
has comment: http://stackoverflow.com/comment/85396215
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/85396990
has comment: http://stackoverflow.com/comment/85383569
downvote count: 0
score: 4

http://stackoverflow.com/comment/85644528
has text: @StevenFines if you come across a fix, please let me know! :)
comment on: http://stackoverflow.com/q/49235092
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/49173374
downvote count: 2
has body: Once you load a JSON file into Python it becomes a dictionary. You can iterate through it like this: for key, value in data.items(): if value == something: new_value = do_something(value) data[key] = new_value I'm not really sure what exactly you're trying to do, but this should help you get started.
has comment: http://stackoverflow.com/comment/85351983
has comment: http://stackoverflow.com/comment/85351719
score: -2
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/49173204

http://stackoverflow.com/comment/85538580
type: QuestionComment
has text: "returns 4 strings". Do you mean it returns a list of 4 strings, or it returns a single string with 4 space-separated words?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49267452

http://stackoverflow.com/a/49181975
answers question: http://stackoverflow.com/q/49180826
has body: You can do this by adding the value to the many to many table. In order to be able to do this you would need to create a custom many to many table. See the django documentation for an example.
score: 0
type: Answer

http://stackoverflow.com/comment/85287689
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49140941
type: Comment
has text: The easiest way is to learn about forms and how to use them with flask. You can use the form to collect information from the visitor for the code that will run, and then send the result back to the visitor.

http://stackoverflow.com/comment/85433301
type: AnswerComment
has text: OP: "I can't use format or ljust to format my answer." Presumably this includes rjust, but I've no idea.
comment on: http://stackoverflow.com/a/49214411
score: 0
type: Comment

http://stackoverflow.com/q/49180092
has title: importing data in Hebrew to python
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49180206
has answer: http://stackoverflow.com/a/49180206
type: AnsweredQuestion
has body: Hello I am new to python. I have a data frame called psagot which has one column called SHEM_NIYAR_HEB with values in Hebrew .When I import the data to python I get gibberish instead of the real values. I read on the internet that the following code could help encode('cp1252').decode('cp1255',errors='replace') The code works well when I apply it to one value at a time for example the following code will fix the third value of the column SHEM_NIYAR_HEB t=psagot.iloc[:,3] t=t.iloc[3] t=t.encode('cp1252').decode('cp1255',errors='replace') The problem arises when I try to apply this for the entire column .This is the code : t=psagot.iloc[:,3] t=t.encode('cp1252').decode('cp1255',errors='replace') The error I get states AttributeError: 'Series' object has no attribute 'encode' Is there a quick way to change all values in the column. Any help will be highly appreciated.
downvote count: 2
answer count: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85365841
favorite count: 0
type: Question
tagged with: hebrew

http://stackoverflow.com/comment/85378073
type: AnswerComment
comment on: http://stackoverflow.com/a/49185697
has text: checking if there is ['after'] field in those if statements like what that dude did? that dude called requests in each step and seperated in formatted urls. and his logic seemed very alien to me, i dont know if it work but definitely its worth to try. thank you sincerely, python is joy to tinker after countless js frameworks i worked by.
type: Comment
score: 0

http://stackoverflow.com/comment/85489327
comment on: http://stackoverflow.com/a/49204296
type: AnswerComment
has text: Thank you very much for this! I am going to use `np.einsum()`, because it seems to be faster than the other options. For `data=np.random.random((50000,100))`, `scale_matrix` takes 23 seconds, `np.matmul()` takes 0.3 seconds, and `np.einsum()` takes 0.1 seconds.
score: 0
type: Comment

http://stackoverflow.com/a/52758652
has body: You can also download a file using the project structure present in Google Colaboratory. Step 1: Click on the chevron-right icon at the top left corner. Step 2: Select the Files tab. Step 3: Right click on the file you want to download and select the Download option. Here's a screenshot:
score: 7
downvote count: 0
upvote count: 7
type: Answer
answers question: http://stackoverflow.com/q/49208567

http://stackoverflow.com/comment/110654968
type: Comment
type: AnswerComment
has text: in the first code block, line 9, `thumb_io.get_value()` should be `thumb_io.getvalue()` (no underscore in `getvalue()`)
comment on: http://stackoverflow.com/a/49296707
score: 2

http://stackoverflow.com/q/49239476
has body: I am using df.style.applymap to render a pandas dataframe. I chose style instead of to_html as I needed css applied based on some of the column values. The challenge is that I want to exclude one of those columns from display. So, with the following code: html = df.style.applymap(color_cell, subset=['columnName']).render() with open('output.html', 'w') as f: f.write(html) Is there way I can exclude/hide a column that I require for styling other columns?
score: 1
has comment: http://stackoverflow.com/comment/85483307
has comment: http://stackoverflow.com/comment/85482755
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has title: Hide a Pandas Column while using style.apply
accepted answer: http://stackoverflow.com/a/49239884
has answer: http://stackoverflow.com/a/49239884
tagged with: python
possible better answer: http://stackoverflow.com/a/54925266
tagged with: pandas-styles
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/54925266
answer count: 2
tagged with: pandas

http://stackoverflow.com/comment/85525695
type: AnswerComment
has text: Thanks a lot - made it work. If you have time for one more question, could you tell me how I only get one value, e.g. the odds or the time the game starts?
score: 0
comment on: http://stackoverflow.com/a/49260303
type: Comment

http://stackoverflow.com/q/49269299
has answer: http://stackoverflow.com/a/49269362
type: Question
has comment: http://stackoverflow.com/comment/85542661
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49269342
has answer: http://stackoverflow.com/a/49269335
has comment: http://stackoverflow.com/comment/85542602
tagged with: sorting
has body: I noticed that the results are different of the two lines. One is a sorted list, while the other is a sorted dictionary. Cant figure out why adding .item will give this difference: aa={'a':1,'d':2,'c':3,'b':4} bb=sorted(aa,key=lambda x:x[0]) print(bb) #['a', 'b', 'c', 'd'] aa={'a':1,'d':2,'c':3,'b':4} bb=sorted(aa.items(),key=lambda x:x[0]) print(bb) # [('a', 1), ('b', 4), ('c', 3), ('d', 2)]
score: 0
answer count: 3
has title: Python: about sort
has comment: http://stackoverflow.com/comment/85542648
has comment: http://stackoverflow.com/comment/85542240
tagged with: python

http://stackoverflow.com/a/49159335
upvote count: 1
has comment: http://stackoverflow.com/comment/85324302
has comment: http://stackoverflow.com/comment/85323993
has comment: http://stackoverflow.com/comment/85324452
has body: Just to add, if you do want to make this check (without relying on an implementation detail (which even then, won't be in python 3.7)), just do from collections import OrderedDict &gt;&gt;&gt; data = OrderedDict(zip('xy', 'xy')) &gt;&gt;&gt; def foo(**kwargs): ... return OrderedDict(kwargs) == data since this is guaranteed to be True.
has comment: http://stackoverflow.com/comment/85323872
type: Answer
has comment: http://stackoverflow.com/comment/85324079
has comment: http://stackoverflow.com/comment/85324395
has comment: http://stackoverflow.com/comment/85324186
has comment: http://stackoverflow.com/comment/85323800
has comment: http://stackoverflow.com/comment/85324072
score: 1
answers question: http://stackoverflow.com/q/49159238
downvote count: 0

http://stackoverflow.com/comment/133833605
has text: Aside from this being a duplicate, `return(str)` in this code makes absolutely no sense, and neither does the `print` in `print(printsql(a))`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49222820
score: 0

http://stackoverflow.com/q/49155113
upvote count: 2
accepted answer: http://stackoverflow.com/a/49156420
has answer: http://stackoverflow.com/a/49156420
tagged with: python
tagged with: keras
has title: Load and Check Total Loss / Validation accuracy of Keras Sequential Model
type: AnsweredQuestion
score: 2
has body: I didn't find any answers to the following question: Is there a way to print the trained model accuracy, total model loss and model evaluation accuracy after loading the saved trained Keras model? from keras.models import load_model m = load_model.load("lstm_model_01.hd5") I checked all the callable methods of m but didn't find what I was looking for.
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/50254217
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/50254217

decode
tag name: decode
tags question: http://stackoverflow.com/q/49260004
tags question: http://stackoverflow.com/q/49268117
tags question: http://stackoverflow.com/q/49255915
type: Tag

http://stackoverflow.com/a/49279198
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49158684
has body: Problem was occuring because the HOME and HOMEDRIVE python environmental variables were set to O:. This could be checked by os.environ['HOME'] in another python interpreter on the computer (in this case, from QGIS). I fixed it by putting import os os.environ['HOME']='C:\\' os.environ['HOMEDRIVE']='C:' at the beginning of the spyder-script.py and anaconda-navigator-script.py under C:\Anaconda3\Scripts
type: Answer
answers question: http://stackoverflow.com/q/49158684

http://stackoverflow.com/q/49187774
upvote count: 4
type: AnsweredQuestion
downvote count: 0
answer count: 1
tagged with: django-rest-framework
tagged with: postman
has body: When I try to send a JSON using a Django REST framework, I get this error: TypeError at /usermanagement/user/ the JSON object must be str, not 'bytes' My post fuction: def post(self,request): user=json.loads(request.body) m_user= user.get('m_name', None) m_email = user.get('m_email', None) m_age=user.get('m_age', None) m_status = user.get('u_status_id', None) user = M_User(m_name=m_name, m_email=m_email, m_age=m_age, u_status_id=m_status) user.save() if user.save: user=M_User.objects.filter(m_user=m_user) serializer = M_Userserializer(user,many=True) context = { 'success': "true", 'user': serializer.data } elif not user.save: context={ 'success':"false" } else: context={ 'success':"false" } return Response(context)
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49187807
has comment: http://stackoverflow.com/comment/85381617
has answer: http://stackoverflow.com/a/49187807
has title: Parsing DRF request body: TypeError the JSON object must be str, not 'bytes'
tagged with: django
tagged with: python
score: 4

http://stackoverflow.com/comment/85440885
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49217493
has text: Thank you everyone for your help! I also understand now the numerator term in the `nltk` implementation of `jaccard_distance()`, which arises from performing the 1 - Jaccard Similarity.
score: 1

build
tag name: build
tags question: http://stackoverflow.com/q/49266003
type: Tag

http://stackoverflow.com/comment/85555277
type: QuestionComment
score: 1
has text: @ArpitSolanki This will add one hour, but it's not what I am looking for
type: Comment
comment on: http://stackoverflow.com/q/49276429

http://stackoverflow.com/a/49147005
has body: Try replacing "params=querystring" with "data=querystring" response = requests.request("POST", url, headers=headers, data=querystring) params seems to be for GET requests and may by your request URL becomes too long after 30 lines of XML. From docs at : http://docs.python-requests.org/en/master/user/quickstart/
answers question: http://stackoverflow.com/q/49145666
score: 1
type: Answer
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85302962
has comment: http://stackoverflow.com/comment/85300237

http://stackoverflow.com/q/49166292
possible better answer: http://stackoverflow.com/a/49166437
has answer: http://stackoverflow.com/a/49166437
type: Question
tagged with: arguments
tagged with: python
has title: How to set keyword arguments values as other keyword arguments?
accepted answer: http://stackoverflow.com/a/49166432
tagged with: abstraction
has answer: http://stackoverflow.com/a/49166432
type: AnsweredQuestion
answer count: 2
score: 0
tagged with: refactoring
has body: Is there a (clean, easy) way to set keyword args as other keyword args in a parameters list? Something like this: class Foo(): def __init__(self, kwarg1='a', kwarg2=kwarg1, kwarg3=kwarg1): I basically need all three to have the same default value without hard coding it in. That way if the user wants to edit kwarg1to be something else, the default of kwarg2 and kwarg3 will default to the new value as well; but will still allow the functionality of customizing kwarg2 and kwarg3 if desired. I imagine I can do something like this: class Foo(): def __init__(self, kwarg1='a', kwarg2='', kwarg3=''): if kwarg2 == '': self.kwarg2 = kwarg1 if kwarg3 == '': self.kwarg3 = kwarg1 It's just kind of ugly. I know this is an odd question. Just kinda curious if there is a cleaner way to accomplish this.
tagged with: keyword

http://stackoverflow.com/comment/85502236
has text: @JorgeReyes, once you have a list, you can use a range of values as indices or a discrete list of numbers for indices. Your posted code indicated that you wanted to use a range of values for indices. This answer addresses your post accurately.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49248703
type: Comment

http://stackoverflow.com/comment/85478253
score: 0
has text: You've described what you want, but not what went wrong when you tried to do it, or how your attempts to overcome those problems failed. Right now it sounds like you just have a specification, not a question.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49237433

http://stackoverflow.com/comment/85461058
has text: What errors are you getting?
score: 0
comment on: http://stackoverflow.com/q/49221014
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49152145
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49152034
score: 0
accepted answer of: http://stackoverflow.com/q/49152034
has comment: http://stackoverflow.com/comment/85309296
has body: Your error is because of the below snippet. raw_data = {L} Change it to raw_data = L #or df = pd.DataFrame(L, columns = ['array'])

http://stackoverflow.com/q/49147403
tagged with: python
has comment: http://stackoverflow.com/comment/85301343
tagged with: dictionary
score: -1
has comment: http://stackoverflow.com/comment/85299397
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85299465
has body: I have a python dict like this: { "stationlist": { "tunein": { "@base-m3u": "/sbin/tunein-station.m3u", "@base": "/sbin/tunein-station.pls", "@base-xspf": "/sbin/tunein-station.xspf" }, "station": [ { "@lc": "34753", "@br": "128", "@mt": "audio/mpeg", "@name": "Dance Wave Retro!", "@id": "1057402", "@genre": "Urban Contemporary" }, { "@lc": "12847", "@br": "64", "@logo": "http://i.radionomy.com/document/radios/a/a265/a2654f5f-669e-4b9e-ac13-962971886ad2.jpg", "@mt": "audio/aacp", "@name": "COOLfahrenheit 93 - (7)", "@id": "1735956", "@ct": "25 Hours - #11D8'1 (Soft Version)", "@genre": "Easy Listening", "@genre2": "Pop" }, ... ... I need to remove @ symbol from all the keys in the dict on all hierarchical levels. Tried this : Removing special characters from dictionary productDictionary=dict(map(str.strip,x) for x in productDictionary.items()) Did not help much. Thanks in advance for any help!
tagged with: http://stackoverflow.com/tag/json
downvote count: 3
has comment: http://stackoverflow.com/comment/85308878
accepted answer: http://stackoverflow.com/a/49147901
tagged with: loops
answer count: 1
has answer: http://stackoverflow.com/a/49147901
favorite count: 0
linked to: http://stackoverflow.com/q/14366332
has comment: http://stackoverflow.com/comment/85299709
type: Question
has title: Remove special characters from all hierarchical levels in a dict - Python

css
tags question: http://stackoverflow.com/q/49178621
tags question: http://stackoverflow.com/q/49215787
tags question: http://stackoverflow.com/q/49200946
tags question: http://stackoverflow.com/q/49225034
tags question: http://stackoverflow.com/q/49197269
tags question: http://stackoverflow.com/q/49244469
tags question: http://stackoverflow.com/q/49171370
tags question: http://stackoverflow.com/q/49168556
tag name: css
tags question: http://stackoverflow.com/q/49244372
tags question: http://stackoverflow.com/q/49209753
tags question: http://stackoverflow.com/q/49122003
type: Tag

http://stackoverflow.com/q/49140540
has answer: http://stackoverflow.com/a/49140721
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49140812
has title: Python nested loop miscounting instances of integers in list
has answer: http://stackoverflow.com/a/49140924
answer count: 5
has comment: http://stackoverflow.com/comment/85286727
possible better answer: http://stackoverflow.com/a/49140621
type: Question
accepted answer: http://stackoverflow.com/a/49140744
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49140621
has comment: http://stackoverflow.com/comment/85286569
has answer: http://stackoverflow.com/a/49140744
has body: I'm banging my head against the wall trying to figure out why this nested loop is miscounting the number of times an integer occurs in a list. I've set up a function to take two lines of input, n and ar, where n is the number of integers in ar and ar is the list of integers. My code is below: import sys n = sys.stdin.readline() n = int(n) ar = sys.stdin.readline() ar = ar.split(' ') ar = [int(i) for i in ar] def find_mode(n,ar): # create an empty dict and initially set count of all integers to 1 d = {} for i in range(n): d[ar[i]] = 1 for i in range(n): # hold integer i constant and check subsequent integers against it # increase count if match x = ar[i] for k in range(i+1,n): if ar[k] == x: d[ar[k]] += 1 print(d) The counter seems to be increasing the count by 1 every time, which leads me to believe it's a problem with the nested loop. &gt;&gt;&gt; 9 &gt;&gt;&gt; 1 2 3 4 4 9 9 0 0 {0: 2, 1: 1, 2: 1, 3: 1, 4: 2, 9: 2} OK &gt;&gt;&gt; 10 &gt;&gt;&gt; 1 2 3 4 4 9 9 0 0 0 {0: 4, 1: 1, 2: 1, 3: 1, 4: 2, 9: 2} Count of 0 increased by +2 &gt;&gt;&gt; 11 &gt;&gt;&gt; 1 2 3 4 4 9 9 0 0 0 0 {0: 7, 1: 1, 2: 1, 3: 1, 4: 2, 9: 2} Count of 0 increased by +3 I understand there might be more efficient or "pythonic" ways to count the amount of times a number occurs in a list but this was the solution I came up with and as someone still learning Python, it would help to understand why this exact solution is failing. Many thanks in advance.
tagged with: nested-loops
tagged with: python
has comment: http://stackoverflow.com/comment/85289631

http://stackoverflow.com/comment/85622928
has text: Maybe a library shared object conflict? Does it still work if you do the `pyeemd` import last?
score: 0
comment on: http://stackoverflow.com/q/49214915
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49159596
tagged with: python
has comment: http://stackoverflow.com/comment/85324399
has comment: http://stackoverflow.com/comment/85325181
has comment: http://stackoverflow.com/comment/85325323
has comment: http://stackoverflow.com/comment/85325272
downvote count: 0
tagged with: pytest
score: 1
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85325386
has comment: http://stackoverflow.com/comment/85325328
has answer: http://stackoverflow.com/a/49159731
has comment: http://stackoverflow.com/comment/85325150
has title: How do I get pytest to ignore a specific subprocess call that returns non-zero code and writes to stderr?
favorite count: 0
type: Question
has body: My code (within pytest) is: try: proc = subprocess.check_output(['somedaemon', '-v'], stderr=subprocess.STDERR) assert str(proc) is False, 'somedaemon returned a version number, should be uninstalled' except subprocess.CalledProcessError: # There was an error - command exited with non-zero code pass My desire here is that a passing test has the subprocess call to somedaemon return a non-zero return code and output on stderr and still pass. I can't seem to get pytest to ignore the error in this case. In other words a try without except is a failure. Failure of the subprocess is expected. Pytest's more global error catching is defeating me and I haven't found a way of overriding it. OS is CentOS 7. After applying Branden's solution below, I got the following result (these are snippets from pytest's error reporting): A. here is a pdb next through the subprocess call: -> proc = subprocess.Popen(['cbdaemon', '-v'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (Pdb) n FileNotFoundError: [Errno 2] No such file or directory: 'cbdaemon' B. in the error report, we are entering subprocess.py: /root/.pyenv/versions/3.6.0/lib/python3.6/subprocess.py:707: in init restore_signals, start_new_session) C. subprocess.py has a raise child_exception_type that raises the error: if errno_num != 0: err_msg = os.strerror(errno_num) if errno_num == errno.ENOENT: if child_exec_never_called: # The error must be from chdir(cwd). err_msg += ': ' + repr(cwd) else: err_msg += ': ' + repr(orig_executable) raise child_exception_type(errno_num, err_msg) E FileNotFoundError: [Errno 2] No such file or directory: 'cbdaemon' /root/.pyenv/versions/3.6.0/lib/python3.6/subprocess.py:1326: FileNotFoundError This might be an intractable problem. I looked through a lot of pytest documents and can't find a way to exclude this failure from the overall test failure. The error is coded into subprocess.py.
type: UnansweredQuestion
tagged with: stderr

http://stackoverflow.com/a/49138226
type: Answer
has comment: http://stackoverflow.com/comment/85281628
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49138119
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49138119
has comment: http://stackoverflow.com/comment/85281643
has body: To the best of my knowledge, you can vectorize this with a groupby + transform: df[~(df.Text.eq('abc').groupby(df.ID).transform('any') &amp; df.Text.eq('xyz'))] ID Text 0 1 abc 3 2 abc 5 3 abc 6 3 ijk 7 4 xyz

http://stackoverflow.com/a/49150105
has body: Instead of using evalf you want to look into using sympy.lambdify to generate a callback for use with SciPy. You will need to create a function with the expected signature of odeint, e.g.: y, params = sym.symbols('y:3'), sym.symbols('kf kb') ydot = rhs(y, p=params) f = sym.lambdify((y, t) + params, ydot) yout = odeint(f, y0, tout, param_values) We gave a tutorial on (among other things) how to use lambdify with odeint at the SciPy 2017 conference, the material is available here: http://www.sympy.org/scipy-2017-codegen-tutorial/ If you are open to use an external library to handle the function signatures of external solvers you may be interested in a library I've authored: pyodesys
accepted answer of: http://stackoverflow.com/q/49134256
answers question: http://stackoverflow.com/q/49134256
type: AcceptedAnswer
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/85320426
upvote count: 3
type: Answer

http://stackoverflow.com/comment/85347686
type: Comment
has text: Nope, `cron` simply kicks off the process, logs the event, and moves on.
type: AnswerComment
comment on: http://stackoverflow.com/a/49159121
score: 1

http://stackoverflow.com/comment/85775998
comment on: http://stackoverflow.com/q/49239665
type: Comment
type: QuestionComment
score: 0
has text: 1) Your testcode is completely memory bound. The CPU has almost nothing to do here. 2) In a more sophisticated example parallelize only the outer loop. Overparallization has a bad cache behaivour and comes with some overhead.

http://stackoverflow.com/comment/125770992
type: Comment
comment on: http://stackoverflow.com/a/49197435
type: AnswerComment
has text: This solution throws the same error for me
score: 0

http://stackoverflow.com/a/49166775
has comment: http://stackoverflow.com/comment/85341636
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49166701
has comment: http://stackoverflow.com/comment/85341512
accepted answer of: http://stackoverflow.com/q/49166701
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85341417
has comment: http://stackoverflow.com/comment/85341268
upvote count: 4
has body: Try cast to int64: df['user'] = df['user'].astype(np.int64) Or: df['user'] = df['user'].astype('int64') print (df['user']) 0 1101110110100 1 1111222555555 2 1112223365556 3 1113656560005 Name: user, dtype: int64 EDIT: #convert not parseable values to NaNs df['user'] = pd.to_numeric(df['user'], errors='coerce') #remove rows with NaNs df = df.dropna('user') df['user'] = df['user'].astype(np.int64) Or: df['user'] = pd.to_numeric(df['user'], errors='coerce').fillna(0) df['user'] = df['user'].astype(np.int64)
has comment: http://stackoverflow.com/comment/85341482

http://stackoverflow.com/q/49204190
accepted answer: http://stackoverflow.com/a/49204372
score: 1
has answer: http://stackoverflow.com/a/49204372
answer count: 1
tagged with: pymongo
downvote count: 0
upvote count: 1
favorite count: 0
has body: I can't seem to get this to work with pymongo it was working before I added the $or option. Am I missing something obvious with this dataout = releasescollection.find( { $or: [{"l_title":{"$regex": "i walk the line", "$options": "-i"}}, {"artistJoins.0.artist_name":{"$regex": "Johnny Cash", "$options": "-i"}}]}).sort('id', pymongo.ASCENDING).limit(25) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "discogs.py", line 51 dataout = releasescollection.find( { $or: [{"l_title":{"$regex": "i walk the line", "$options": "-i"}}, {"artistJoins.0.artist_name":{"$regex": "Johnny Cash", "$options": "-i"}}]}) ^ SyntaxError: invalid syntax Running the below directly in mongo works but I'm missing something in the switchover to python db.releases.find( { $or: [{"l_title":{"$regex": "i walk the line", "$options": "-i"}}, {"artistJoins.0.artist_name":{"$regex": "Johnny Cash", "$options": "-i"}}]}).sort({'id':1}).limit(25)
type: AnsweredQuestion
tagged with: python
has title: PYTHON - PYMONGO - Invalid Syntax with $or
tagged with: mongodb-query
type: Question
tagged with: python-2.7

http://stackoverflow.com/a/49178087
score: 2
accepted answer of: http://stackoverflow.com/q/49176652
type: Answer
has body: Your problem is that mutating the list iterable is a bad strategy. Changes made to iterbale will always be reflected, because they are all the same object. If we use tuples instead, we can avoid this. Here's the recursive permutation code I came up with: def permute(iterable): iterable = tuple(iterable) if len(iterable) &lt;= 1: yield iterable return for i, x in enumerate(iterable): for sub_permutation in permute(iterable[:i] + iterable[i+1:]): yield (x,) + sub_permutation
answers question: http://stackoverflow.com/q/49176652
upvote count: 2
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85430155
type: Comment
type: QuestionComment
has text: i have tried that user=input(speak.Speak("enter your username\b")) 1 comes after the speak function ends but i dont know how can that happen
score: 0
comment on: http://stackoverflow.com/q/49212784

http://stackoverflow.com/q/49170056
type: UnansweredQuestion
has body: I want to fill columns 'level' and 'class' with respective values as '2' and '1' of subsetted data at once: data[(data["Main_Pressure"]&lt;100) &amp; data["Return_Pressure"]&lt;200]'level','class' = "2","1" After executing the above line Python console the columns 'level' and 'class' were not replaced with '2' and '1'. How to achieve this in a single line in Python?
tagged with: python
has comment: http://stackoverflow.com/comment/85345963
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85346420
has title: How to fill different values to two different columns in a subsetted data at once?
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85346398

http://stackoverflow.com/q/49271586
has answer: http://stackoverflow.com/a/50297147
score: 9
has title: ValueError: wrapper loop when unwrapping
answer count: 2
has body: Python3 test cases (doctests) are failing with my sample code. But the same is working fine in Python2. test.py: class Test(object): def __init__(self, a=0): self.a = a def __getattr__(self, attr): return Test(a=str(self.a) + attr) tst.py: from test import Test t = Test() Run test cases: python3 -m doctest -v tst.py Error: Traceback (most recent call last): File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/usr/lib/python3.6/doctest.py", line 2787, in <module> sys.exit(_test()) File "/usr/lib/python3.6/doctest.py", line 2777, in _test failures, _ = testmod(m, verbose=verbose, optionflags=options) File "/usr/lib/python3.6/doctest.py", line 1950, in testmod for test in finder.find(m, name, globs=globs, extraglobs=extraglobs): File "/usr/lib/python3.6/doctest.py", line 933, in find self._find(tests, obj, name, module, source_lines, globs, {}) File "/usr/lib/python3.6/doctest.py", line 992, in _find if ((inspect.isroutine(inspect.unwrap(val)) File "/usr/lib/python3.6/inspect.py", line 513, in unwrap raise ValueError('wrapper loop when unwrapping {!r}'.format(f)) ValueError: wrapper loop when unwrapping <test.Test object at 0x7f6e80028550>
accepted answer: http://stackoverflow.com/a/49272249
downvote count: 0
possible better answer: http://stackoverflow.com/a/50297147
has answer: http://stackoverflow.com/a/49272249
tagged with: doctest
favorite count: 0
type: Question
type: AnsweredQuestion
upvote count: 9
tagged with: python

http://stackoverflow.com/comment/85321170
type: QuestionComment
type: Comment
score: 0
has text: That isn't an array, that is a `tuple` with a single element, which is the array. That is what you seem to not be grokking
comment on: http://stackoverflow.com/q/49157647

seaborn
tags question: http://stackoverflow.com/q/49175861
tags question: http://stackoverflow.com/q/49254337
tags question: http://stackoverflow.com/q/49227504
tags question: http://stackoverflow.com/q/49203408
tags question: http://stackoverflow.com/q/49211334
tags question: http://stackoverflow.com/q/49185427
tag name: seaborn
tags question: http://stackoverflow.com/q/49179154
tags question: http://stackoverflow.com/q/49184094
tags question: http://stackoverflow.com/q/49201174
tags question: http://stackoverflow.com/q/49266014
tags question: http://stackoverflow.com/q/49277182
tags question: http://stackoverflow.com/q/49264157
tags question: http://stackoverflow.com/q/49139299
type: Tag
tags question: http://stackoverflow.com/q/49265951

http://stackoverflow.com/q/49192027
type: AnsweredQuestion
score: 0
answer count: 3
tagged with: pandas
tagged with: dataframe
tagged with: python
has title: Create dataframe from array
has answer: http://stackoverflow.com/a/49196972
type: Question
has answer: http://stackoverflow.com/a/49192404
possible better answer: http://stackoverflow.com/a/49192404
has answer: http://stackoverflow.com/a/49192088
accepted answer: http://stackoverflow.com/a/49192088
linked to: http://stackoverflow.com/q/43973999
has body: I have data in the following form: [('06/03/2018 17.35.18.211', 'param_a', 1), ('06/03/2018 17.35.19.211', 'param_b', 1), ('06/03/2018 17.35.20.211', 'param_c', 1), ('06/03/2018 17.35.21.211', 'param_a', 2), ('06/03/2018 17.35.22.211', 'param_b', 2), ('06/03/2018 17.35.22.211', 'param_c', 2)] What would be the best way to create a dataframe out of it which looks like this: timestamp param_a param_b param_C 0 06/03/2018 17.35.18.211 1.0 NaN NaN 1 06/03/2018 17.35.19.211 NaN 1.0 NaN 2 06/03/2018 17.35.20.211 NaN NaN 1.0 3 06/03/2018 17.35.21.211 2.0 NaN NaN 4 06/03/2018 17.35.22.211 NaN 2.0 2.0
upvote count: 1
downvote count: 1
favorite count: 0

http://stackoverflow.com/q/49133317
has title: How to extract specific numbers from a matrix?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85271976
tagged with: matrix
has body: I have the following matrix: a = array([[100. , 100. , 100. ], [175.24163615, 198.31220183, 32.71406333], [150.36778472, 82.62453566, 38.51860719], [ 155.28247936, 191.50455896, 23.09254829], [ 36.4302652 , 67.34580186, 30.82481977]]) What I do is that I check each column and if the number in the third row is greater then 100 I change it into 21.75; if the number in the fourth row is greater then 100 I change it into 29. For this, I use the following code: Z1[2]=[21.75 if x&gt;100 else x for x in Z1[2]] Z1[3]=[29 if x&gt;100 else x for x in Z1[3]] What I am struggling with is to do the following. Once there is a change, I want to create an array with the changed number (only the first one in a given row) and if there is no change take the last one of a given row. Say, for the matrix above by running the code I will receive: a = array([[100. , 100. , 100. ], [175.24163615, 198.31220183, 32.71406333], [21.75, 82.62453566, 38.51860719], [ 29, 29, 23.09254829], [ 36.4302652 , 67.34580186, 30.82481977]]) So, the final array should look like: a = array([21.75, 29, 30.82481977]) Can anyone help me with this?
answer count: 0
tagged with: arrays
downvote count: 0
upvote count: 1
score: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85279988
type: Question

http://stackoverflow.com/a/49176557
upvote count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/91202418
has comment: http://stackoverflow.com/comment/85358833
score: 2
type: Answer
answers question: http://stackoverflow.com/q/49175961
has body: Consider having a separate feedforward network that takes in those features and outputs some n dimensional vector. time_independent = Input(shape=(num_features,)) dense_1 = Dense(200, activation='tanh')(time_independent) dense_2 = Dense(300, activation='tanh')(dense_1) Firstly, please use keras' functional API to do something like this. You would then either pass this in as the hidden state of the LSTM, or you can concatenate it with every word embedding so that the lstm sees it at every timestep. In the latter case, you would want to drastically reduce the dimensionality of the network. If you need an example, let me know.

http://stackoverflow.com/comment/85452858
score: 2
has text: Please don't post pictures of code or error messages, post the text directly here on SO.
comment on: http://stackoverflow.com/q/49224621
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49267376
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85538693
tagged with: python
has comment: http://stackoverflow.com/comment/85538614
has comment: http://stackoverflow.com/comment/85538564
has title: csv.writer adding quote to last term as well as extra line even with newline=''
has comment: http://stackoverflow.com/comment/85538283
score: 0
has comment: http://stackoverflow.com/comment/85539160
has comment: http://stackoverflow.com/comment/85541383
answer count: 0
has comment: http://stackoverflow.com/comment/85539124
type: Question
has body: Prefacing this question by stating that my Python 3 code IS using newline = '' (which was an answer to similar questions), but the behavior is persisting. This code reads in data from a really big comma delimited text file, buffers one day into a list, then writes that list to a csv file. I'm getting this odd behavior at the ends of the rows: Source data: "27/56/4382","81:00:00","5464.4","5464.4","5464.4","3\r\n" "27/56/4382","81:00:00","5464.4","5464.4","5464.4","3\r\n" Output looks like this: "27/56/4382","81:00:00","5464.4","5464.4","5464.4","3 " "27/56/4382","81:00:00","5464.4","5464.4","5464.4","3 " Code: with open(readfilepath,newline='') as f: for line in f: date1 = date2 # set date1 to date2 so don't get kicked out purchline= line # grab line parsedline = purchline.split(",") # split up line record date2 = parsedline[0] # grab date 2 if (date1 == date2): # if day hasn't flipped, continue to build buffer daybuffer.append(parsedline) else: # day has flipped. write buffer to file, clear buffer, then append this line (don't lose line!) # create writefilepath writedate = datetime.datetime.strptime(date1,"%M/%d/%Y").strftime("%Y%M%d") writefilename = "poa" + writedate + "purRaw.txt" writefilepath = writedirectorypath + writefilename # write daybuffer to csvfile with open(writefilepath,'w',newline='') as writecsv: purchwriter = csv.writer(writecsv) purchwriter.writerows(daybuffer) # wipe out daybuffer del(daybuffer[:]) # add last line to daybuffer daybuffer.append(parsedline) print("The day hath flipped.")

http://stackoverflow.com/q/49272370
has title: Multiple Data Files Read in Python
score: 0
tagged with: pandas
tagged with: python
has body: I have Data of different Stocks of various dates and each stock is stored in different Text Files (not in CSV) How to Gather up Data in some way into a Single File
favorite count: 0
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49272909
linked to: http://stackoverflow.com/q/20109391
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49272577
upvote count: 1
downvote count: 1
tagged with: data-science
has comment: http://stackoverflow.com/comment/85547437

http://stackoverflow.com/q/49152232
downvote count: 1
favorite count: 0
type: Question
score: 0
tagged with: algorithm
has comment: http://stackoverflow.com/comment/85320614
tagged with: python
has title: Largest subgraph with each couple of vertices connected by one edge
tagged with: graph
has comment: http://stackoverflow.com/comment/85309763
has comment: http://stackoverflow.com/comment/85309196
answer count: 0
has body: I'm quite a newbie in graph theory so I don't know if there's a name for such a subgraph, and thus I do not find much information about this. Say you have the following undirected graph : I'm looking for the right algorithm for finding the largest subgraph in which each vertex is linked with any other vertex by a path of exactly one edge. So in this example, it would be the subgraph 4, 5, 6. The subgraph 7,8 also works but is smaller, and the subgraph 0,1,2,3 doesn't work since 0 and 2 are not linked by one edge. If your code could be written in either javascript or python, I'd appreciate it ! But pseudo-code would be fine too.
type: UnansweredQuestion
tagged with: graph-algorithm
tagged with: javascript
upvote count: 1

http://stackoverflow.com/q/49242338
type: UnansweredQuestion
answer count: 1
tagged with: django
type: Question
score: 0
has body: gunicorn status gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor Active: failed (Result: exit-code) since Mon 2018-03-12 18:30:15 UTC; Process: 3535 ExecStart=/home/mike/movingcollage/movingcollageenv/bin/ Main PID: 3535 (code=exited, status=1/FAILURE) Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: File "/home/mike/mo Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: time.sleep(0.1) Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: File "/home/mike/mo Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: self.reap_workers Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: File "/home/mike/mo Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: raise HaltServer( Mar 12 18:30:15 ubuntu-2gb-nyc3-01 gunicorn[3535]: gunicorn.errors.HaltS Mar 12 18:30:15 ubuntu-2gb-nyc3-01 systemd[1]: gunicorn.service: Main pr Mar 12 18:30:15 ubuntu-2gb-nyc3-01 systemd[1]: gunicorn.service: Unit en Mar 12 18:30:15 ubuntu-2gb-nyc3-01 systemd[1]: gunicorn.service: Failed 29 ubuntu-2gb-nyc3-01 systemd[1]: gunicorn.service: Failed nginx error log: 2018/03/12 04:59:08 [error] 1562#1562: *1787 connect() to unix:/home/mik e/movingcollage/movingcollage.sock failed (111: Connection refused) whil e connecting to upstream, client: 107.205.110.154, server: movingcollage .com, request: "GET / HTTP/1.1", upstream: "http://unix:/home/mike/movin gcollage/movingcollage.sock:/", host: "movingcollage.com" My config is ok, this used to work; I pulled some new application code and am now getting a 502 bad gateway error (before I pulled the application code the site worked fine). I already did service gunicorn restart and systemctl restart gunicorn and am still getting the 502 bad gateway error. Can anyone help? This is a django project, for what it's worth. Gunicorn config: description "Gunicorn application server handling movingcollage" start on runlevel [2345] stop on runlevel [!2345] respawn setuid user setgid www-data chdir /home/mike/movingcollage …
tagged with: nginx
has comment: http://stackoverflow.com/comment/85489552
tagged with: python
has answer: http://stackoverflow.com/a/49244316
has comment: http://stackoverflow.com/comment/85489928
tagged with: gunicorn
has title: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> django project

http://stackoverflow.com/q/49170851
answer count: 1
downvote count: 0
tagged with: django
has title: Showing sensor reading in a django website
favorite count: 0
type: Question
score: 2
type: AnsweredQuestion
has body: I want to design a web based application for showing sound sensor readings, collected from an Arduino based setup (and also show some analysis results). For making my arduino setup work I had developed a python program named 'ard_sensor_project.py' which collects readings and store in .csv file and create a graph. Now I want to display the readings generated in a django website. For that I have imported 'ard_sensor_project.py' in views.py of my django site and called a method to print the sensor reading at real time. But on running the program, it seems that though the reading collecting module has started, the site has not started yet and I can neither see the web page nor any reading. Is there any way such that I can show the readings on the django site? Here is my ard_sensor_project.py import matplotlib.pyplot as plt from datetime import datetime #necessary declarations sr = serial.Serial("COM6",9600) #self declared methods def getsensordata(): st = list(str(sr.readline(),'utf-8')) return int(str(''.join(st[:]))) def storedata(fname,val1,val2): #stores data in a .csv file, will update if required def plotgraph(): #method for plotting data in a matplotlib graph, will update if required #codes as part of main execution + function calls print("------Reading collection starts now------") while True: try: timeNow = datetime.now().strftime("%d-%m-%Y %H:%M:%S") storedata('op.csv', timeNow, getsensordata()) #plotgraph() except KeyboardInterrupt: break sr.close() print("------Reading collection ends successfully------") Here is views.py of my django site from django.shortcuts import render # Create your views here. from django.template.loader import get_template from django.http import HttpResponse from . import ard_sensor_project as ard def index(request): return render(request,'start.html',{'noise_level':ard.getsenordata}) My runtime output : So it seems that the server is not at all running. When I replace ard.getsensordata by 0 (also removing ard import), I get : Now …
has answer: http://stackoverflow.com/a/49173337
tagged with: webserver
tagged with: python
has comment: http://stackoverflow.com/comment/85349511
has comment: http://stackoverflow.com/comment/86819865
accepted answer: http://stackoverflow.com/a/49173337
upvote count: 2

http://stackoverflow.com/q/49221550
tagged with: pandas
has comment: http://stackoverflow.com/comment/85447052
upvote count: 7
has answer: http://stackoverflow.com/a/49382694
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has body: I am trying to insert a dataframe into MongoDB. Each row should be one document. from pymongo import MongoClient import pandas as pd client = MongoClient() col = client['test']['test'] d = {'name': ['Braund', 'Cummings', 'Heikkinen', 'Allen'], 'age': [22,38,26,35], 'fare': [7.25, 71.83, 0 , 8.05], 'survived?': [False, True, True, False]} df = pd.DataFrame(d) col.insert_many(df) However, the above code returns an error: ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). Changing col.insert_many(df) to col.insert_many(df.to_dict()) or col.insert_many(df.to_json()) causes TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping
score: 7
accepted answer: http://stackoverflow.com/a/49382694
tagged with: python
has title: Pandas - insert a dataframe to MongoDB
type: AnsweredQuestion
tagged with: mongodb

http://stackoverflow.com/q/49235268
has body: I’m thinking if it is possible to perform a “pairing” between two lists (so one list acts like the answer to the other). Let’s say that LIST A (obtained from an iteration) is like this: [RESULT 1, X] [RESULT 2, Y] [RESULT 3, X, Y] [RESULT 4, Z, Y] [RESULT 5, Z] [RESULT 6, Z, X] and that LIST 2 is: [X, 12, 56, 2] [Y, 100] [Z, 22, 78, 00, 01, 5] I’d like to substitute X, Y, Z... in LIST1 by their respective data (that is available in LIST2, so the final result is something like this: [RESULT 1, [X, 12, 56, 2]] [RESULT 3, [X, 12, 56, 2], [Y, 100]] or [RESULT 1, X, 12, 56, 2] [RESULT 3, X, 12, 56, 2, Y, 100] What is the pythonic way to achieve this? Thank you very much for any help.
possible better answer: http://stackoverflow.com/a/49235380
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49235380
has title: Pairing elements of two lists
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/49235522
has comment: http://stackoverflow.com/comment/85473639
tagged with: pandas
score: 0
has comment: http://stackoverflow.com/comment/85473740
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/49235593
favorite count: 0
accepted answer: http://stackoverflow.com/a/49235522
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/85330239
comment on: http://stackoverflow.com/a/49162151
type: Comment
has text: Thanks @Alan , I did as you advised and now I have this:Reverse for 'posts' with arguments '(1,)' not found. 1 pattern(s) tried: ['posts/$']
type: AnswerComment
score: 0

http://stackoverflow.com/a/49240909
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49240801
type: Answer
has body: Try adding the following lines after all your defs. if __name__=='__main__': start() Also, everytime you call a function it needs to be followed by parenthesis, example: sign = Button(rootE, text='register', command=Signup) login = Button(rootE, text='log in', command=Login) Should be: sign = Button(rootE, text='register', command=Signup()) login = Button(rootE, text='log in', command=Login())
score: 0
accepted answer of: http://stackoverflow.com/q/49240801

http://stackoverflow.com/a/49211382
downvote count: 1
type: Answer
score: -1
has body: the name doesn't matter but if you are gonna initialize a lot of objects you are still gonna make it reasonable somehow
answers question: http://stackoverflow.com/q/49211118
upvote count: 0

http://stackoverflow.com/q/49164853
score: 0
accepted answer: http://stackoverflow.com/a/49164868
has body: I'm struggling with a few things right now using python dataframes. I have one column with a long list of numbers ranging from 1-5. For example, the column contains the values (3.6, 2.1, 4.7, 3.8, 1.9, etc., etc.). What I want to do is round each number to the nearest HALF number (not the nearest whole number). What I want to do is create a new column that would return the values (3.5, 2.0, 4.5, 4.0, 2.0, etc.). Conceptually, this is super easy, but I'm having trouble doing this within the dataframe. My initial idea was to use the int function to get a value rounded to the nearest whole number. Then I would subtract my initial value from that. Then, based on the returned value, I would determine how to round each value. So far, however, I've been unsuccessful. I keep running into the following error for example: "cannot convert the series to " DataFrame
answer count: 1
has answer: http://stackoverflow.com/a/49164868
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
has title: Rounding Python Values to the Nearest Half Number
tagged with: dataframe
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/49226365
has body: The file constructor was already discouraged in Python 2.5 (maybe even earlier) in favor of the open function. In Python 3, it was removed entirely. So, it should just be a matter of: f=open(filename, 'rb') Note that, unlike your second version, I did not remove the 'rb' "mode" argument. That b means "binary mode", and it's even more important in Python 3 than in Python 2. Without it, you're asking it to decode the file to Unicode text (using some default encoding), which isn't going to work with a binary file—it's going to give you something like the output in the second half of your question. As a side note, you may want to rewrite the function like this: def load_model(filename): with open(filename, 'rb') as f: return pickle.load(f) This guarantees that the file gets closed even if unpickling raises an exception.
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49226243

http://stackoverflow.com/q/49213585
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49213646
tagged with: machine-learning
tagged with: dataframe
tagged with: python
has body: I would like to save predicted output as a CSV file. In Python, how can I save Naive Bayes, SVM, RF and DT Classification for final predictions for all samples saved as a .csv file with three columns, namely Sample, Actual value, Prediction values. My code is as follows: pred_scores = [] for i in np.linspace(0.05, 1, num=20): mnb = MultinomialNB(alpha=i) mnb.fit(features_train, labels_train) pred = mnb.predict(features_test) pred_scores.append((i, [accuracy_score(labels_test,pred)])) df = pd.DataFrame.from_items(pred_scores,orient='index', columns=['Score']) df.plot(figsize=(11,6)) print(df[df['Score'] == df['Score'].max()]) df_NB=df['Score'].max()
has title: In Python How I can save Naive Bayes, SVM, RF and DT Classification for final predictions for all samples saved as a .csv
score: 0
tagged with: pandas
answer count: 1

http://stackoverflow.com/comment/85312462
has text: as in try to pick out the sequence one by one and append to a list?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49153945
score: 0

http://stackoverflow.com/a/49139555
has body: def function(given): for (key,value) in my_dict: if(key==given): print((key,value))
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49139542

bind
tags question: http://stackoverflow.com/q/49216412
type: Tag
tag name: bind

http://stackoverflow.com/q/49139877
downvote count: 0
has title: import the development version of a module over the version that is installed in site-packages
answer count: 1
tagged with: pip
tagged with: python-importlib
has body: I'm developing a python module that is currently closed-source and cannot go on pip (not my choice) for this example I'll refer to it as private_module. This module relies on another module that I'm also developing that is available on pip I'll refer to it as public_module. Here is the problem private_module and the development version of public_module are in a directory on a windows server that I shared with co-workers. The computers that need to access the code have variable file permissions for their variable flavors of python meaning, it is very difficult to pip install ANYTHING but at the same time there may be lingering versions of both private_module and public_module in their site-packages directory. Also assume that all users have no programming experience and even if they did the computers would not be able to install packages with pip without admin privileges. The directory structure can be represented like so: C:\Program Files\Anaconda3\lib\site-packages\[outdated public and private modules] F:\PythonModules\exp\[new public and private modules] I've tried the following and it works perfectly if the modules have not been installed into pip but the modules that are installed in pip appear to be loaded in favor over the other which makes sense. import os staging = [r"F:\PythonModules\exp"] for path in staging: if os.path.isdir(path): sys.path.append(path) Is there a way that I can load the new public and private modules over their counterparts that may be in site-packages?
tagged with: import
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49139946
has comment: http://stackoverflow.com/comment/85285168
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49139946
has comment: http://stackoverflow.com/comment/85285193
has comment: http://stackoverflow.com/comment/85285120

http://stackoverflow.com/q/49168267
tagged with: matlab
type: Question
tagged with: theano
score: 1
has title: Implemented LSTM inference code shows different test loss compared to using lasagne.
has body: I have difficulty implementing LSTM inference code using matlab. I extraced weight from trained model using theano and lasagne. And then, i coded LSTM inference(test) code using extraced weights and biases. The loss of implemented inference code shows about 5, but the test loss of theano and lasagne shows about 1.5. I think implemented inference matlab code is correct and the code is like this. for i=1:100 input1 = input(i,:); input_gate=activation_sigmoid(mtimes(input1,W_in_to_ingate)+mtimes(hidden,W_hid_to_ingate)+reshape(b_ingate,1,512)); forget=activation_sigmoid(mtimes(input1,W_in_to_forgetgate)+mtimes(hidden,W_hid_to_forgetgate)+reshape(b_forgetgate,1,512)); output=activation_sigmoid(mtimes(input1,W_in_to_outgate)+mtimes(hidden,W_hid_to_outgate)+reshape(b_outgate,1,512)); cell=activation_tanh(mtimes(input1,W_in_to_cell)+mtimes(hidden,W_hid_to_cell)+reshape(b_cell,1,512)); ct=input_gate.*cell+forget.*ct; hidden=activation_tanh(ct).*output; result=softmax(reshape(mtimes(hidden,W)+reshape(b,1,83),83,1)); new_loss=-(log(result(answer(1,i)+1))); loss = loss+new_loss; end loss=loss/100; I have no idea which part is incorrect compared to lasagne LSTM source code. The code using theano and lasagne is described below. l_in = lasagne.layers.InputLayer(shape=(None, None, vocab_size)) l_forward_2 = lab.LSTMLayer( l_in, num_units=N_HIDDEN, grad_clipping=GRAD_CLIP, peepholes=False, nonlinearity=activation, method=method) ### batch_size*SEQ_LENGTH*N_HIDDEN l_shp = lasagne.layers.ReshapeLayer(l_forward_2, (-1, N_HIDDEN)) ## (batch_size*SEQ_LENGTH, N_HIDDEN) l_out = lasagne.layers.DenseLayer(l_shp, num_units=vocab_size, W = lasagne.init.Normal(), nonlinearity=lasagne.nonlinearities.softmax) batchsize, seqlen, _ = l_in.input_var.shape l_shp1 = lasagne.layers.ReshapeLayer(l_out, (batchsize, seqlen, vocab_size)) l_out1 = lasagne.layers.SliceLayer(l_shp1, -1, 1) test_output = lasagne.layers.get_output(l_out, deterministic=True) test_loss = T.nnet.categorical_crossentropy(test_outp…
tagged with: python
tagged with: lasagne
tagged with: lstm
answer count: 0
type: UnansweredQuestion
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/85490996
type: Comment
type: QuestionComment
has text: @ArchitSaxena can do!
comment on: http://stackoverflow.com/q/49241535
score: 0

http://stackoverflow.com/comment/85278752
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49136697
type: QuestionComment
has text: Possible duplicate of [How to sort a list of lists by a specific index of the inner list?](https://stackoverflow.com/questions/4174941/how-to-sort-a-list-of-lists-by-a-specific-index-of-the-inner-list)

http://stackoverflow.com/comment/85696368
comment on: http://stackoverflow.com/a/49327935
type: AnswerComment
has text: I was hoping for a simpler solution, but short of something simpler, this is clean and effective. Thanks. I'm leaving the answer unaccepted for a while in case someone can find a better one.
score: 0
type: Comment

http://stackoverflow.com/comment/85416699
type: AnswerComment
comment on: http://stackoverflow.com/a/49187498
has text: Interesting question. Try applying inverse transform on the coefficients too. Logically it should make sense
score: 0
type: Comment

http://stackoverflow.com/a/49214712
upvote count: 3
downvote count: 0
score: 3
answers question: http://stackoverflow.com/q/49214585
has body: In [52]: myDF['pet'].str.extract(r'/(?P&lt;bunny&gt;(?!jack).*rabbits?.*)',expand=True) Out[52]: bunny 0 NaN 1 rabbit 2 small fluffy rabbit 3 lop-eared rabbit 4 many rabbits 5 NaN RegEx explained ...
type: Answer
has comment: http://stackoverflow.com/comment/85433990

lxml
tags question: http://stackoverflow.com/q/49154990
tags question: http://stackoverflow.com/q/49143689
tags question: http://stackoverflow.com/q/49245454
tags question: http://stackoverflow.com/q/49255477
tags question: http://stackoverflow.com/q/49226665
tags question: http://stackoverflow.com/q/49122530
type: Tag
tags question: http://stackoverflow.com/q/49228312
tag name: lxml
tags question: http://stackoverflow.com/q/49122406
tags question: http://stackoverflow.com/q/49253503
tags question: http://stackoverflow.com/q/49138415
tags question: http://stackoverflow.com/q/49260514

aspect-ratio
tag name: aspect-ratio
type: Tag
tags question: http://stackoverflow.com/q/49182669

http://stackoverflow.com/comment/85319112
type: Comment
comment on: http://stackoverflow.com/a/49156878
score: 0
type: AnswerComment
has text: That didnt work. I have a worksheet names ws. And I want to make the font in a specific cell bigger. What would the actual line of code for that look like. For example would it be something like ws['A2'].cell.font.size = "5"?

http://stackoverflow.com/comment/85649695
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49243291
has text: I've run into this on several upgrades, and this is exactly what I did - uninstall and reinstall DRF and it was golden. DRF isn't forced to an upgrade, since Wagtail 2.0 still also runs on Django 1.13.

http://stackoverflow.com/q/49146540
score: 1
tagged with: python
has body: so thanks to some great help I am able to manipulate a CSV file. However, a tutorial I was linked to seemed a bit complicated because they're posting several bits of code to get rows and columns for their data, without showing their full code. So, this is what I have so far: import pandas as pd df = pd.read_csv("TB_burden_countries_2018-03-06.csv") df = df[df["country"] == "Zimbabwe"] print(df) What should I be writing if I want a specific column (example would be "e_pop_num"?) The website I used did: df2.loc["Alaska":"Arkansas","2005":"2007"] I changed the code to: df.loc["Zimbwabe":"Zimbwabe","e_pop_num":"e_pop_num"] And it doesn't seem to work.
has comment: http://stackoverflow.com/comment/85298600
answer count: 2
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85298328
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49146680
has title: CSV file - Have Pandas and Python module
has answer: http://stackoverflow.com/a/49146582
favorite count: 0
type: Question
tagged with: pandas

http://stackoverflow.com/comment/112757274
type: Comment
score: 0
type: AnswerComment
has text: this gives me a white png image (ImageMagick 7.0.10-27)
comment on: http://stackoverflow.com/a/49179389

http://stackoverflow.com/q/49186263
favorite count: 0
tagged with: pycharm
has title: Pycharm Language Injection of f-strings
type: Question
score: 5
upvote count: 5
answer count: 0
downvote count: 0
tagged with: python
type: UnansweredQuestion
has body: I'm trying to get PyCharm to recognise an f-string as an SQL query via the Language Injection feature. PyCharm doesn't seem to evaluate the f-string and then run the Language Injection test. Is there anyway to set up PyCharm to evaluate and determine language? I have noticed that if the f-string does not contain any variables then the language injection does work. For example: f""" select * from foo where id &gt; 10""" detects SQL f""" select * from foo where id &gt; {id_threshold}""" does not detect SQL This also applies for language injection of other languages

odoo
tags question: http://stackoverflow.com/q/49180408
tags question: http://stackoverflow.com/q/49162794
type: Tag
tags question: http://stackoverflow.com/q/49257981
tags question: http://stackoverflow.com/q/49136087
tags question: http://stackoverflow.com/q/49234798
tags question: http://stackoverflow.com/q/49233653
tags question: http://stackoverflow.com/q/49194348
tags question: http://stackoverflow.com/q/49217965
tags question: http://stackoverflow.com/q/49187779
tags question: http://stackoverflow.com/q/49154891
tags question: http://stackoverflow.com/q/49150330
tags question: http://stackoverflow.com/q/49247321
tags question: http://stackoverflow.com/q/49170913
tags question: http://stackoverflow.com/q/49128065
tag name: odoo
tags question: http://stackoverflow.com/q/49171191
tags question: http://stackoverflow.com/q/49225461

http://stackoverflow.com/comment/85576721
type: Comment
comment on: http://stackoverflow.com/q/49276547
score: 0
has text: You might find this is pretty similar to your requirement (two lists to work with - when usually there is just one list): https://stackoverflow.com/questions/29102155/r-string-fuzzy-matching-using-jarowinkler
type: QuestionComment

http://stackoverflow.com/comment/85282024
type: Comment
has text: sets in Python are implemented as hash tables.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49138355

http://stackoverflow.com/q/49157077
has answer: http://stackoverflow.com/a/49170179
has comment: http://stackoverflow.com/comment/85324674
upvote count: 13
score: 13
tagged with: python
has comment: http://stackoverflow.com/comment/85341164
has body: I have .zip archive with filename.xlsx inside it and I want to parse Excel sheet line by line. How to proper pass filename into pandas.read_excel in this case? I tried: import zipfile import pandas myzip=zipfile.ZipFile(filename.zip) for fname in myzip.namelist(): with myzip.open(fname) as from_archive: with pandas.read_excel(from_archive) as fin: for line in fin: .... but it doesn't seem to work, and the result was: AttributeError: __exit__
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/69063850
possible better answer: http://stackoverflow.com/a/49157418
answer count: 3
downvote count: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49170179
has comment: http://stackoverflow.com/comment/85319933
has comment: http://stackoverflow.com/comment/85324753
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49157418
tagged with: http://stackoverflow.com/tag/zip
has comment: http://stackoverflow.com/comment/85319290
has title: Pandas. How to read Excel file from ZIP archive

http://stackoverflow.com/comment/85281505
has text: You will have to use multi-threading. There are [dozens of examples on SO](https://www.google.com/search?&q=pyqt+thread+site%3Astackoverflow.com) that can be easily adapted.
comment on: http://stackoverflow.com/q/49131747
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49193775
linked to: http://stackoverflow.com/q/30820997
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85392230
has answer: http://stackoverflow.com/a/49193918
linked to: http://stackoverflow.com/q/464864
type: UnansweredQuestion
has title: Extracting combinations from a list python
tagged with: python
has comment: http://stackoverflow.com/comment/85392272
has comment: http://stackoverflow.com/comment/85392133
has body: I have this list: List = [1, 2, 3] ...and I want to print out all possible combinations such that the output is like: [1] [1,2] [1, 2, 3] [2] [2, 3] [3] So far my code is this: E=[] i=0 for seq in L[i:]: E.append(seq) i += 1 print(E) Which gives my first 3 outputs. Is there a way for me to loop it so that the index goes up by 1 so I can get my desired output? Edit; so I basically want to write a code which summarizes this: List = [1, 2, 3] E = [] F = [] G = [] for seq in List[0:]: E.append(seq) print(E) for seq in List[1:]: F.append(seq) print(F) for seq in List[2:]: G.append(seq) print(G) I pretty much want to know if I can loop the index so that I don't have to create multiple for loops and maybe apply it to a longer list.
score: 0
answer count: 1
duplicate of: http://stackoverflow.com/q/464864
has comment: http://stackoverflow.com/comment/85392617
has comment: http://stackoverflow.com/comment/85392270

http://stackoverflow.com/q/49125167
answer count: 2
has answer: http://stackoverflow.com/a/49127950
downvote count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/85257906
favorite count: 0
has title: Find the elements dynamically in header and click on them to verify in python selenium
type: Question
possible better answer: http://stackoverflow.com/a/49127950
tagged with: python-3.x
tagged with: automation
has body: This is my code from selenium import webdriver from selenium.webdriver.common.by import By class Runfftest(): def test(self): """ Inistitate the ff browser launch the browser :return: """ baseUrl = "https://letskodeit.teachable.com/p/practice" driver = webdriver.Firefox(executable_path="/usr/local/bin/geckodriver") driver.maximize_window() driver.get(baseUrl) driver.implicitly_wait(10) header_by_xpath = driver.find_element_by_xpath("//*[@id='navbar']") links_in_header = header_by_xpath.find_elements(By.TAG_NAME,"a") size_of_links = len(links_in_header) print(size_of_links) for linkinheader in links_in_header: linkinheader.click() ff = Runfftest() ff.test() I am able to find a element and also click on it but when I do, it throws an error.
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49127548
accepted answer: http://stackoverflow.com/a/49127548
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85255764
upvote count: 0

http://stackoverflow.com/a/49216300
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49216095
has body: Regarding your concern about group being appended and popped. Remember that the statement if sum_checker(ints, total, group, index + 1): Starts the search again (just this time with the next index). Say with your example. sum_checker( ints=[0, 2, 4, 8], total=10, group=[], index=0 ) The first time we hit group, we append 0 to group, so we're then calling sum_checker with the arguments. sum_checker( ints=[0, 2, 4, 8], total=10, group=[0], index=1 ) Then, since group already has one element, we append 2 to group. So we then have: sum_checker( ints=[0, 2, 4, 8], total=10, group=[0, 2], index=2 ) Which means, we start filling up group before we get to .pop(). If the sum() of group becomes too big, THEN we do the first .pop(), and start checking again without the last element that was added.
type: Answer
downvote count: 0

http://stackoverflow.com/comment/85554280
has text: It might be related to this error https://stackoverflow.com/questions/46422488/get-rid-of-pyximport. Essentially Spyder decided to autoimport pyimport which always tries to recompile Cython modules and makes it a complete disaster for using Cython. I'm not sure if they've fixed it yet.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49274956
type: Comment

http://stackoverflow.com/comment/85372802
type: QuestionComment
comment on: http://stackoverflow.com/q/49183487
score: 0
has text: I'm voting to close this question as off-topic because we don't do malicious code
type: Comment

http://stackoverflow.com/a/49238780
accepted answer of: http://stackoverflow.com/q/49238607
has body: What you're encountering is variable scoping. If you import all of test1, you have access to the variables in test 1 because they are within your current operating scope, so directly accessing it, and changing it, allows you to print 2. In your second snippet, you are defining a local variable a=2, which has no bearing on test1.a and therefore when you print, it displays test1.a value of 1. In other words, when you reference test1.a you are accessing one variable, but when you define a local a=2, this is a different variable altogether than printa() is referencing. Variables in python are created and destroyed within their scope. As such, you can create multiple variables in the same python script with the same name without undesired functionality, provided they are encapsulated within their scope. try printing both versions to see the difference. import test1 a=2 print a print test1.a
has comment: http://stackoverflow.com/comment/85481119
type: Answer
answers question: http://stackoverflow.com/q/49238607
upvote count: 2
type: AcceptedAnswer
downvote count: 0
score: 2

http://stackoverflow.com/q/49258566
type: AnsweredQuestion
has body: Using developers.google.com we created api user and downloaded credentials as json file. Now On my macbook gspread authentication is working fine while using credentials.json. when moved same config to linux server on aws its giving 403 insufficient permission error. Pip and python version are same. exception gspread.v4.exceptions.APIError: { "error": { "errors": [ { "domain": "global", "reason": "insufficientPermissions", "message": "Insufficient Permission" } ], "code": 403, "message": "Insufficient Permission" } } basic code import gspread from oauth2client.service_account import ServiceAccountCredentials scope = ['https://spreadsheets.google.com/feeds'] creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope) client = gspread.authorize(creds) sheet = client.open('MySheetName').sheet1
answer count: 3
possible better answer: http://stackoverflow.com/a/49260003
has title: gspread authentication throwing insufficient permission
has comment: http://stackoverflow.com/comment/85540223
favorite count: 0
type: Question
upvote count: 15
tagged with: google-drive-api
tagged with: google-sheets-api
has answer: http://stackoverflow.com/a/49295205
downvote count: 0
has answer: http://stackoverflow.com/a/49260003
tagged with: python
has answer: http://stackoverflow.com/a/50189800
score: 15
tagged with: gspread
has comment: http://stackoverflow.com/comment/85540651
accepted answer: http://stackoverflow.com/a/49295205

http://stackoverflow.com/comment/123000784
score: 0
comment on: http://stackoverflow.com/a/69036247
type: Comment
has text: Good comment, but by the fact OP put `runGui` leads me to think it is a script that initially starts in the terminal, like a kivy application
type: AnswerComment

http://stackoverflow.com/q/49220479
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85444570
possible better answer: http://stackoverflow.com/a/49220541
downvote count: 0
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49220541
accepted answer: http://stackoverflow.com/a/49220742
has answer: http://stackoverflow.com/a/49220640
answer count: 4
has answer: http://stackoverflow.com/a/49220551
has answer: http://stackoverflow.com/a/49220742
type: AnsweredQuestion
has title: How to group by according to the values of a list present in a column in dataframe python
score: 3
tagged with: pandas-groupby
tagged with: pandas
upvote count: 3
has body: I have a dataframe of movies from pandas like this id, name, genre, release_year 1 A [a,b,c] 2017 2 B [b,c] 2017 3 C [a,c] 2010 4 D [d,c] 2010 .... I want to group by the movies according to the values present in the genre lists. My expected output is: year, genre, number_of_movies 2017 a 1 2017 b 2 2017 c 2 2010 a 1 2010 c 2 ... Can somebody please help me to achieve this?

http://stackoverflow.com/comment/85506867
type: QuestionComment
has text: Assuming you use `python` to run the script, then you can check via `python -m pip list` if this is the python you installed the package to.
score: 0
comment on: http://stackoverflow.com/q/49251624
type: Comment

http://stackoverflow.com/comment/85382418
type: AnswerComment
has text: This program is made for users trying to understand conversion between base numbers. So as long as I show the conversion steps and also correcting user-made errors, it should be fine.
type: Comment
comment on: http://stackoverflow.com/a/49188253
score: 0

http://stackoverflow.com/comment/85493625
has text: I'm running into a similar problem any help on this would be great.
comment on: http://stackoverflow.com/q/49207138
type: QuestionComment
type: Comment
score: 0

hadoop
tags question: http://stackoverflow.com/q/49194737
tag name: hadoop
type: Tag

http://stackoverflow.com/comment/85419569
type: Comment
comment on: http://stackoverflow.com/q/49207097
score: 0
has text: btw. your indendation for your code is off - probably due to splitting it with your "And this is the ..." - the comment `""" ... """`should be indentent - same fro your written code - and you lack the "call" to your function to make this a real [mvce](https://stackoverflow.com/help/mcve). Please add the error message and stacktrace to your code and fix the code so we can copy&paste it into our IDEs, execute it and get the same error as you do - as starting point for fixing it. Thanks.
type: QuestionComment

oracle-database
tags question: http://stackoverflow.com/q/49168550
tags question: http://stackoverflow.com/q/49229664
tag name: oracle-database
type: Tag
tags question: http://stackoverflow.com/q/49159643
tags question: http://stackoverflow.com/q/49171782

http://stackoverflow.com/comment/85564514
comment on: http://stackoverflow.com/a/49279570
type: Comment
score: 0
has text: Hahaha wow but this works perfectly! Thank you so much. Your previous answer however worked for the example I posted in my question.
type: AnswerComment

http://stackoverflow.com/a/49219176
type: Answer
has comment: http://stackoverflow.com/comment/85442153
answers question: http://stackoverflow.com/q/49219050
upvote count: 3
downvote count: 0
has body: In the first configuration, your Flask app was located directly in the package myapp; after you moved it, it is in the module myapp.app. Gunicorn expects the app to be specified as module_name:variable_name, somewhat like from module_name import variable_name. Option one: specify the correct module path: /usr/local/bin/gunicorn -b :8000 myapp.app:app Option two: add the app back to myapp. In myapp/__init__.py, add from .app import app Note that if the variable and the module share the name, the module will be overshadowed (not a good thing, although not a critical either).
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49219050
score: 3

http://stackoverflow.com/q/49228842
answer count: 3
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49228964
has comment: http://stackoverflow.com/comment/85461359
favorite count: 0
type: Question
has title: Checking for duplicates in list of list and sorting them
score: 3
has body: I have a table containing: table = [[5, 7],[4, 3],[3, 3],[2, 3],[1, 3]] and the first values represented in each list, (5,4,3,2,1) can be said to be an ID of a person. the second values represented (7,3,3,3,3) would be a score. What I'm trying to do is to detect duplicates values in the second column which is in this case is the 3s in the list. Because the 4 lists has 3 as the second value, i now want to sort them based on the first value. In the table, notice that [1,3] has one as the first value hence, it should replace [4,3] position in the table. [2,3] should replace [3,3] in return. Expected output: [[5,7],[1,3],[2,3],[3,3],[4,3]] I attempted: def checkDuplicate(arr): i = 0 while (i&lt;len(arr)-1): if arr[i][1] == arr[i+1][1] and arr[i][0] &gt; arr[i+1][0]: arr[i],arr[i+1] = arr[i+1],arr[i] i+=1 return arr checkDuplicate(table) The code doesn't fulfil the output i wanted and i would appreciate some help on this matter.
has answer: http://stackoverflow.com/a/49228902
tagged with: python
has comment: http://stackoverflow.com/comment/85461099
has comment: http://stackoverflow.com/comment/85461133
has answer: http://stackoverflow.com/a/49229821
upvote count: 3

http://stackoverflow.com/comment/85280115
comment on: http://stackoverflow.com/q/49122185
type: Comment
type: QuestionComment
score: 0
has text: Then how are you running your program?

http://stackoverflow.com/comment/86231092
comment on: http://stackoverflow.com/q/49234682
score: 0
type: Comment
has text: This project https://github.com/wmayner/pyemd
type: QuestionComment

http://stackoverflow.com/q/49218313
has answer: http://stackoverflow.com/a/49267612
tagged with: urllib
answer count: 1
accepted answer: http://stackoverflow.com/a/49267612
has body: I want to make a python script, which is parsing the pronounciation from a chinese character from the site hanyu.baidu.com. I found a code to make a search at the main site of baidu.com #!/usr/bin/env python2 # -*- coding: utf-8 -*- import urllib2,urllib,sys,io url = "http://www.baidu.com/s" search = [('w','吃')] getString = url + "?" + urllib.urlencode(search) print getString req = urllib2.Request(getString) fd = urllib2.urlopen(req) which is returning the html code of the site http://www.baidu.com/s?w=%E5%90%83 This is what I expected. But when I change the url to url = "https://hanyu.baidu.com/s" and the argument to search = [('wd','吃')] I would like to get the result of the site https://hanyu.baidu.com/s?wd=%E5%90%83 but instead python returns an page, which says that my I am referring to a page which do not exist (in chinese: 很抱歉，您要访问的页面不存在！) Why can I open the url in my browser, but not with python?
type: Question
type: AnsweredQuestion
score: 0
has title: python2 urllib request at hanyu.baidu.com
tagged with: python

http://stackoverflow.com/comment/85321459
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49151057
score: 0
has text: I can guess that error occurs in the last line, but usually we ask for the traceback from errors to be sure. Another wild guess is that `f` is not open when you try to access `grp`, and that the `invalid object id` refers to `grp`. For more than guesses we need a [mcve].

http://stackoverflow.com/q/49159720
tagged with: python
duplicate of: http://stackoverflow.com/q/12680754
score: 0
has comment: http://stackoverflow.com/comment/85324672
has answer: http://stackoverflow.com/a/49160021
tagged with: pandas
type: UnansweredQuestion
answer count: 1
has body: I have a dataframe like so: ID | Value1 | Value2 | Tags 1 | 1 | 6 | Alex/Jason 2 | 6 | 3 | Miranda 3 | 5 | 9 | Jose/Rebecca 4 | 2 | 7 | Max 5 | 0 | 1 | Lilly I want to split the Tag column by a delimiter (in this case "/") and then duplicate the rows such that there is only one Tag per row: ID | Value1 | Value2 | Tags 1 | 1 | 6 | Alex 1 | 1 | 6 | Jason 2 | 6 | 3 | Miranda 3 | 5 | 9 | Jose 3 | 5 | 9 | Rebecca 4 | 2 | 7 | Max 5 | 0 | 1 | Lilly
type: Question
has title: Transforming a dataset
has comment: http://stackoverflow.com/comment/85324709
linked to: http://stackoverflow.com/q/12680754

http://stackoverflow.com/comment/85424900
has text: @GianMauroMusso so what would `[4, 4, 4, 4, 5, 5, 5, 5]` be? Trying to work out if it should be 1, 2, 3, 4 or 3, 4, 3, 4... or something else...
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49210113

http://stackoverflow.com/comment/85439001
comment on: http://stackoverflow.com/q/49216840
score: 0
type: Comment
type: QuestionComment
has text: @eugenhu I did :"I'm trying to get a login screen that has a checkbox that toggles the visibility of the password"

http://stackoverflow.com/q/49222421
accepted answer: http://stackoverflow.com/a/49222458
tagged with: beautifulsoup
type: AnsweredQuestion
has body: I am filtering a web page content which includes a table, which of I parse the row with bold text and then get the a tags there. response = urllib2.urlopen("https://wiki.guildwars.com/wiki/Weekly_activities") data = response.read() soup = BeautifulSoup(data, 'html.parser') dailiesunsorted = soup.findAll('tr', style="font-weight: bold;") pvebonus = dailiesunsorted[0].findAll('a')[0] pvpbonus = dailiesunsorted[0].findAll('a')[1] nickitem = dailiesunsorted[0].findAll('a')[2] nicklocation = dailiesunsorted[0].findAll('a')[3] nickmap = dailiesunsorted[0].findAll('a')[4] #not working when adding this line, but the line does what I want it to nickcount = nickitem = dailiesunsorted[0].findAll('a')[2].next_sibling pvebonus = "["+pvebonus.text+"](https://wiki.guildwars.com"+quote(pvebonus['href'])+")" pvpbonus = "["+pvpbonus.text+"](https://wiki.guildwars.com"+quote(pvpbonus['href'])+")" nickitem = "["+nickitem.text+"](https://wiki.guildwars.com"+quote(nickitem['href'])+")" nicklocation = "["+nicklocation.text+"](https://wiki.guildwars.com"+quote(nicklocation['href'])+")" nickmap = "["+nickmap.text+"](https://wiki.guildwars.com"+quote(nickmap['href'])+")" return pvebonus, pvpbonus, nickitem, nicklocation, nickmap, nickcount.strip() The code worked perfectly and did what it was meant to do, until I added the commented line. Now I get this error: File "/home/jens/gelbbot/gwhttp.py", line 42, in weeklies nickitem = "["+nickitem.text+"](https://wiki.guildwars.com"+quote(nickitem['href'])+")" File "/usr/lib/python3.6/site-packages/bs4/element.py", line 737, in __getattr__ self.__class__.__name__, attr)) AttributeError: 'NavigableString' object has no attribute 'text' It seems I can't use the findAll('a')[2] twice, but how to fix that? .copy() doesnt work
score: 0
has answer: http://stackoverflow.com/a/49222458
tagged with: python
tagged with: python-3.6
has title: BeautifulSoup call Soup twice (.text)
type: Question
tagged with: urllib2
answer count: 1

http://stackoverflow.com/comment/85285979
type: QuestionComment
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 his own. A good way to show this effort is to include a [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve). Check the [intro tour](https://stackoverflow.com/tour) you were *supposed* to finish before posting, especially [How to Ask](http://stackoverflow.com/help/how-to-ask).
comment on: http://stackoverflow.com/q/49140169
score: 1
type: Comment

http://stackoverflow.com/comment/85391762
type: Comment
type: QuestionComment
has text: Once I register with url like 'www.example.com', and complete django-disqus setup providing API_KEY and Shortname in settings.py, I get the following error : `We were unable to load Disqus. If you are a moderator please see our troubleshooting guide`
comment on: http://stackoverflow.com/q/49192077
score: 0

http://stackoverflow.com/q/49230602
has body: I have a dataframe with DenseVectors as row: df = spark.createDataFrame([(Vectors.dense([1,2,3]),),(Vectors.dense([3,4,5]),),(Vectors.dense([6,2,5]),)], ["a"]) and I want to find the maximum of each row with UDF. This is what I did: findmax = F.udf(lambda x: max(x),DoubleType()) df_out = df_out.select('*',findmax(df_out['sensor_data']).alias('MAX')) After I ran the codes, this is the message i got Traceback (most recent call last): File "", line 1, in df.select('*',findmax(df['a'])).show() File "C:\ProgramData\Anaconda3\envs\python2\lib\site-packages\pyspark\sql\dataframe.py", line 336, in show print(self._jdf.showString(n, 20)) File "C:\ProgramData\Anaconda3\envs\python2\lib\site-packages\py4j\java_gateway.py", line 1133, in call answer, self.gateway_client, self.target_id, self.name) File "C:\ProgramData\Anaconda3\envs\python2\lib\site-packages\pyspark\sql\utils.py", line 63, in deco return f(*a, **kw) File "C:\ProgramData\Anaconda3\envs\python2\lib\site-packages\py4j\protocol.py", line 319, in get_return_value format(target_id, ".", name), value) Py4JJavaError: An error occurred while calling o785.showString. : org.apache.spark.SparkException: Job aborted due to stage failure: Task 2 in stage 67.0 failed 1 times, most recent failure: Lost task 2.0 in stage 67.0 (TID 890, localhost, executor driver): net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for numpy.dtype) at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23) at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707) at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175) at net.razorvine.pickle.Unpickler.load(Unpickler.java:99) at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112) at org.apache.spark.sql.execution.python.BatchEvalPythonExec$$anonfun$doExecute$1$$anonfun$apply$6.apply(BatchEvalPythonExec.scala:156) at org.apache.spark.sql.execution.python.BatchEvalPythonExec$$anonfun$doExecute$1$$anonfun…
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
tagged with: user-defined-functions
tagged with: pyspark
tagged with: python
accepted answer: http://stackoverflow.com/a/49231316
has title: Getting the maximum of a row from a pyspark dataframe with DenseVector rows
has answer: http://stackoverflow.com/a/49231316
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/86447555
score: 0
type: Comment
type: QuestionComment
has text: `cdvirtualenv` (at least on windows) goes to the `sys.exec_prefix` directory, which is the main python installation if you haven't activated a virtualenv. If you have activated a virtualenv it will go to the location of that virtualenv. Use the `virtualenvwrapper` command to get a list, and summary, of available commands.
comment on: http://stackoverflow.com/q/49249451

http://stackoverflow.com/q/49249996
linked to: http://stackoverflow.com/q/11347862
score: 0
has body: Background info: I know how to use a keyPressEvent, it works fine when the window is in focus. My keyPressEvent function is as follows: def keyPressEvent(self, e): if e.key() == Qt.Key_F7: self.prevSong() if e.key() == Qt.Key_F9: self.nextSong() The keys are connected to the functions and they do what they are supposed to do What I am trying to achieve: Make the same key presses call the same functions when the key is pressed when the window is out of focus or in the background. How can I make this happen on a Mac?
linked to: http://stackoverflow.com/q/35564502
answer count: 0
tagged with: pyqt
linked to: http://stackoverflow.com/q/16615087
type: Question
has title: PyQt5 - How can I make keyPressEvent function work the same when the window is out of focus?
has comment: http://stackoverflow.com/comment/85536965
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85539907
tagged with: python
has comment: http://stackoverflow.com/comment/85540080
has comment: http://stackoverflow.com/comment/85503676

http://stackoverflow.com/a/49272940
type: Answer
has body: The function strips the url from the double slash to the single slash: the rest is 'clean up' def stripURL( url, TwoSlashes, OneSlash ): try: start = url.index(TwoSlashes) + len(TwoSlashes) end = url.index( OneSlash, start ) return url[start:end] except ValueError: return "" url= raw_input("URL : ") if "www." in url:url=url.replace("www.","") Strip = stripURL( url, "//", "/" ) # Strips anything after the last period found Stripped = Strip[:Strip.rfind(".")] # get rid of the any periods used in the name Stripped = Stripped.replace("."," ") print Stripped
has comment: http://stackoverflow.com/comment/85549092
has comment: http://stackoverflow.com/comment/85550066
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49271668
has comment: http://stackoverflow.com/comment/85549147

http://stackoverflow.com/comment/85535210
has text: @0x5453 How would a "debugger" tell you why a built-in function like `input()` is reporting an error?
comment on: http://stackoverflow.com/q/49265644
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85309042
has text: Use `in` → ex: `".jpg" in string`?
score: 1
comment on: http://stackoverflow.com/q/49152437
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49200363
has comment: http://stackoverflow.com/comment/85406015
has answer: http://stackoverflow.com/a/68070435
has comment: http://stackoverflow.com/comment/85406001
tagged with: python
score: -1
has answer: http://stackoverflow.com/a/49200502
has comment: http://stackoverflow.com/comment/85405843
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/85406321
possible better answer: http://stackoverflow.com/a/68070435
accepted answer: http://stackoverflow.com/a/49200502
has comment: http://stackoverflow.com/comment/85406867
has comment: http://stackoverflow.com/comment/85405922
downvote count: 1
has comment: http://stackoverflow.com/comment/85406212
favorite count: 0
has comment: http://stackoverflow.com/comment/85406123
type: Question
tagged with: cosine-similarity
tagged with: tf-idf
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85406151
has title: Cosine similarity for special vectors (only one component)
has comment: http://stackoverflow.com/comment/85406234
has comment: http://stackoverflow.com/comment/85405942
has body: I'm trying to implement cosine similarity for two vectors, but I ran into a special case where the two vectors only have one component, like this: v1 = [3] v2 = [4] Here is my implementation for the cosine similarity: def dotProduct(v1, v2): if len(v1) != len(v2): return 0 return sum([x * y for x, y in zip(v1, v2)]) def cosineSim(v1, v2): dp = dotProduct(v1, v2) mag1 = math.sqrt(dotProduct(v1, v1)) mag2 = math.sqrt(dotProduct(v2, v2)) return dp / (mag1 * mag2) The cosine similarity for any two vectors that only have one component is always 1 then. Can someone guide me through how to handle this special case? Thank you.
upvote count: 0

http://stackoverflow.com/q/49266391
tagged with: web-scraping
tagged with: scrapy
has answer: http://stackoverflow.com/a/49267851
has body: I'm trying to scrape movie titles from Tmdb but each title has a different selector. Is there a way for me to get them all in one go? For example: The css selector for Birdman is .7, Star Wars is .9, and other movies have different ones. You may ask why not just got the titles like this but it is because I need to go on each page in order to get the genre as well. class PosterSpider(scrapy.Spider): name = "movieposter - imgsearch" start_urls = ["https://www.themoviedb.org/?language=en"] def parse(self, response): url = response.css('.logo~ li:nth-child(3) &gt; a').xpath('//*~[contains(concat( " ", @class, " " ), concat( " ", "logo", " " ))]//li[(((count(preceding-sibling::*) + 1) = 3) and parent::*)]//&gt;//a') yield scrapy.Request(url.xpath("@href").extract_first(), self.parse_page) def parse_page(self, response): """ Method to press the 'next' button and go through each movie poster """ for href in response.xpath('//*[contains(concat( " ", @class, " " ), concat( " ", "view_more", " " ))]//*[contains(concat( " ", @class, " " ), concat( " ", "result", " " ))]'): yield scrapy.Request(href.xpath('@href').extract_first(), self.parse_covers) next = response.css('.glyphicons-circle-arrow-right').xpath('//*[contains(concat( " ", @class, " " ), concat( " ", "glyphicons-circle-arrow-right", " " ))]') yield scrapy.Request(next.xpath("@href").extract_first(), self.parse_page) def parse_covers(self, response): img = response.css('.zoom a').xpath('//*[contains(concat( " ", @class, " " ), concat( " ", "zoom", " " ))]//a') # what to put for this selector? title = response.css().extract_first() genre = response.css('.genres a').extract_first() yield MoviePoster(title=title, genre = genre, file_urls=[])
favorite count: 0
type: Question
answer count: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85536278
accepted answer: http://stackoverflow.com/a/49267851
has title: How would I select a selector in CSS that changes?
tagged with: python
possible better answer: http://stackoverflow.com/a/49267254
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49267254
has comment: http://stackoverflow.com/comment/85536233
tagged with: css-selectors
downvote count: 0
has comment: http://stackoverflow.com/comment/85536491

http://stackoverflow.com/a/49236918
type: Answer
has body: WAMP is a protocol which sits on top of WebSocket, and you need a library which implements it. Autobahn|Python does so, but you are trying to establish a pure WebSocket connection with a WAMP router. This will naturally fail. For a basic example of how to connect to a WAMP router from Python, see e.g. https://github.com/crossbario/crossbar-examples/tree/master/hello/python Side note: WAMP v2 is what all the implementations listed at http://wamp-proto.org/implementations/ are running. version 1 has pretty much been resigned to the history books.
answers question: http://stackoverflow.com/q/49195721
has comment: http://stackoverflow.com/comment/85480575
score: 0

http://stackoverflow.com/a/49465001
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49171883
answers question: http://stackoverflow.com/q/49171883
type: AcceptedAnswer
has body: It may be possible for pycurl to propagate Python exceptions in callbacks out of perform calls, however this is not currently implemented. Right now each callback should return an appropriate value to indicate the error; in case of opensocket callback, this value is CURL_SOCKET_BAD. (Unfortunately, pycurl does currently not expose this constant either; use -1 instead.) One way to provide rich error information is to store it on the Curl object itself, as follows: import pycurl, random, socket class ConnectionRejected(Exception): pass def opensocket(curl, purpose, curl_address): if random.random() &lt; 0.5: curl.exception = ConnectionRejected('Rejecting connection attempt in opensocket callback') # should be pycurl.SOCKET_BAD in the next release return -1 family, socktype, protocol, address = curl_address s = socket.socket(family, socktype, protocol) s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) return s c = pycurl.Curl() c.setopt(c.URL, 'http://pycurl.io') c.exception = None c.setopt(c.OPENSOCKETFUNCTION, lambda purpose, address: opensocket(c, purpose, address)) try: c.perform() except pycurl.error as e: if e.args[0] == pycurl.E_COULDNT_CONNECT and c.exception: print(c.exception) else: print(e) Additionally pycurl doesn't currently handle -1/CURL_SOCKET_BAD return quite correctly - it complains that -1 is not a valid return value (but functionality is not otherwise affected). https://github.com/pycurl/pycurl/pull/484 will repair this.
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/49180516
has answer: http://stackoverflow.com/a/49180565
has comment: http://stackoverflow.com/comment/85412638
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49180565
has title: Order a recipe queryset by replies number using django-disqus
tagged with: disqus
has body: I have a recipe model: class Recipe(models.Model): title = models.CharField(_("Recipe Title"), max_length=250) slug = models.SlugField(_('slug'), unique=True) author = models.ForeignKey(User, verbose_name=_('user')) ... I need create a view for most commented recipes, i'm using django-disqus for handling recipe's comments, but i don't know how can i order the queryset by the recipe's comment number. class PopRecipeListView(GlobalQueryMixin, ListView): model = Recipe context_object_name = "recipe_list" template_name = 'recipe/recipe_top_list.html' def get_queryset(self): qs = super(PopRecipeListView, self).get_queryset() if qs: qs = qs.extra( select={ 'comments': # get comment numbers } ).filter(shared=True).order_by('-rate')[:20] return qs I found this in documentation: https://disqus.com/api/docs/forums/listThreads/ I can get a json file with the site and forum id and iterate over them for get the properly key, but i think it is not easy. Looking more deep i can get the json file using some like this: var url = "https://disqus.com/api/3.0/forums/listThreads.json?api_key=" + api_key + "&amp;forum=" + forum; //+ "&amp;limit=100";, but i am not sure about it. Ok, i have the next function for get that parameters: def get_comments_by_site(): api_key = settings.DISQUS_API_KEY forum = settings.DISQUS_WEBSITE_SHORTNAME url = 'https://disqus.com/api/3.0/forums/listThreads.json?api_key={0}&amp;forum={1}&amp;limit=100'.format(api_key, forum) raw = requests.get(url) dict = json.loads(raw) values = {} for thread in dict['response']: item = {thread['slug']: thread['posts']} values.update(item) return values def get_comments_number(slug): return values[slug] I made two different functions because i want that View get all value at once, and after, in the query call the secong function for get the values from the obtained dictionary. I created a mixin to integrate the two functions: class DisqusCommentsNumber(object): values = {} def get_comments_by_site(self): api_key = settings.D…
accepted answer: http://stackoverflow.com/a/49218596
type: Question
has answer: http://stackoverflow.com/a/49218596
answer count: 2
tagged with: django
tagged with: python

http://stackoverflow.com/a/49169107
downvote count: 0
answers question: http://stackoverflow.com/q/49168762
score: 1
type: Answer
upvote count: 1
has body: There are several ways to get multiple return values. Example 1: def test_fun(): return 1,2 def test_call(): x, y = test_fun() print x print y you will get correct output: 1 2 When you would like to ignore several return values, you can use * before a variable in python3. Example 2: def test_fun2(): return 1,2,3 def test_call2(): x, *y = test_fun2() print x print y you will get the result: 1 (2, 3)

http://stackoverflow.com/q/49207138
has comment: http://stackoverflow.com/comment/85423768
tagged with: quantile-regression
favorite count: 0
has comment: http://stackoverflow.com/comment/85493625
type: Question
has body: I am trying to forecast my target variable using Quantile Regression in Python. The data I am considering for training and validation is from period 2015 Oct -2017 Dec 31st. Now the model has developed,Im trying to forecast values for 2018 Jan, which throws the following error: ValueError: operands could not be broadcast together with shapes (34,) (33,) mod = smf.quantreg('ASBCU_SUM~Month+Year+WeekofMonth+DayNum+isHoliday+PCOP_CS+PCOP_LS+PCOP_IFS+PCOP_LSS+PCOP_FSS+PCOP_FS+DayOfWeek_6+DayOfWeek_5+DayOfWeek_2+DayOfWeek_7+DayOfWeek_3+DayOfWeek_4',dfTrainingData) res = mod.fit(q=0.8) If I check,the error comes from quantile regression.py file inside statmodels. diff = np.max(np.abs(beta - beta0)) I have gone through similar posts on stack overflow,which recommends to check the data type of target variable being numerical or not. This is the dtype of the variables: ASBCU_SUM: int64 Month: category Year: category WeekofMonth: category isHoliday: int64 DayNum: int32 PCOP_SUM: int64 PCOP_CS: int64 PCOP_LS: int64 PCOP_IFS: int64 PCOP_LSS: int64 PCOP_FS: int64 PCOP_FSS: int64 DayOfWeek_3: float64 DayOfWeek_2: float64 DayOfWeek_5: float64 DayOfWeek_7: float64 DayOfWeek_4: float64 DayOfWeek_6: float64 The datatypes are same while developing the model using 2015-2017 data as well. I really appreciate any help..
type: UnansweredQuestion
score: 5
downvote count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85424386
has answer: http://stackoverflow.com/a/66118264
tagged with: statsmodels
tagged with: pandas
has title: QuantileRegression ValueError: operands could not be broadcast together with shapes
upvote count: 5
answer count: 1

http://stackoverflow.com/comment/85301175
type: QuestionComment
has text: i think datetime.date.today() dont give a good format. Try to build a string with format 'yyyy/MM/dd'
type: Comment
comment on: http://stackoverflow.com/q/49142767
score: 0

http://stackoverflow.com/q/49240711
answer count: 0
has title: tkinter generate widgets dynamically
has comment: http://stackoverflow.com/comment/85518340
type: Question
tagged with: python-3.x
type: UnansweredQuestion
has body: I need some advice on style and how to generate tk widgets dynamically. I'm downloading some weather data from an API as an xml-string. What I'm doing is finding certain strings in it for displaying the weather data in a tk frame: def getSingleDate(self, weatherXML, singleDate): return weatherXML[weatherXML.index("&lt;"+singleDate+"&gt;")+len(singleDate)+2: weatherXML.index("&lt;/"+singleDate+"&gt;")] def lookUpData(self, weatherXML): weatherDict={} weatherData=["localtime", "temp_c", "text", "wind_kph", "wind_dir", "pressure_mb", "precip_mm", "humidity", "cloud", "feelslike_c", "vis_km"] for i in range(len(weatherData)): weatherDict[weatherData[i]] = self.getSingleDate(weatherXML, weatherData[i]) The code works but I wanted to know if there is a more 'pythonic' way to construct the dictionary from my list and the method to generate the actual data from the XML file. If I wanted to display all my weather data using tkinter: Is there any good way to generate tk labels from the weatherData list or even the weatherDict in pairs (one for the name and one for the value) and how could I possibly change them from any other part of the programme? Is there a way constructing tk widgets dynamically and naming them specifically for calling them later on? I guess I want to do something like: self.label_temp_c = tk.Label(text=weatherData[0]) self.label_temp_c.grid(row=0, column=0) self.label_temp_c_value = tkLabel(text=weatherDict['temp_c']) self.label_temp_c_value.grid(row=0, column=1) But not like that but dynamically. Gots some knots in the brain... need help! Thanks!
tagged with: python
has comment: http://stackoverflow.com/comment/85485653
score: 0
tagged with: tkinter

http://stackoverflow.com/q/49178797
tagged with: pypi
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: pipenv
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85630362
tagged with: pip
tagged with: python
has title: How to install python packages from more than pypi repository?
has comment: http://stackoverflow.com/comment/85805549
answer count: 0
score: 1
has body: I'm using pipenv as package management tool and for my project I use packages from pypi and other private local project for that we did a private pypi repo, but when trying to install the packages, I got the following error: File "/usr/local/Cellar/pipenv/8.3.2_1/libexec/lib/python3.6/site-packages/pipenv/utils.py", line 382, in prepare_pip_source_args pip_args.extend(['-i', sources[0]['url']]) TypeError: 'NoneType' object is not subscriptable My Pipfile looks as follow: source url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" source url = "https://my.domain.com/repository/" verify_ssl = true name = "local" [packages] flask = "*" sqlalchemy = "*" gunicorn = "*" ... my_project = {version="*", index="local"} [dev-packages] tox = "*" pytest = "*" "flake8" = "*" [requires] python_version = "3.6" What I am doing wrong? How can I fix the issue!?
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49128065
score: 0
tagged with: odoo
tagged with: odoo-8
has answer: http://stackoverflow.com/a/49128351
answer count: 1
tagged with: image
type: Question
type: UnansweredQuestion
has title: Odoo 8 image on xml form rotated
tagged with: javascript
tagged with: python
has body: I'm using Odoo V8 and added an image widget on the XML form. Now this image is always 90° rotated, however in windows this appears normal. I suppose that the orignal image was taken sideways and windows auto-rotates this and Odoo takes the original orientation. I can't seem to find a way to rotate this image and upload it. I was wondering if there was a possibility to rotate this image in Odoo itself, through a JS-script maybe? Any ideas welcome.

http://stackoverflow.com/a/49244583
answers question: http://stackoverflow.com/q/49239841
score: 0
accepted answer of: http://stackoverflow.com/q/49239841
type: Answer
has comment: http://stackoverflow.com/comment/85509123
type: AcceptedAnswer
has body: You can extract the files individually rather than using extractall. with tarfile.open('musthaves.tar.gz') as tarObj: for member in tarObj.getmembers(): if member.isfile(): member.name = os.path.basename(member.name) tarObj.extract(member, ".") With appropriate credit to this SO question and the tarfile docs. getmembers() will provide a list what is inside the archive (as objects); you could use listnames() but then you'd have to devise you own test as to whether or not each entry is a file or directory. isfile() - if it's not a file, you don't want it. member.name = os.path.basename(member.name) resets the subdirectory depth - the extractor things everything is at the top level.

http://stackoverflow.com/a/49162680
downvote count: 0
type: Answer
score: 1
answers question: http://stackoverflow.com/q/49162302
upvote count: 1
has body: You can use groups to extract what you want from the match: str = 'AAPL1809A170' match = re.search(r"\d{1}([A-Z])\d{1}", str) print(match.group(1)) The group is whatever you put between parenthesis (), e.g., [A-Z], and then you print the group. Since there's only one group specified, ([A-Z]), use print(match.group(1)) to print the matched letter. In the case above, this will return A.

http://stackoverflow.com/comment/85272296
has text: This might be done faster via pandas -- convert to dataframes, perform a sql-style merge based on B-keys, multiply columns, and then `df.groupby(A-key).sum()`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49133777
type: Comment

http://stackoverflow.com/a/49200475
score: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49200384
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49200384
has body: That happens because the time part of the datetime. You can use the __date helper in filters. Use it like this: fm.filter(user__date_joined__date__gte=filters['from_date']) And only the Date part of a DateTime will be used.

http://stackoverflow.com/comment/85339920
type: AnswerComment
has text: Please look at the code I supplied !!! It is initialized each time the function is called.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49143795

http://stackoverflow.com/comment/85467810
comment on: http://stackoverflow.com/q/49232180
has text: https://stackoverflow.com/questions/13590749/reading-unicode-file-data-with-bom-chars-in-python startswith seems to be ok for that
type: Comment
type: QuestionComment
score: 0

linear-discriminant
tags question: http://stackoverflow.com/q/49208444
type: Tag
tag name: linear-discriminant

http://stackoverflow.com/comment/85391419
score: 0
comment on: http://stackoverflow.com/q/49184472
has text: @Ykh, I tried this but the problem persists
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85382161
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49188432
has text: You probably want to use a for loop to go from start to end of the input string. Keep a python dictionary of each sequence of length n=3 that you encounter in the input sequence.

http://stackoverflow.com/comment/85424131
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49197079
score: 0
has text: @Joran Beasley to my understanding, there are two options when dealing with classes used as interfaces. Either you provide setters and getters to users of the interface, so that you can later modify the implementation of the interface. Or you provide access directly to the attributes (foo.val), and if need be implement custom setters getters later. The former might be clearer on what's happening, the latter is more convenient during writing the initial implementation. So I'd say it depends on the scale and target of your project.

http://stackoverflow.com/comment/85485783
score: 0
comment on: http://stackoverflow.com/q/49240364
type: QuestionComment
has text: I want to display every post for each author , can I do it without AuthorDetails !?
type: Comment

http://stackoverflow.com/comment/85288121
score: 0
type: Comment
type: QuestionComment
has text: @tisaconundrum what is `obj`?
comment on: http://stackoverflow.com/q/49140505

http://stackoverflow.com/comment/85498354
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49247279
has text: Cool, I'll give it a shot
type: Comment

draftjs
type: Tag
tags question: http://stackoverflow.com/q/49206815
tag name: draftjs

http://stackoverflow.com/a/49199213
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49197079
has body: A possibility is to use a custom Unpickler, although you would need to keep the old class around (with a different name, hidden if you want) and define the logic to convert an object of the old class to the new one. Here's a basic example: import pickle # define Class and create instance class Foo: def __init__(self): self.val = 1 foo = Foo() # dump foo into file with open("foo.pickle", 'wb') as handle: pickle.dump(foo, handle, pickle.HIGHEST_PROTOCOL) # Old class is kept with a new name FooOld = Foo # overwrite and add @property in the class definition class Foo: def __init__(self): self._val = "new_foo" @property def val(self): return self._val @val.setter def val(self, val): self._val = val foo_new = Foo() print(foo_new.val) # Custom Unpickler class FooOldUnpickler(pickle.Unpickler): def __init__(self, *args, **kwargs): super(FooOldUnpickler, self).__init__(*args, **kwargs) def load(self): obj = super(FooOldUnpickler, self).load() if type(obj) is FooOld: # Object conversion logic newObj = Foo() newObj.val = obj.val obj = newObj return obj def find_class(self, module, name): # Use old class instead of new for loaded objects if module == __name__ and name == 'Foo': return FooOld return super(FooOldUnpickler, self).find_class(module, name) # reload foo with open("foo.pickle", "rb") as handle: # Use custom unpickler foo_old = FooOldUnpickler(handle).load() # try to access attributes print(foo_old.val)
has comment: http://stackoverflow.com/comment/85424360
type: Answer
score: 1
answers question: http://stackoverflow.com/q/49197079
has comment: http://stackoverflow.com/comment/85636912

http://stackoverflow.com/comment/85280818
type: QuestionComment
comment on: http://stackoverflow.com/q/49137845
has text: Does `-arg1 "hi"` and `arg1 "hi"` produce similar results?
score: 1
type: Comment

http://stackoverflow.com/comment/85278264
comment on: http://stackoverflow.com/q/49131451
type: Comment
score: 0
type: QuestionComment
has text: But the algorithm is looking for all nodes anyhow because it is a weighted graph. So it has to pick the weight attribute to use for calculation (weights='weight'). So if it is taking the weight attribute, it could take IMHO any other attribute/condition as well without any extra cost.

http://stackoverflow.com/a/49135478
downvote count: 0
upvote count: 4
has body: You can follow &lt;http://dbpedia.org/ontology/wikiPageRedirects&gt;: &lt;http://dbpedia.org/resource/Sheldon_J._Plankton&gt; dbo:wikiPageRedirects*/dct:subject ?subject . The * will make the property path match zero or more redirects.
has comment: http://stackoverflow.com/comment/85275808
accepted answer of: http://stackoverflow.com/q/49133915
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/49133915
score: 4

http://stackoverflow.com/comment/85435292
type: QuestionComment
comment on: http://stackoverflow.com/q/49215267
score: 0
has text: Use a for-loop, as suggested in other SO posts where this question has already been answered. Or look at numpy datetime documentation.
type: Comment

http://stackoverflow.com/comment/85771449
type: QuestionComment
has text: @JohnColeman: If that were true, the kind of skewing would be random, wouldn't it? But it's not, and this is over many, many trials over multiple years.
comment on: http://stackoverflow.com/q/49243597
score: 0
type: Comment

http://stackoverflow.com/q/49155472
has answer: http://stackoverflow.com/a/49155569
possible better answer: http://stackoverflow.com/a/49155733
has answer: http://stackoverflow.com/a/49155733
tagged with: python-collections
has comment: http://stackoverflow.com/comment/85315552
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
has title: Python append Counter to Counter, like Python dictionary update
score: 5
linked to: http://stackoverflow.com/q/8930915
upvote count: 5
downvote count: 0
has body: I have 2 Counters (Counter from collections), and I want to append one to the other, while the overlapping keys from the first counter would be ignored. Like the dic.update (python dictionaries update) For example: from collections import Counter a = Counter(a=4, b=0, c=1) b = Counter(z=1, b=2, c=3) So something like (ignore overlapping keys from the first counter): # a.update(b) Counter({'a':4, 'z':1, 'b':2, 'c':3}) I guess I could always convert it to some kind of a dictionary and then convert it back to Counter, or use a condition. But I was wondering if there is a better option, because I'm using it on a pretty large data set.
tagged with: counter
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/49155569
type: AnsweredQuestion

http://stackoverflow.com/comment/85291344
comment on: http://stackoverflow.com/q/49142836
type: Comment
score: 0
has text: I have read the docs but how to accommodate the "<=" on the join key criteria is my question.
type: QuestionComment

http://stackoverflow.com/q/49278490
linked to: http://stackoverflow.com/q/1436703
tagged with: python
type: AnsweredQuestion
answer count: 2
downvote count: 0
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49278639
has body: I have a class Board. class Board: # Initialize empty n x n board def __init__(self, n): self.board = [[0]*n for x in range(n)] self.size_n = n # ... I want to be able to print an object of this class with the default print(board_obj) function such that I get this output: [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0] I tried this but it prints the matrix in one line, which I don't want: # Represent the class object as its board def __repr__(self): return repr(self.board) Wrong output: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] I also do not want a custom class method like below: # Custom print def print_board(self): for row in self.board: print row
favorite count: 0
accepted answer: http://stackoverflow.com/a/49278639
type: Question
has answer: http://stackoverflow.com/a/49278658
possible better answer: http://stackoverflow.com/a/49278658
has title: Change default print for class object - Python

http://stackoverflow.com/q/49268725
tagged with: python
tagged with: inheritance
upvote count: 6
tagged with: superclass
has title: Why is my superclass calling my subclass method?
type: AnsweredQuestion
answer count: 3
possible better answer: http://stackoverflow.com/a/74995071
downvote count: 0
linked to: http://stackoverflow.com/q/6620832
has answer: http://stackoverflow.com/a/74995071
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49269359
tagged with: subclass
has body: When I call a method that was overrided from my constructor, I am getting an error and it says that it is missing an argument (due to the subclass requiring a second argument). However, I called the method in the super(), so why doesn't it call the super class version of that method? This is best illustrated with a short example: class A: def __init__(self): self.do() def do(self): print("A") class B(A): def __init__(self): super().__init__() self.do("B") def do(self, arg2): super().do() print(arg2) b = B() Here is the error I get: Traceback (most recent call last): File "D:/Python/Advanced/randomStuff/supersub.py", line 19, in &lt;module&gt; b = B() File "D:/Python/Advanced/randomStuff/supersub.py", line 11, in __init__ super().__init__() File "D:/Python/Advanced/randomStuff/supersub.py", line 3, in __init__ self.do() TypeError: do() missing 1 required positional argument: 'arg2' It seems to be calling the do() method in class B, but I want to call the do() method in Class A. Ideally, the code should print: A A B What am I doing wrong?
tagged with: overriding
has answer: http://stackoverflow.com/a/49269208
has answer: http://stackoverflow.com/a/49269359
score: 6

http://stackoverflow.com/a/49130122
score: 1
upvote count: 1
has body: Your error because when you go through the s tring. Your first i: response = 0 but you print d['int value'] which d doesn't has at that time. This will work: s= '''response: 0 id: 70402 type: 1 has value int value: 15 ''' s=s.replace("has","has:") s = s.strip() print s d = {} for i in s.split('\n'): try: key, val = i.split(":") d[key.strip()] = val.strip() except ValueError: print "no key:value pair found in", i print d['int value'] If you want to get the error with the key. You should add: except KeyError: print "key error found in", i Or just change ValueError to KeyError
has comment: http://stackoverflow.com/comment/85266268
answers question: http://stackoverflow.com/q/49129934
downvote count: 0
type: Answer

http://stackoverflow.com/comment/85427412
type: QuestionComment
has text: Great, thank you @Stack I'll get onto that now - thanks for the pointer!
comment on: http://stackoverflow.com/q/49211426
score: 0
type: Comment

http://stackoverflow.com/q/49205799
has comment: http://stackoverflow.com/comment/85416970
tagged with: watchdog
has comment: http://stackoverflow.com/comment/85418152
has comment: http://stackoverflow.com/comment/85431651
has title: How to sync two folders which are in two different systems
has comment: http://stackoverflow.com/comment/85417052
has comment: http://stackoverflow.com/comment/85421424
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85416865
has answer: http://stackoverflow.com/a/49208563
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85417264
tagged with: linux
has comment: http://stackoverflow.com/comment/85416949
upvote count: 0
has comment: http://stackoverflow.com/comment/85418174
answer count: 1
tagged with: directory
accepted answer: http://stackoverflow.com/a/49208563
downvote count: 1
has body: I would like to do a two-way automatic sync between folders Directory A and Directory B. This means that whenever a file in Directory A or one of its sub-directories is changed, that change is immediately applied to Directory B, and whenever a file in Directory B or one of its sub-directories is changed, that change is immediately applied to Directory A. Thus, the two directories would be completely identical, including document properties. How can I achieve this? I m trying to this in python can anyone help?
favorite count: 0
tagged with: synchronization
type: Question
has comment: http://stackoverflow.com/comment/85416975

logic
tags question: http://stackoverflow.com/q/49128041
type: Tag
tag name: logic

http://stackoverflow.com/a/49176977
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49176892
downvote count: 0
upvote count: 1
has body: a = ["W", "", "X", "", "Y", "Z"] b = ["a", "b", "c", "d", "e", "f"] aNew,bNew = zip(*[(a[i], b[i]) for i in range(len(a)) if len(a[i]) &gt; 0]) print(aNew) #('W', 'X', 'Y', 'Z') print(bNew) #('a', 'c', 'e', 'f')

http://stackoverflow.com/comment/85414250
comment on: http://stackoverflow.com/q/49204317
has text: In line 2 you do a path split, so you had some path like /home/user/movie.mp4. Then you take movie.mp4 off of that and and put it on a different location on your system /tmp/movie.mp4 -- then it looks at the new location and didn't find the file. Try just removing `.split('/')[-1]`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85529860
type: Comment
type: QuestionComment
has text: I find this rather hard to understand. What do the letters signify? How should the plot look like according to those letters?
score: 0
comment on: http://stackoverflow.com/q/49262815

http://stackoverflow.com/q/49158604
linked to: http://stackoverflow.com/q/44594887
tagged with: python
type: AnsweredQuestion
upvote count: 9
accepted answer: http://stackoverflow.com/a/49159236
has title: Matplotlib animation update title using ArtistAnimation
tagged with: matplotlib
answer count: 1
has body: I am trying to use the ArtistAnimation to create an animation. And everything is working, except set_title isn't working. I don't understand why blit=False doesn't work. Do I need to go to a FuncAnimation? for time in np.arange(-0.5,2,0.01): writer.UpdatePipeline(time=time) df=pd.read_csv(outputPath + '0.csv', sep=',') df['x'] = 1E6*df['x'] df['Efield'] = 1E-6*df['Efield'] line3, = ax3.plot(df['x'], df['Efield']) line1A, = ax1.semilogy(df['x'], df['em_lin']) line1B, = ax1.semilogy(df['x'], df['Arp_lin']) line2A, = ax2.plot(df['x'], df['Current_em']) line2B, = ax2.plot(df['x'], df['Current_Arp']) ax1.set_title('$t = ' + str(round(time, n))) ims.append([line1A, line1B, line2A, line2B, line3]) im_ani = animation.ArtistAnimation(fig, ims, interval=50, blit=False) im_ani.save(outputPath + 'lines.gif', writer='imagemagick', fps=10, dpi=100) plt.show()
has answer: http://stackoverflow.com/a/49159236
favorite count: 0
type: Question
score: 9
has comment: http://stackoverflow.com/comment/85323008
downvote count: 0
tagged with: animation

http://stackoverflow.com/a/49195523
downvote count: 0
score: 2
type: Answer
answers question: http://stackoverflow.com/q/49183329
has body: AMP pages are required to reference their canonical version via: &lt;link rel="canonical" href="https://www.example.com/url/to/full/document.html"&gt; The correct way to discover the non-AMP version of a page, is to fetch the AMP document and extract the href value of it's canonical link tag. You can read more about this in the official documentation.
upvote count: 2

http://stackoverflow.com/comment/85274141
has text: How do I get them to be the same?
comment on: http://stackoverflow.com/q/49134554
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49146743
has comment: http://stackoverflow.com/comment/85298912
has comment: http://stackoverflow.com/comment/85298167
linked to: http://stackoverflow.com/q/1145217
favorite count: 0
type: Question
has body: I found this in pyhash.h. I know _PyHASH_MULTIPLIER is prime multiplier used for hashing but I just want to the rationale behind that prime number. I searched PEPs but didn't get anything constructive. Thank you.
tagged with: hash
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: cpython
tagged with: python
score: 0
has title: Rationale behind cpython's prime multiplier _PyHASH_MULTIPLIER
downvote count: 1

http://stackoverflow.com/comment/85372100
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49182978
has text: Oh, one more thing: You can create the module from the C side, but can you import it from the C side? Start at `PyImport_ImportModule` and move down through the lower-level functions until you find one that goes the opposite direction.
type: Comment

http://stackoverflow.com/q/49215252
accepted answer: http://stackoverflow.com/a/49215290
has answer: http://stackoverflow.com/a/49215296
has answer: http://stackoverflow.com/a/49215290
tagged with: python
tagged with: pandas
score: 2
upvote count: 2
type: AnsweredQuestion
answer count: 2
tagged with: pandas-datareader
downvote count: 0
has body: I have a file that has 50 million records and I have a list of indexes that I need to drop from the file. If I want to use pandas dataframe to read the file - I can run into memory issues (if I have limited memory). Let's say I do this: df = pd.read_csv('input_file') df = df.drop(df.index[example_ix_list]) df.to_csv('input_file', index=False) I might run into memory issues: File "/home/ec2-user/CloudMatcher/cloudmatcher/core/execution/user_interaction.py", line 768, in process new_unlabel_df = unlabel_df.drop(unlabel_df.index[list_ix]) File "/home/ec2-user/anaconda2/envs/cloudmatch/lib/python2.7/site-packages/pandas/core/generic.py", line 2162, in drop dropped = self.reindex(**{axis_name: new_axis}) File "/home/ec2-user/anaconda2/envs/cloudmatch/lib/python2.7/site-packages/pandas/core/frame.py", line 2733, in reindex **kwargs) File "/home/ec2-user/anaconda2/envs/cloudmatch/lib/python2.7/site-packages/pandas/core/generic.py", line 2515, in reindex fill_value, copy).__finalize__(self) File "/home/ec2-user/anaconda2/envs/cloudmatch/lib/python2.7/site-packages/pandas/core/frame.py", line 2679, in _reindex_axes fill_value, limit, tolerance) File "/home/ec2-user/anaconda2/envs/cloudmatch/lib/python2.7/site-packages/pandas/core/frame.py", line 2690, in _reindex_index allow_dups=False) File "/home/ec2-user/anaconda2/envs/cloudmatch/lib/python2.7/site-packages/pandas/core/generic.py", line 2627, in _reindex_with_indexers copy=copy) File "/home/ec2-user/anaconda2/envs/cloudmatch/lib/python2.7/site-packages/pandas/core/internals.py", line 3897, in reindex_indexer for blk in self.blocks] File "/home/ec2-user/anaconda2/envs/cloudmatch/lib/python2.7/site-packages/pandas/core/internals.py", line 1046, in take_nd allow_fill=True, fill_value=fill_value) File "/home/ec2-user/anaconda2/envs/cloudmatch/lib/python2.7/site-packages/pandas/core/algorithms.py", line 1467, in take_nd out = np.empty(out_shape, dtype=dtype) MemoryError Q: Can I read the file in chunks using pandas dataframe a…
favorite count: 0
has title: drop indexes from a huge pandas dataframe that cannot possibly fit in memory
possible better answer: http://stackoverflow.com/a/49215296
type: Question

http://stackoverflow.com/comment/85376496
comment on: http://stackoverflow.com/q/49185419
type: QuestionComment
has text: How do you intend to hold 2 series of unequal length (d = 9, e = 6) in a single dataframe?
type: Comment
score: 1

http://stackoverflow.com/a/49128845
has comment: http://stackoverflow.com/comment/85262410
has comment: http://stackoverflow.com/comment/85262773
has comment: http://stackoverflow.com/comment/85262633
has comment: http://stackoverflow.com/comment/85262604
has comment: http://stackoverflow.com/comment/85262894
type: Answer
has body: You should install pytesseract use pip (also see guide): pip install pytesseract and then: from PIL import Image from pytesseract import image_to_string print(image_to_string(Image.open('marlboro.png'), lang='eng')) or use python cross-platform module tesseract: pip install tesseract and use it as you have in your question: from PIL import Image from tesseract import image_to_string print(image_to_string(Image.open('marlboro.png'), lang='eng'))
answers question: http://stackoverflow.com/q/49125866
score: 0
has comment: http://stackoverflow.com/comment/85262576
has comment: http://stackoverflow.com/comment/85296193
has comment: http://stackoverflow.com/comment/85262694
has comment: http://stackoverflow.com/comment/85263815

http://stackoverflow.com/q/49160579
has title: Recording numbers generated in a loop
has comment: http://stackoverflow.com/comment/85326772
has comment: http://stackoverflow.com/comment/85326747
type: AnsweredQuestion
has body: I am creating a simple program to calculate how much of each component should be added to create a buffer of a desired final concentration of each component. I want the user to be able to add as many components as necessary to the buffer. For each component I have a loop that will tell the user how much of each component to add, but I can't seem to find a way to save each value as a variable and subtract it to the total buffer volume later. In short, I want to record the value of each component after the loop runs, but I do not know how to achieve this. Here is what I have so far Buffer_Volume = input('What does the final volume of the buffer need to be, in mL? ') Final_Volume = float(Buffer_Volume) Component_Number = int(input('How many components does this buffer have? ')) x = 0 for x in range(0, Component_Number): Stock = input('What is the molarity of the stock component? ') Stock_Molarity = float(Stock) Final = input('What does the final molarity of the component need to be? ') Final_Molarity = float(Final) #Volume = input('What does the final volume of the buffer need to be, in mL? ') #Final_Volume = float(Volume) Stock_Volume = (Final_Molarity * Final_Volume) / Stock_Molarity print('Add ' + str(round(Stock_Volume, 6)) + 'mL of stock component to the solution') print('Add ' + str((Final_Volume - Stock_Volume)) + 'mL of water to the solution')
accepted answer: http://stackoverflow.com/a/49160773
downvote count: 0
has comment: http://stackoverflow.com/comment/85326773
upvote count: 1
answer count: 1
tagged with: loops
tagged with: variables
has comment: http://stackoverflow.com/comment/85326721
favorite count: 0
has comment: http://stackoverflow.com/comment/85328606
type: Question
has answer: http://stackoverflow.com/a/49160773
has comment: http://stackoverflow.com/comment/85326984
score: 1
tagged with: python

http://stackoverflow.com/a/49168818
score: -1
answers question: http://stackoverflow.com/q/49168550
type: Answer
has body: Here's a simple way to insert variables into SQL statements: table = 'mytable' col1 = 'name' col2 = 'age' statement = 'select {}, {} from {};'.format(col1, col2, table) Is this what you're looking for? If not, i don't really understand the question.
downvote count: 1
upvote count: 0

http://stackoverflow.com/comment/85358023
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49176138
has text: I admire your way of solving this problem. :) (even though we do not know if the file could be pre-processed this way)

http://stackoverflow.com/q/49145235
linked to: http://stackoverflow.com/q/4978738
has body: Say there's a kind of function that returns either some value or None, and we have three such functions: egg, ham and spam. The goal is to call egg, ham, spam and return the first non-None value returned, and if there's no valid value return, return None. The most straightforward way would be: def func(): ret = egg() if ret: return ret ret = ham() if ret: return ret ret = spam() if ret: return ret return None or, a smarter but maybe harder to read solution is: def func(): return egg() or ham() or spam() Here're my questions (there could be more than three candidate functions to call): Is the second way hard to read and should be avoided? Is there a better way to design such control flow? I remember there's something in Lisp that does exactly this, but what about in Python?
favorite count: 0
has answer: http://stackoverflow.com/a/49153284
has comment: http://stackoverflow.com/comment/85295617
tagged with: algorithm
score: 1
has comment: http://stackoverflow.com/comment/85295826
tagged with: python
has answer: http://stackoverflow.com/a/49154878
type: Question
tagged with: coding-style
answer count: 2
has comment: http://stackoverflow.com/comment/85296360
has comment: http://stackoverflow.com/comment/85295523
has comment: http://stackoverflow.com/comment/85296032
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85297023
downvote count: 0
has title: How to design control flow for a "sifter" like behavior in Python?
upvote count: 1

http://stackoverflow.com/q/49149644
type: AnsweredQuestion
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49149669
has body: I want to count index elements by userID.My dataframe gender adID rating userID 1 m 100 50 1 m 101 100 1 m 102 0 2 f 100 50 2 f 101 100 3 m 102 62 3 m 107 28 3 m 101 36 2 f 102 74 2 f 107 100 4 m 101 62 4 m 102 28 5 f 109 50 5 f 110 100 6 m 103 50 6 m 104 100 6 m 105 0 I tried df.count('userID') But got output File "/home/mm/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py", line 5630, in count axis = self._get_axis_number(axis) File "/home/mm/anaconda3/lib/python3.6/site-packages/pandas/core/generic.py", line 357, in _get_axis_number .format(axis, type(self))) ValueError: No axis named adID for object type &lt;class 'pandas.core.frame.DataFrame'&gt; How to fix this?Do the index operations follow the same principles as the column ones?
type: Question
has answer: http://stackoverflow.com/a/49149669
answer count: 1
tagged with: python
has title: ValueError: No axis named userID for object type <class 'pandas.core.frame.DataFrame'

http://stackoverflow.com/q/49208377
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85423240
tagged with: python
has comment: http://stackoverflow.com/comment/85441127
has body: I was trying to handle QTabletEvent events generated from a WACOM Intuos ART tablet. I succeeded with the following code but was obliged to resize my QWidget handling the tablet events to the full Windows desktop size in order to receive the tablet events from all its surface (whereever the pen is located). It seems by default the tablet surface is mapped to the full desktop. I want to map it to my own widget client area. How to do this ? import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class TabletSampleWindow(QWidget): def __init__(self, parent=None): super(TabletSampleWindow, self).__init__(parent) self.pen_is_down = False self.pen_x = 0 self.pen_y = 0 self.pen_pressure = 0 self.text = "" # Resizing the sample window to full desktop size: frame_rect = app.desktop().frameGeometry() width, height = frame_rect.width(), frame_rect.height() self.resize(width, height) self.move(-9, 0) self.setWindowTitle("Sample Tablet Event Handling") def tabletEvent(self, tabletEvent): self.pen_x = tabletEvent.globalX() self.pen_y = tabletEvent.globalY() self.pen_pressure = int(tabletEvent.pressure() * 100) if tabletEvent.type() == QTabletEvent.TabletPress: self.pen_is_down = True self.text = "TabletPress event" elif tabletEvent.type() == QTabletEvent.TabletMove: self.pen_is_down = True self.text = "TabletMove event" elif tabletEvent.type() == QTabletEvent.TabletRelease: self.pen_is_down = False self.text = "TabletRelease event" self.text += " at x={0}, y={1}, pressure={2}%,".format(self.pen_x, self.pen_y, self.pen_pressure) if self.pen_is_down: self.text += " Pen is down." else: self.text += " Pen is up." tabletEvent.accept() self.update() def paintEvent(self, event): text = self.text i = text.find("\n\n") if i &gt;= 0: text = text.left(i) painter = QPainter(self) painter.setRenderHint(QPainter.TextAntialiasing) painter.drawText(self.rect(), Qt.AlignTop | Qt.AlignLeft , text) app = QApplication(sys.argv) mainform = TabletSampleWindow() ma…
tagged with: wacom
has comment: http://stackoverflow.com/comment/85433654
has comment: http://stackoverflow.com/comment/85423467
answer count: 0
tagged with: pyqt
upvote count: 3
tagged with: tablet
downvote count: 0
has title: Handling QTabletEvent, How to map the Tablet Full Surface to the Widget Client Area?
tagged with: events
favorite count: 0
type: Question
score: 3

http://stackoverflow.com/comment/85850907
comment on: http://stackoverflow.com/q/49136230
has text: Decided to use pycharm in the end, at least both IntelliJ and Pycharm are very similar
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49144000
has comment: http://stackoverflow.com/comment/85626865
upvote count: 16
has comment: http://stackoverflow.com/comment/85567996
has comment: http://stackoverflow.com/comment/85568715
has comment: http://stackoverflow.com/comment/85553935
type: AcceptedAnswer
downvote count: 0
score: 16
answers question: http://stackoverflow.com/q/49143787
accepted answer of: http://stackoverflow.com/q/49143787
has comment: http://stackoverflow.com/comment/85568303
has comment: http://stackoverflow.com/comment/85555169
has comment: http://stackoverflow.com/comment/85568863
type: Answer
has body: Problem But I am still struggling to understand what is happening and why it is happening. And also, why is variable res only assigned value ('a', 'l') in the first iteration of while loop? res is always assigned an empty list [] afterwards. Why is it not assigned ('b', 'm'), and then ('c', 'n') in second and third iteration? The reason the code you posted works in Python 2 while failing in Python 3, is because the built-in map returns an iterator in Python 3, rather than a list as it did in Python 2. Of course this doesn't really explain much unless you know what an iterator is. Although I could go in-depth about what an iterator is exactly1, the important part of iterators to understand here, is that: An iterator can only be iterated over once. Once you've iterated over an iterator once, it's exhausted. It's done. You can't use it anymore.2 When you iterate over the iters iterator in the list comprehension in your code, then iters is done and exhausted, and can no longer be used. So essentially all the list comprehension: [next(i) for i in iters] does is grab the first item from each iterator in iters (which are 'a' and 'l'), and then store those in a list. On the next iteration of your while loop, iters can no longer be used, its empty. So empty list are yielded. That's why in the first list yielded you see 'a' and 'l', while other subsequent list are empty. Lastly, the reason you're code degrades into an infinite loop, is because of the fact that an iterator object - even one that's been exhausted - will evaluate to True in a boolean context: &gt;&gt;&gt; it = map(str, [1, 2]) &gt;&gt;&gt; next(it) '1' &gt;&gt;&gt; next(it) '2' &gt;&gt;&gt; # The `it` iterator is exhausted &gt;&gt;&gt; next(it) Traceback (most recent call last): File "&lt;pyshell#17&gt;", line 1, in &lt;module&gt; next(it) StopIteration &gt;&gt;&gt; bool(it) # but it still evaluates to `True` in a boolean context True &gt;&gt;&gt; Solution The simplest solution to this problem is to cast the ite…
has comment: http://stackoverflow.com/comment/85624816

http://stackoverflow.com/comment/85357931
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49168556
has text: Are you just using this script to find these selectors once, to make it easier to write your Puppeteer script? Or will this be done every time you use Puppeteer? Are you actually using Puppeteer to interact with anything outside of the HTML document, e.g., the browser chrome?

http://stackoverflow.com/comment/85400296
has text: ========== RESTART: C:/Users/HP/Downloads/python/check_profanity.py ========== Traceback (most recent call last): File "C:/Users/HP/Downloads/python/check_profanity.py", line 16, in <module> read_text() File "C:/Users/HP/Downloads/python/check_profanity.py", line 4, in read_text quotes = open ("C:\\Users\HP\Downloads\book\just.txt") OSError: [Errno 22] Invalid argument: 'C:\\Users\\HP\\Downloads\x08ook\\just.txt'
type: Comment
comment on: http://stackoverflow.com/a/49197601
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85378161
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49185695
has text: I think i need something like `if field value none set point to 0 elif greater or equal to zero and equal to another field value set value to 1`
score: 0

http://stackoverflow.com/q/49202895
has comment: http://stackoverflow.com/comment/85411689
has comment: http://stackoverflow.com/comment/85411150
has comment: http://stackoverflow.com/comment/85411289
has comment: http://stackoverflow.com/comment/85411620
type: Question
upvote count: 0
has body: nested_dict = { b: { a: some_other_source_dict[b][a] or {} for a in a_list } for b in b_list } If some_other_source_dict[b][a] exists, the correct output should be: nested_dict = { b_key_1: { a_key_1: a_val_1, a_key_2: a_val_2 }, b_key_2: { a_key_1: a_val_3, a_key_2: a_val_4 } } If it doesn't exist, the output should be: nested_dict = { b_key_1: { a_key_1: {}, a_key_2: {} }, b_key_2: { a_key_1: {}, a_key_2: {} } }
downvote count: 2
has title: Why isn't this nested dict comprehension working in Python?
has comment: http://stackoverflow.com/comment/85411299
has answer: http://stackoverflow.com/a/49203213
tagged with: dictionary-comprehension
score: -2
answer count: 1
has comment: http://stackoverflow.com/comment/85411096
has comment: http://stackoverflow.com/comment/85411492
favorite count: 0
has comment: http://stackoverflow.com/comment/85411234
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49203213
tagged with: python

http://stackoverflow.com/a/49276296
downvote count: 0
has comment: http://stackoverflow.com/comment/85555356
has comment: http://stackoverflow.com/comment/85555116
has comment: http://stackoverflow.com/comment/85555113
has comment: http://stackoverflow.com/comment/85555208
type: Answer
has comment: http://stackoverflow.com/comment/85554995
answers question: http://stackoverflow.com/q/49276183
has body: Clearly one of the dictionaries in the list doesn't have a gender key. You can get rid of this by adding an extra part to the list comprehension len([x for x in l1 if "gender" in x and x['gender'] == "Male"])
has comment: http://stackoverflow.com/comment/85555049
upvote count: 2
score: 2

http://stackoverflow.com/comment/85369734
comment on: http://stackoverflow.com/q/49182009
score: 0
type: Comment
has text: You probably cannot pause during a call to write() because you are in kernel-land. It is probably pausing as soon as that syscall finishes.
type: QuestionComment

http://stackoverflow.com/comment/85385501
comment on: http://stackoverflow.com/q/49189962
has text: can you please edit that into the post?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49130767
type: Question
has title: How to render a WTF Form in flask from a template that is included in another template?
tagged with: wtforms
tagged with: python
has body: I would like to include the template for a WTF form in my home.html page like so: {% include "users/register.html" %} while keeping the code that renders home.html and the form register.html separate as shown below. I have a home page 'home.html' that is being routed by the 'index()' function in my 'app.py' file. 'app.py' also registers the blueprint 'user_blueprint' that is defined in the 'views.py' file. I have a function 'sign_up' that renders a wtf form in a template called 'register.html'. In home.html I want to do this: {% include "users/register.html" %}. My understanding is that this does not work because form is not being passed to home.html and including register.html in home.html is essentially like copying it and the form object will not be passed to home.html How can I go about rendering the template 'register.html' while maintaining the blueprint (and not just copying the form into 'index()')? Although perhaps this is not the best approach, in which case what would you suggest? Thanks app.py import... app = Flask(__name__) app.config.from_object('config') app.secret_key = "123" UPLOAD_FOLDER = os.path.join(app.root_path, 'static/img/products/') app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.before_first_request def init_db(): Database.initialize() @app.route('/') @app.route('/home') def index(): products = Product.find_all() return render_template('home.html', title='Home', products=products) app.register_blueprint(user_blueprint, url_prefix="/users") views.py user_blueprint = Blueprint('users', __name__) class RegisterUser(FlaskForm): first_name = StringField('first_name', validators=[DataRequired()]) last_name = StringField('last_name', validators=[DataRequired()]) email = StringField('email', validators=[DataRequired()]) password = StringField('password', validators=[DataRequired()]) @user_blueprint.route('/register', methods=['GET', 'POST']) def sign_up(): form = RegisterUser(request.form) if request.method == 'POST' and form.validate(): first_na…
tagged with: flask
has answer: http://stackoverflow.com/a/49442935
type: AnsweredQuestion
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/49442935
tagged with: jinja2

http://stackoverflow.com/comment/85397047
has text: You can't deliver a signal to a non-main thread. There are other ways to communicate with threads but if the thread is blocked for an arbitrary amount of time in a syscall then you're probably out of luck. However, this is too complex an issue to discuss in comments on an answer.
type: Comment
comment on: http://stackoverflow.com/a/49193505
type: AnswerComment
score: 1

http://stackoverflow.com/comment/85412531
score: 0
has text: this is exactly that I was trying. ..I can not give you vote due to low reputation :/ .. anyway, Thank very much !
comment on: http://stackoverflow.com/a/49203414
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49154607
has title: Exclude files with fnmatch
answer count: 3
tagged with: file
tagged with: fnmatch
favorite count: 0
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/91494018
has answer: http://stackoverflow.com/a/49154820
accepted answer: http://stackoverflow.com/a/49154820
has answer: http://stackoverflow.com/a/49154875
possible better answer: http://stackoverflow.com/a/49154875
has answer: http://stackoverflow.com/a/49155184
downvote count: 0
tagged with: python
has body: I am creating a loop in Python that runs through all files in specific directory using fnmatch.filter(). Currently I am going through all .csv files in specific folder as following: for file_source in fnmatch.filter(os.listdir(source_dir), "*.csv") What I would like to do is exclude files with pattern "Test*". Is that somehow possible to do with fnmatch. In worst case I would just create another internal if loop, but would prefer a cleaner solution.
score: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/85384838
has text: You can't connect more than one service to the same port! Please check the error logs. Please also check network or loopback access permissions.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49189246
type: QuestionComment

http://stackoverflow.com/comment/85446734
has text: Thank you @ImportanceOfBeingErnest.
comment on: http://stackoverflow.com/q/49218457
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49264283
type: AnsweredQuestion
score: 0
has body: Say I have two commands with associated parameters: command1 command2 I want to run the first command on ServerA and the second on ServerB Is the right way to do that in fabric by changing the env? give or take, is the below the correct way of doing so? Can't I have the list of hosts include all the servers and I get to choose to tell the run method on which server to execute? env.hosts = ['ServerA'] run( command1 ) env.hosts = ['ServerB'] run( command2 ) Thanks!
has title: What is the proper way for fabric to run two separate commands on two separate servers?
answer count: 1
has answer: http://stackoverflow.com/a/49390957
type: Question
accepted answer: http://stackoverflow.com/a/49390957
tagged with: fabric
tagged with: python

http://stackoverflow.com/q/49175373
has title: Turning a Python dict with mutiple values in to a list with every key value pair
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85355890
accepted answer: http://stackoverflow.com/a/49175456
tagged with: list
has comment: http://stackoverflow.com/comment/85355719
has answer: http://stackoverflow.com/a/49175456
type: Question
has comment: http://stackoverflow.com/comment/85356063
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49175554
has comment: http://stackoverflow.com/comment/85356044
has answer: http://stackoverflow.com/a/49175554
downvote count: 1
favorite count: 0
has body: I have a dictionary with changing number of values per key, e.g. my_dict = {'a':['e','f'],'b':['g'],'c':[]} I would like to extract every key value pair in a list, i.e. [('a','e'),('a','f'),('b','g')] So 'c' should not be a part of the list since it has no value associated.
has comment: http://stackoverflow.com/comment/85355689
answer count: 2
upvote count: 1
tagged with: python

http://stackoverflow.com/q/49244490
score: 3
downvote count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/49244602
accepted answer: http://stackoverflow.com/a/49244602
answer count: 1
tagged with: python
favorite count: 0
type: Question
has title: How to concat two pandas DataFrames with similar indices of differing sizes
has body: I want to combine two dataframes where individual indices exist in a sorted manner, but show up a different number of times in the dataframes that I want to combine. frame1 = pd.DataFrame([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], index=['A','B','B','C','C','C','D','E','E','F']) frame2 = pd.DataFrame([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], index=['A', 'A', 'B', 'C', 'C', 'D', 'D', 'E', 'F', 'F']) frame1.columns =['Hi'] frame2.columns =['Bye'] frame1 Out[160]: Hi A 1 B 2 B 3 C 4 C 5 C 6 D 7 E 8 E 9 F 10 frame2 Out[161]: Bye A 1 A 2 B 3 C 4 C 5 D 6 D 7 E 8 F 9 F 10 Desired output: Bye Hi A 1.0 1.0 A 2.0 NaN B 3.0 2.0 B NaN 3.0 C 4.0 4.0 C 5.0 5.0 C NaN 6.0 D 6.0 7.0 D 7.0 NaN E 8.0 8.0 E NaN 9.0 F 9.0 10.0 F 10.0 NaN Can't seem to find any right combinations of concat or join to do this. Is there any way?
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/a/49190718
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49190186
has body: The following code takes 3:20 on my laptop mac_list=list() for i in range(0, 100000000): strHex = hex(i)[2:].rjust(12, '0') mac_list.append(strHex[0:2] + ":"+strHex[2:4] + ":"+strHex[4:6] + ":"+strHex[6:8] + ":"+strHex[8:10] + ":"+strHex[10:12])
score: 1

http://stackoverflow.com/q/49187779
tagged with: http://stackoverflow.com/tag/xml
tagged with: python-2.7
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85466798
favorite count: 0
type: Question
has body: How to create a dynamic sequence based on Many2one fields, instead of fixed values. For example, student registration number based on degree, batch and year. How can I implement this using a sequence in Odoo 10?
tagged with: odoo-10
has comment: http://stackoverflow.com/comment/85386892
tagged with: odoo
score: 1
tagged with: python
has answer: http://stackoverflow.com/a/49191217
has title: How to create a dynamic sequence based on Many2one fields?

http://stackoverflow.com/comment/85492595
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49244280
has text: .content just doesnt exist - https://imgur.com/a/wVerZ
type: Comment

http://stackoverflow.com/q/49133234
tagged with: python
has comment: http://stackoverflow.com/comment/85275280
has comment: http://stackoverflow.com/comment/85275577
has comment: http://stackoverflow.com/comment/85271879
has comment: http://stackoverflow.com/comment/85274405
tagged with: dockerfile
has comment: http://stackoverflow.com/comment/85273447
has answer: http://stackoverflow.com/a/69906294
has comment: http://stackoverflow.com/comment/85273377
tagged with: docker
type: AnsweredQuestion
has title: Docker ENTRYPOINT with ENV variable and optional arguments
has body: I have a Dockerfile with an ENTRYPOINT that uses an ENV variable. I can't get the ENTRYPOINT structured so the container can also accept additional command line arguments. Here is the relevant part of the Dockerfile: ARG MODULE_NAME ENV MODULE_NAME=$MODULE_NAME ENTRYPOINT /usr/bin/python3 -m ${MODULE_NAME} That works fine if I just want to launch the container without additional arguments: docker run my-image But I need to be able to pass additional command line arguments (e.g., a "--debug" flag) to the python process like this: docker run my-image --debug With the form of ENTRYPOINT above, the "--debug" arg is not passed to the python process. I've tried both the exec form and the shell form of ENTRYPOINT but can't get it to work with both the ENV variable and command line args. A few other forms I tried: This runs but doesn't accept additional args: ENTRYPOINT ["/bin/bash", "-c", "/usr/bin/python3 -m ${MODULE_NAME}"] This gives "/usr/bin/python3: No module named ${MODULE_NAME}": ENTRYPOINT ["/usr/bin/python3", "-m ${MODULE_NAME}"] This gives "/usr/bin/python3: No module named ${MODULE_NAME}": ENTRYPOINT ["/usr/bin/python3", "-m", "${MODULE_NAME}"]
has comment: http://stackoverflow.com/comment/85273223
possible better answer: http://stackoverflow.com/a/69906294
has comment: http://stackoverflow.com/comment/85278578
has answer: http://stackoverflow.com/a/49156417
favorite count: 0
has comment: http://stackoverflow.com/comment/85275060
type: Question
has comment: http://stackoverflow.com/comment/85272776
has comment: http://stackoverflow.com/comment/85273297
score: 20
has comment: http://stackoverflow.com/comment/85274942
answer count: 2
upvote count: 20
downvote count: 0
has comment: http://stackoverflow.com/comment/85272714
accepted answer: http://stackoverflow.com/a/49156417

http://stackoverflow.com/a/49149022
answers question: http://stackoverflow.com/q/49148452
score: 3
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85308145
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49148452
has body: You don't need a side effect. Your 'redirect' response is just another return value for the session.request call. Set your attributes on the mock_return reference: mock_response = session_instance.request.return_value mock_response.status_code = 302 mock_response.headers = {"location": "https://absolute"} response = _request_url('METHOD', 'http://absolute') Use .side_effects for when you need to: raise exceptions handle multiple calls (you can set side_effects to a sequence of return values to produce, used in order). need to have access to the values that have been passed to the call (you can set side_effect to a function that'll be called with the same arguments). However: if the code you are testing is _request_url(), then it should not matter if the request resulted in a redirect or not. The code in _request_url() is entirely indifferent to what kind of response is being returned, so why should you need to test for that at all? If, on the other hand you are testing code that uses _request_url() as a utility function, then you should be mocking that function, and not the requests library.

http://stackoverflow.com/a/49162781
has body: Try this using python: for i in range(26): f = open(chr(97+i)+".html", "w") f.write("Some text") f.close() It should write a file with every letter in the alphabet.
answers question: http://stackoverflow.com/q/49162712
has comment: http://stackoverflow.com/comment/85333686
score: 0
type: Answer

http://stackoverflow.com/q/49191546
has comment: http://stackoverflow.com/comment/85388222
downvote count: 1
type: Question
score: 0
has title: Inconsistent regex behaviour in Python
has body: I have a regular expression that I have verified works correctly, proof is here: https://regex101.com/r/ffSVuD/6 Unfortunately when I use the same regex within some Python code I do not get the same behaviour. The regex does get a match, but it does not find the same match groups. Here is some demo code: import re ddl_string = """ CREATE TABLE default.test_parse_partitioned_table__using_parquet_1_082921496561 (DATA4 BIGINT, DATA5 BIGINT, DATA2 BIGINT, DATA3 BIGINT) USING parquet OPTIONS ( serialization.format \\'1\\' ) PARTITIONED BY (DATA2, DATA3) """ regex = r'CREATE +?(TEMPORARY +)?TABLE *(?P&lt;db&gt;.*?\.)?(?P&lt;table&gt;.*?)\((?P&lt;col&gt;.*?)\).*?USING +([^\s]+)( +OPTIONS *\([^)]+\))?( *PARTITIONED BY \((?P&lt;pcol&gt;.*?)\))?' match = re.search(regex, ddl_string, re.MULTILINE | re.DOTALL) if match.group("pcol"): print match.group("pcol").strip() else: print 'did not find any pcols in {matches}'.format(matches=match.groups()) which returns: did not find any pcols in (None, 'default.', 'test_parse_partitioned_table__using_parquet_1_082921496561 ', 'DATA4 BIGINT, DATA5 BIGINT, DATA2 BIGINT, DATA3 BIGINT', 'parquet', None, None, None) My intention is to populate DATA2, DATA3 into match.group("pcol") but as you will observe that is not happening. In my aforementioned regex verification at https://regex101.com/r/ffSVuD/6 it does find a match: I have fiddled around quite a lot trying to get a regex that will return what I need but no success hence this post. Can anyone help?
tagged with: python
tagged with: regex
favorite count: 0
has answer: http://stackoverflow.com/a/72679220
has comment: http://stackoverflow.com/comment/85388327
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85388215
answer count: 1
linked to: http://stackoverflow.com/q/28856238
upvote count: 1

http://stackoverflow.com/a/49200608
answers question: http://stackoverflow.com/q/49200573
type: Answer
has body: The python packages are associated with python versions. The praw package is only installed for Python 2 but NOT for Python 3. Depending on how you installed your python 3, you will need to install the praw package. For example, do pip3 install praw, conda install praw, etc.
score: 0

http://stackoverflow.com/q/49181602
tagged with: django
tagged with: python
tagged with: django-filter
score: 0
has title: Django filter queryset optimization
answer count: 0
tagged with: django-queryset
tagged with: django-models
type: Question
has body: I'm using django-filter and i have 40k+ record that comes from filter. def index(request): cleaned_objects = Mymodel.objects.filter(is_deleted=False) my_objects = ReportFilter(request.GET,queryset=cleaned_objects) and i'm giving some filter for example created_at__gte = 01.01.2011 and this query retrieve 40k records i also using django pagination but i'm getting timeout error. So how can i fix that timeout error and which optimization should i use.
has comment: http://stackoverflow.com/comment/85373768
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85378958

http://stackoverflow.com/q/49167933
type: Question
has answer: http://stackoverflow.com/a/49167967
has title: getting empty index after applying filter to paandas data frame
tagged with: python
type: UnansweredQuestion
tagged with: pandas
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
has body: am trying to apply filter to pandas dataframe, but getting empty index my df looks like this My code is... df = pd.DataFrame(list(boh), columns = ['MATERIAL', 'Plant', 'BOM Usage', 'Alt. BOM', 'Valid-From Date']) print df Alternate_bom = df['Alt. BOM'] == 1 print df[Alternate_bom]

http://stackoverflow.com/comment/85512965
has text: I would put the lats and long in the same array adding an extra dimension, instead of two separate arrays, and then you could use np.unique
comment on: http://stackoverflow.com/q/49254850
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49134687
upvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85274137
tagged with: infinite-loop
has comment: http://stackoverflow.com/comment/85274124
tagged with: python
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49134858
score: 0
has comment: http://stackoverflow.com/comment/85274016
has title: Unable to break infinite loop
tagged with: while-loop
has answer: http://stackoverflow.com/a/49134858
has body: There are various posts related to infinite loops on here but none reflect my particular predicament (they deal with Java or they do not match my code format etc). The code I have used is actually source code or 'answer code' to an exercise aimed at new students such as myself and it only supplies the 'correct code without correct format' which for an independent student can complicate things but also provide a more productive challenge. The code makes solid use of 'functions' and 'calling functions from within other functions' which leaves very little 'global code' as a result, this may make things slightly more complicated but hopefully experienced programmers won't be phased by this. I think the loop is either an issue with my 'while loop code indentation' or the 'while loop condition/counter code itself'. The loop code takes and uses data from other parts of the program code and shouldn't be completely ruled out but realistically I suspect the problem is one of the two former possible issues of either indentation or internal loop code itself, I have already tried multiple variations of 'indentation layout' as well as making quick fixes (misstyped syntax etc). The code in question can be found towards the end of the program code (there is only one 'while loop' in the program code) it is in the 'menu options' section of code under '# Loop through quotes selecting those referencing the appropriate month and store the data in the summary dictionary'. I have included two separate code windows, one highlighting the suspected 'problem code' and the the other with 'full program code'. Any help in any aspect will be appreciated. Code segment most likely to hold error def monthlyReport(): file = open(QUOTES_TO_DATE_FILE, 'r') text = file.read() file.close() quotes = text.split() month = input('Enter month: ') summary = {'Lawn':{'Quantity' : 0.0, 'Value' : 0.0}, 'Patio' :{'Quantity' : 0.0, 'Value' : 0.0}, 'Water Feature' :{'Quantity' : 0.0, 'Value' : 0.0}} # Loop through q…
tagged with: break
has comment: http://stackoverflow.com/comment/85275371
answer count: 1
has comment: http://stackoverflow.com/comment/85274054

http://stackoverflow.com/q/49192713
favorite count: 0
type: Question
type: UnansweredQuestion
has title: I want to convert decimal numbers from western arabic (0,1,2,3,4,5,6) to eastern arabic(٠, ١, ٢, ٣))
has comment: http://stackoverflow.com/comment/85391560
tagged with: localization
answer count: 1
upvote count: 1
tagged with: django
tagged with: arabic
has comment: http://stackoverflow.com/comment/85392112
downvote count: 1
tagged with: indic
has body: Is there any way available in python that I can convert decimal numbers (99.3) to (٩ ٩ .٣ ) I can convert the simple integers to eastern Arabic but the issue is with decimal. devanagari_nums = ('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹') number = str(numeral) return ''.join(devanagari_nums[int(digit)] for digit in number)
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/49194437

http://stackoverflow.com/a/49194281
has comment: http://stackoverflow.com/comment/85393436
has comment: http://stackoverflow.com/comment/85400216
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85393208
accepted answer of: http://stackoverflow.com/q/49194232
has comment: http://stackoverflow.com/comment/85393989
has comment: http://stackoverflow.com/comment/85395279
answers question: http://stackoverflow.com/q/49194232
has comment: http://stackoverflow.com/comment/85393336
score: 1
type: AcceptedAnswer
has body: No, it doesn't mean that at all. What it does mean is that you are not passing the user to the template. This is because you are using render_to_response - which apart from anything else is deprecated - rather than the render shortcut which runs context processors. Note, your login_required decorator makes that if request.user.is_authenticated() check pointless; the user will never not be authenticated. Also note that you really should be using template inheritance to break out things like the top nav and the HTML boilerplate into their own templates.
upvote count: 1
has comment: http://stackoverflow.com/comment/85395434

http://stackoverflow.com/comment/85363714
type: Comment
type: QuestionComment
has text: It is an insoluble problem as stated then. `ping` itself has `root` group membership (at least on *nix) and your either need to use `ping` or write or use a similar utility with `root` group membership or privileges. There is no shortcut to that.
score: 0
comment on: http://stackoverflow.com/q/49159493

http://stackoverflow.com/q/49135250
tagged with: python
has title: python regex unexpected end of pattern
has body: My problem is quite simple. I want to parse a string like this one : string = 'SENT (ADVWH Pourquoi) (NP (DET ce) (NC theme)) (PONCT ?)' I want to use regex (I am not an expert, I have used it few times before). I want to extract the first level of brackets, i.e. I want the result to be : (ADVWH Pourquoi) (NP (DET ce) (NC theme)) (PONCT ?) I used this regex, that I tested successfully on regex101, but it doesn't even want to compile : re.compile(r"\(([^()]|(?R))*\)") I also tried these ones that still work on regex101: re.compile(r"\(([^\(\)]|(?R))*\)") re.compile(r"\((([^\(\)]|(?R))*)\)") I always get the same answer from python : unexpected end of pattern. I really don't see what is the problem here, and why does it work on regex101 and not with python. Thanks a lot in advance!
type: AnsweredQuestion
score: 0
tagged with: regex
type: Question
has answer: http://stackoverflow.com/a/49135297
accepted answer: http://stackoverflow.com/a/49135297
answer count: 1

http://stackoverflow.com/q/49246442
linked to: http://stackoverflow.com/q/89228
tagged with: python
has comment: http://stackoverflow.com/comment/85496924
tagged with: variables
duplicate of: http://stackoverflow.com/q/89228
has comment: http://stackoverflow.com/comment/85498231
score: 0
tagged with: bash
answer count: 1
tagged with: shell
tagged with: unix
has title: Pass Python String to shell input
type: Question
has body: I have a Python program, it generates a string, say fileName. In fileName I hold something like "video1.avi", or "sound1.wav". Then I make an os call to start a program ! program arg1 arg2, where my fileName is arg2. How can I achieve that on the fly, without making the whole program return a single string (the fileName) and then pass it to the shell line? How can I make that during execution. The script executes in Jupyter. P.S. I am looping and changing the file name and I have to run that script at every loop.
has answer: http://stackoverflow.com/a/49246630
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85496669

http://stackoverflow.com/a/49311186
answers question: http://stackoverflow.com/q/49269823
has body: May as well share another slightly different variant, but still can't shake the feeling that there's some sublime way that we just can't see. Haven't marked any answers as correct yet, because i'm convinced python can do this in a simpler way, somehow. What's also driving me crazy is that if i remember correctly VB's format command can handle this (with a pattern like "### ####0"). Maybe it's just a case of not understanding how to use Python's .format correctly. The below accepts a float or decimal and a list indicating split positions. If there are still digits in the string after consuming the last split position, it re-applies that until it reaches the start of the string. def format_number(num, pat, sep=' '): fmt = [] strn = "{:.0f}".format(num) while strn: p = pat.pop() if pat else p fmt.append(strn[-p:]) strn = strn[:-p] if len(strn) &gt; p else '' return sep.join(fmt[::-1]) &gt;&gt;&gt; format_number(123456789, [3, 4]) &gt;&gt;&gt; '12 345 6789' &gt;&gt;&gt; format_number(1234567890, [3]) &gt;&gt;&gt; '1 234 567 890'
upvote count: 1
score: 1
type: Answer
downvote count: 0

http://stackoverflow.com/comment/85374129
type: QuestionComment
comment on: http://stackoverflow.com/q/49183315
has text: You selected Enoc_Practice-Items.ps1 Enoc_Practice-Items.ps1 : The term 'Enoc_Practice-Items.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + Enoc_Practice-Items.ps1 + ~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (Enoc_Practice-Items.ps1:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
score: 0
type: Comment

http://stackoverflow.com/comment/85487705
comment on: http://stackoverflow.com/a/49236844
type: Comment
has text: For the most part, the rules about how code executes in the subprocess are the same as the normal rules. The subprocess is just another Python process running some Python code. So, yes, execution starts at the top and proceeds downwards, with function calls, loops, and other control structures retaining their normal meaning.
type: AnswerComment
score: 0

http://stackoverflow.com/q/49237792
has comment: http://stackoverflow.com/comment/85524775
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/131056183
has comment: http://stackoverflow.com/comment/85480117
has answer: http://stackoverflow.com/a/56067344
downvote count: 0
has title: VS Code task and Python virtual environment
has answer: http://stackoverflow.com/a/58252426
favorite count: 0
type: Question
has body: I have a python virtual environment declared in my workspace settings, everything is fine with it. Now I have a build task that calls a make target which in turn calls a pip package. When I run it, it doesn't use my venv even though it is the selected interpreter. I've tried to add a activate venv/... before calling my make command but I get a Permission denied error in the embedded terminal. How can I use a virtual environment and tasks at the same time?
has answer: http://stackoverflow.com/a/49267401
linked to: http://stackoverflow.com/q/28227957
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/70456194
possible better answer: http://stackoverflow.com/a/56067344
has answer: http://stackoverflow.com/a/68709242
score: 29
tagged with: python
answer count: 6
has answer: http://stackoverflow.com/a/68581738
accepted answer: http://stackoverflow.com/a/49267401
upvote count: 29

http://stackoverflow.com/comment/85461665
comment on: http://stackoverflow.com/q/49228191
type: Comment
type: QuestionComment
has text: Is this a question about how to draw a separating line and color both parts or how to calculate, which line best separates the two populations? Apart from that, this is not a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve)
score: 0

http://stackoverflow.com/comment/85517224
score: 0
comment on: http://stackoverflow.com/a/49256941
type: Comment
type: AnswerComment
has text: Not sure what you mean. The blue line is at 22000. The red line is at 1500. It's your data and only you know about its meaning. You may use mathematics to shift them whereever you want them to be.

http://stackoverflow.com/comment/85375710
type: AnswerComment
has text: Do you mind editing it where I can just copy it and hit run and it works?
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49184817

http://stackoverflow.com/q/49174304
favorite count: 0
tagged with: encoding
type: Question
has comment: http://stackoverflow.com/comment/85395525
has body: I'm working with the latest Python 3. I'm trying to set the file encoding when getting a file with Paramiko. Below a snippet of my code: using paramiko using csv ... self._sftp = paramiko.SFTPClient.from_transport(self._transport) with self._sftp.file(filename) as csv_file: reader = csv.DictReader(csv_file, delimiter=';') for line in reader: data.customer_name = line["customer_name"] The file I'm trying to parse is a text file encoded in ISO-8859-1 (Latin-1). The file contains accent character like "èé". When I launch my script I got the exception below: def decode(self, input, final=False): # decode input (taking the buffer into account) data = self.buffer + input (result, consumed) = self._buffer_decode(data, self.errors, final) E UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd4 in position 691: invalid continuation byte The exception is raised on this line: for line in reader: I have try to search a solution to force the encoding when getting the file from Paramiko but I can't see any encoding parameter. Thanks for helping
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/85354612
tagged with: python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/26307271
tagged with: paramiko
tagged with: sftp
duplicate of: http://stackoverflow.com/q/26307271
has comment: http://stackoverflow.com/comment/85396758
upvote count: 1
score: 1
has title: How to set the file encoding when getting file from Paramiko

http://stackoverflow.com/a/49132383
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49132100
accepted answer of: http://stackoverflow.com/q/49132100
type: Answer
has body: You can use OrderedDict to control the order of key-value pairs in a dictionary. from collections import OrderedDict import json def ordered(d, desired_key_order): return OrderedDict([(key, d[key]) for key in desired_key_order]) toplevel_desired_key_order = ("author", "url", "text", "intent", "entities", "answer", "training") entity_desired_key_order = ("stop", "start", "entity", "text") with open("data.json") as file: d = json.load(file) result = ordered(d, toplevel_desired_key_order) result["entities"] = [ordered(entity, entity_desired_key_order) for entity in result["entities"]] with open("results.json", "w") as file: json.dump(result, file, indent=4) Result: { "author": "Kristofer", "url": "http://askubuntu.com/questions/226332/how-to-install-a-canon-mf8040cn-printer-on-ubuntu-12-04", "text": "How to Install a Canon MF8040Cn Printer on Ubuntu 12.04", "intent": "Setup Printer", "entities": [ { "stop": 5, "start": 4, "entity": "Printer", "text": "Canon MF8040Cn" }, { "stop": 11, "start": 9, "entity": "UbuntuVersion", "text": "12.04" } ], "answer": { "text": " For 14.04 through 16.04 do the following: \n\n Download the drivers from:\nhttps://www.usa.canon.com/internet/portal/us/home/support/details/printers/black-and-white-laser/mf4770n?tab=drivers#Z7_MQH8HIC0L88RB0AMD0F1Q42K25 \n\n untar it to a directory.\nfrom that directory (assuming 64-bit, adjust as you need to) \n\n cd ~/Downloads\ngunzip -c Linux_UFRII_PrinterDriver_V320_us_EN.tar.gz | tar xvf -\ncd Linux_UFRII_PrinterDriver_V320_us_EN/64-bit_Driver/Debian/\nsudo apt-get -y install libglade2-0 libc6:i386 lib32z1 libxml2:i386 libjpeg62:i386 libstdc++6:i386\ncd 64-bit_Driver/Debian\nsudo dpkg -i *.deb\n \n\n reboot \n\n run add printer .. should just show up automatically when you click the 'Add' button .. give it a few seconds and the printer chirps then just magically shows up. \n\n EDIT 3/2/15 for Vivid (15.04) (I suspect may need for 14.10 as well on brand new installation): \n\n Added extra software depe…
score: 2
upvote count: 2

http://stackoverflow.com/comment/85307464
type: QuestionComment
has text: There are several correct answers, please accept one of them.
comment on: http://stackoverflow.com/q/49151289
score: 0
type: Comment

http://stackoverflow.com/a/49231635
has comment: http://stackoverflow.com/comment/85469626
type: Answer
has comment: http://stackoverflow.com/comment/85471989
has comment: http://stackoverflow.com/comment/85468616
has comment: http://stackoverflow.com/comment/85469885
has comment: http://stackoverflow.com/comment/85469723
has comment: http://stackoverflow.com/comment/85468155
accepted answer of: http://stackoverflow.com/q/49228474
has comment: http://stackoverflow.com/comment/85504958
has comment: http://stackoverflow.com/comment/85468331
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85468294
has comment: http://stackoverflow.com/comment/85472782
has comment: http://stackoverflow.com/comment/85472959
has comment: http://stackoverflow.com/comment/85505349
answers question: http://stackoverflow.com/q/49228474
has comment: http://stackoverflow.com/comment/85472236
has comment: http://stackoverflow.com/comment/85505810
has comment: http://stackoverflow.com/comment/85468842
has comment: http://stackoverflow.com/comment/85470959
has comment: http://stackoverflow.com/comment/85470101
has body: I had similar problems with StaleElementReference exception. Problem here is that after supplying the next page number and sending Keys.RETURN Selenium finds the elements where you are waiting for but this are the elements of the old page, after loading the next page this elements are not connected to the Dom anymore but replaced by the ones of the new page but Selenium is going to interact with the elements of the former page wich are no longer attached to the Dom giving a StaleElement exception. After you pressed Keys.RETURN you have to wait till the next page is completly loaded before you start your loop again. This has to be something else then presence_of_all_elements_located((By.CLASS_NAME,"faq-sub-content exempted-result"). A good strategy for you could be waiting for the pageselector of the page you are navigating to having the class "NumericalPagerSelected". How to wait for an Element having an attribute with a specific value is described here: Using selenium webdriver to wait the attribute of element to change value See: StaleElementException when Clicking on a TableRow in an Angular WebPage how I solved it.

http://stackoverflow.com/comment/85547338
has text: I did. But unable to figure out the issue. I made the assignment to actual matrix itself. But it is updating both matrices.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49258716
type: QuestionComment

http://stackoverflow.com/a/49252907
answers question: http://stackoverflow.com/q/49252774
type: AcceptedAnswer
type: Answer
score: 3
upvote count: 3
has body: The problem is here: new = Session(sessionname, owner_id, owner_name).add_player(owner_id, owner_name) GameHandler.open_sessions.append(new) By immediately calling add_player on the newly created Session, new is not the Session but the result of add_player, and whatever that does, it seems to return None. Thus you are adding a bunch of None objects to your open_sessions list. Use this instead: new = Session(sessionname, owner_id, owner_name) new.add_player(owner_id, owner_name) GameHandler.open_sessions.append(new) Or if you want to keep it the way it was, you could change your Session class to provide kind of a "fluent interface" and have add_player (and other methods) return self: class Session: ... def add_player(self, id_, name): .... return self
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49252774

http://stackoverflow.com/a/49225425
has body: You can use a dictionary comprehension. Also as was noted in the comments, naming something dict in Python is not good practice.: dct = {'ID':'', 'gender':'male', 'age':'20', 'weight':'', 'height':'5.7'} dct = {k: None if not v else v for k, v in dct.items() } print(dct) Output: {'ID': None, 'gender': 'male', 'age': '20', 'weight': None, 'height': '5.7'} Just replace None with whatever you want it to default to. In your question, you want to replace with NaN. You can use any of the following: float('nan') if you are using Python 2.x, or with Python &lt;3.5 math.nan for Python 3.5+ numpy.nan using numpy
has comment: http://stackoverflow.com/comment/85454679
type: Answer
answers question: http://stackoverflow.com/q/49225394
score: 22
has comment: http://stackoverflow.com/comment/85454591
has comment: http://stackoverflow.com/comment/85455058
has comment: http://stackoverflow.com/comment/85454656
upvote count: 22
has comment: http://stackoverflow.com/comment/85454766
accepted answer of: http://stackoverflow.com/q/49225394
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85455099
has comment: http://stackoverflow.com/comment/85454778
has comment: http://stackoverflow.com/comment/85455068

http://stackoverflow.com/comment/85484142
score: 0
type: AnswerComment
has text: Yes, I checked that when I import the array from the external file and I assign names to the columns, it is changed from a 2D to a 1D
comment on: http://stackoverflow.com/a/49239335
type: Comment

http://stackoverflow.com/q/49174514
has comment: http://stackoverflow.com/comment/85354221
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85354400
favorite count: 0
type: Question
has body: I have been experimenting with decorators and found an interesting inconsistency with them, hope you might help me to resolve it. To begin with I had a decorator like this: &gt;&gt;&gt; def name(n): ... def decorator(fun): ... fun.name = n ... return fun ... return decorator and I used it like so: &gt;&gt;&gt; @name("my name jeff") ... def f(): ... print f.name since decorator returns fun I could do both: &gt;&gt;&gt; f() my name jeff &gt;&gt;&gt; f.name 'my name jeff' This was all fine and what I expected. Now comes the weird bit. My new decorator is as follows: &gt;&gt;&gt; def name(n): ... def decorator(fun): ... fun.name = n ... def wrapper(): ... return fun() ... return wrapper ... return decorator To me it looks like this should do the same thing as the one before it, however I get this: &gt;&gt;&gt; @name("my name jeff") ... def f(): ... print f.__name__ ... print f.name ... &gt;&gt;&gt; f() wrapper Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 5, in wrapper File "&lt;stdin&gt;", line 4, in f AttributeError: 'function' object has no attribute 'name' Whats even more weird is the following: &gt;&gt;&gt; def f(): ... print f.__name__ ... print f.name ... &gt;&gt;&gt; x = name("jeff")(f) &gt;&gt;&gt; x.name Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'function' object has no attribute 'name' &gt;&gt;&gt; x() f jeff Of course, x.name now fails since decorator returns wrapper and not fun. At the same time: &gt;&gt;&gt; f = name("jeff")(f) &gt;&gt;&gt; f() wrapper Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 5, in wrapper File "&lt;stdin&gt;", line 3, in f AttributeError: 'function' object has no attribute 'name' Furthermore: &gt;&gt;&gt; def name(n): ... def decorator(fun): ... fun.name = n ... @wraps(fun) ... def wrapper(): ... return fun() ... return wrapper ... return decorator ...…
has comment: http://stackoverflow.com/comment/85354555
tagged with: python
score: 4
has title: Python decorators with function attributes
tagged with: python-decorators
upvote count: 4
type: AnsweredQuestion
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/49174722
has comment: http://stackoverflow.com/comment/85354176
has answer: http://stackoverflow.com/a/49174722

http://stackoverflow.com/q/49237298
has title: Data Cleansing, List iteration and closest match, Python or R
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85477786
type: Question
has answer: http://stackoverflow.com/a/49300418
answer count: 2
upvote count: 0
type: UnansweredQuestion
has body: I have a problem of dirty data. I have a list of ~600k names. An example would be: John Doe, JohnDoe, JohnDoe2, JohnDoe 84302, I would like to use either Python or R, to iterate through this list and take the above closest match record (using a probability of closest match) and replace the current record, so the above list would look like: Iteration 1: John Doe, John Doe, JohnDoe2, JohnDoe 84302, Iteration 2: John Doe, John Doe, John Doe, JohnDoe 84302, Iteration 3: John Doe, John Doe, John Doe, John Doe, Any help would be much appreciated. Thanks
downvote count: 1
favorite count: 0
tagged with: http://stackoverflow.com/tag/r
has answer: http://stackoverflow.com/a/49238515

http://stackoverflow.com/a/49266586
score: 0
has comment: http://stackoverflow.com/comment/85560915
has body: I couldn't find why where doesn't work, but here is a way around : Creating a code to create your df : def make_row(): import random dico = {"MOSL_Rating" : ['Highly Effective', 'Effective', 'Ineffective', 'Developing'], "MOTP_Rating" : ['Developing', 'Ineffective', 'Highly Effective', 'Effective', 'Highly Effective'], "disp_rating" : range(100)} row = {} for k in dico.keys(): v = random.choice(dico[k]) row[k] =v return row def make_df(nb_row): import pandas as pd rows = [make_row() for i in range(nb_row)] return pd.DataFrame(rows) I can create a df : df = make_df(3) MOSL_Rating MOTP_Rating disp_rating 0 Highly Effective Ineffective 39 1 Highly Effective Highly Effective 71 2 Effective Ineffective 95 and a seconde one : df2 = make_df(3) df2 MOSL_Rating MOTP_Rating disp_rating 0 Effective Highly Effective 24 1 Effective Developing 38 2 Highly Effective Ineffective 16 I then create your tests : MOSL_high_efective = df['MOSL_Rating'] == 'Highly Effective' MOSL_efective = df['MOSL_Rating'] == 'Effective' MOSL_inefective = df['MOSL_Rating'] == 'Ineffective' MOSL_developing = df['MOSL_Rating'] == 'Developing' MOTP_high_efective = df['MOTP_Rating'] == 'Highly Effective' MOTP_efective = df['MOTP_Rating'] == 'Effective' MOTP_inefective = df['MOTP_Rating'] == 'Ineffective' MOTP_developing = df['MOTP_Rating'] == 'Developing' test1 = MOSL_high_efective &amp; MOTP_developing test2 = MOSL_high_efective &amp; MOTP_inefective test3 = MOSL_efective &amp; MOTP_inefective test4 = MOSL_inefective &amp; MOTP_high_efective test5 = MOSL_inefective &amp; MOTP_efective test6 = MOSL_developing &amp; MOTP_high_efective conditions = test1 | test2 | test3 | test4 | test5 | test6 and then update the values of first dataframe by the second one where the conditions are meet : lines_to_be_updates = df.loc[conditions].index.values df.loc[lines_to_be_updates, "disp_rating"] = df2[lines_to_be_updates]["disp_rating"] df MOSL_Rating MOTP_Rating disp_rating 0 Highly Effective Ineffective 24 1 Highly Effe…
type: Answer
answers question: http://stackoverflow.com/q/49265766

http://stackoverflow.com/a/53391008
has body: Try defining image data format from keras import backend as K K.set_image_data_format('channels_first') I think this should resolve your problem.
score: 1
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49183229
type: Answer
accepted answer of: http://stackoverflow.com/q/49183229
downvote count: 0

http://stackoverflow.com/comment/86960885
type: AnswerComment
comment on: http://stackoverflow.com/a/49972418
has text: oh, I'm sorry to necro the post. I'm a codefighter too could I get your ign to add you? thanks :)
type: Comment
score: 0

http://stackoverflow.com/comment/85490206
type: QuestionComment
has text: Yes, actually my example code was wrong. The calculated feature importance is computed with `clf.tree_.compute_feature_importances(normalize=False)`. I updated my answer.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49170296

http://stackoverflow.com/q/49140570
has title: Match string with pandas series that contain a list of strings
answer count: 3
has answer: http://stackoverflow.com/a/49140873
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/49140784
has body: I have a pandas dataframe like this: The values are string type. I would like to find out if each of these row contains the string '63'. So I first split each the strings at ',' by doing df['col_name'].str.split(','), which gives me this: So each row now contains a list of strings. I next tried to match the string by doing df['col_name'].str.split(',').str.contains('63') but it gives me this: Why? :( I'd like it to say False for all rows especially for the rows that contain the value 263.
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49140660
tagged with: split
tagged with: python
possible better answer: http://stackoverflow.com/a/49140784
tagged with: series
upvote count: 2
tagged with: string-matching
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49140660
score: 2

http://stackoverflow.com/a/49236541
type: Answer
score: 4
has comment: http://stackoverflow.com/comment/85478810
has body: when not using DRF - what is a poor idea... you have to build manually in your view the dict with the data you wish to return and then use from django.http.response import JsonResponse for serializing the result. def single_object_representation(obj): return { 'fid': obj.fid, 'user': obj.user.username, 'url': obj._get_file_url() } def demo_view(request): objects_to_serialize = File.objects.all() result = [single_object_representation(obj) for obj in objects_to_serialize] return JsonResponse(result, safe=False) using django.core.serializers see here: https://docs.djangoproject.com/en/2.0/topics/serialization/#subset-of-fields but make sure it will work with your property. For some fields like User you should use duble underscore notation __ e.g user__username otherwise (with DRF) - what I strongly recommend to you First of all install drf: pip install djangorestframework Then if there is still problem with your serializer give a try to the SerializerMethodField (if in doubt see the docs: http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield) from rest_framework import serializers class FileSerializer(serializers.ModelSerializer): url = serializers.SerializerMethodField() class Meta: model = File fields = ('fid', 'user', 'file', 'url') def get_url(self): return self. _get_file_url()
has comment: http://stackoverflow.com/comment/85478557
downvote count: 1
has comment: http://stackoverflow.com/comment/85479428
answers question: http://stackoverflow.com/q/49234739
has comment: http://stackoverflow.com/comment/85479484
has comment: http://stackoverflow.com/comment/85480393
has comment: http://stackoverflow.com/comment/85479753
upvote count: 5
has comment: http://stackoverflow.com/comment/85481066
has comment: http://stackoverflow.com/comment/85480189

google-cloud-sdk
tag name: google-cloud-sdk
type: Tag
tags question: http://stackoverflow.com/q/49148473

tcp
tags question: http://stackoverflow.com/q/49268568
tags question: http://stackoverflow.com/q/49160034
type: Tag
tags question: http://stackoverflow.com/q/49139232
tags question: http://stackoverflow.com/q/49246497
tags question: http://stackoverflow.com/q/49136690
tag name: tcp
tags question: http://stackoverflow.com/q/49123337

http://stackoverflow.com/comment/85415095
type: AnswerComment
comment on: http://stackoverflow.com/a/49204748
type: Comment
has text: @tscv11 share the code that you are running through dropbox, drive or similar.
score: 0

http://stackoverflow.com/q/49168550
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85342223
type: Question
tagged with: format
has answer: http://stackoverflow.com/a/49168818
type: UnansweredQuestion
tagged with: oracle-database
tagged with: python
has body: Because to deal with static sql into dynamic sql, so need to use python conversion format, for example DROP TABLE TABLE_NAME PURE; CREATE TABLE TABLE_NAME NOLOGGING AS SELECT DUMMY USER_ID FROM DUAL; CREATE INDEX I_TABLE_NAME_USER_ID ON TABLE_NAME(USER_ID) NOLOGGING; I want to convert the format to: First determine whether there is a “drop table” and then remove the data, replaced V_TAB_NAME: = 'TABLE_NAME'; IF (F_DROP_TAB (V_TAB_NAME) = 1) THEN V_SQL: = ' The final result is shown as V_TAB_NAME := 'TABLE_NAME '; IF (F_DROP_TAB(V_TAB_NAME) = 1) THEN SJ_SQL := ' CREATE TABLE TABLE_NAME NOLOGGING AS SELECT DUMMY USER_ID FROM DUAL'; EXECUTE IMMEDIATE SJ_SQL; COMMIT; END IF; SJ_SQL := ' CREATE INDEX I_TABLE_NAME_USER_ID ON TABLE_NAME (USER_ID) NOLOGGING'; EXECUTE IMMEDIATE SJ_SQL; It may be a bit difficult to understand, but I hope someone can give me a little string to iterate over and judge the modified example or idea. Thanks.
has title: python conversion format sql string

http://stackoverflow.com/comment/85386249
type: QuestionComment
has text: can you post the `groupby` code you tried?
comment on: http://stackoverflow.com/q/49190649
score: 0
type: Comment

http://stackoverflow.com/a/49198081
downvote count: 0
answers question: http://stackoverflow.com/q/49197937
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85405598
accepted answer of: http://stackoverflow.com/q/49197937
score: 3
upvote count: 3
type: Answer
has body: You can perform two groupby + count operations, followed by an index-aligned division: i = df.groupby(['Creditcard_number']).Cashier.count() j = df.groupby(['Cashier', 'Creditcard_number']).Cashier.count() (j / i).reset_index(name='Times_Used_By_Cashier') Cashier Creditcard_number Times_Used_By_Cashier 0 Steve Green 1111-1111-1111-1111 0.5 1 Steve Green 1111-1111-1121-1111 1.0 2 Steve Green 1111-2211-1111-1111 1.0 3 Steve Rogers 1111-1111-1111-1111 0.5 Or, if you want the result in "x/y" form (as strings), then - (j.astype(str) + '/' + i.astype(str)).reset_index(name='Times_used_by_cashier') Cashier Creditcard_number Times_used_by_cashier 0 Steve Green 1111-1111-1111-1111 1/2 1 Steve Green 1111-1111-1121-1111 1/1 2 Steve Green 1111-2211-1111-1111 1/1 3 Steve Rogers 1111-1111-1111-1111 1/2
has comment: http://stackoverflow.com/comment/85401105
has comment: http://stackoverflow.com/comment/85401147

http://stackoverflow.com/q/49271359
has comment: http://stackoverflow.com/comment/85547219
tagged with: insertion-order
has comment: http://stackoverflow.com/comment/85551312
tagged with: python
tagged with: networkx
has comment: http://stackoverflow.com/comment/85546563
has comment: http://stackoverflow.com/comment/85582535
has title: Insert a node to graph in its best place, not at end of graph
score: 0
has comment: http://stackoverflow.com/comment/85547079
has comment: http://stackoverflow.com/comment/85588045
tagged with: traveling-salesman
type: Question
tagged with: graph
has comment: http://stackoverflow.com/comment/85552886
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85582564
has body: Suppose I have a list=[2,5,7] (representing a visit order of cities). I want to insert node 6 to this list (or Graph); however, I'm looking for the best place of insertion (in terms of total cost of list). For instance Cost of list1=[2,6,5,7] is lower than cost of list2=[2,5,7,6]. The Cost function is the distance between nodes. For instance, Cost[2,6,5,7] = Distance[2][6] + Distance[6][5] + Distance[5][7] Is there any fast way of doing this? Is there any built-in function in Networkx (like nx.dijkstra_path_length(G, i, j, 'weight') which calculates shortest path before insertion) or any other package? Please note that list=[2,5,7] can be considered as a graph and easily generated by Networkx (2---5---7) P.S: I will provide a toy-sized instance below: a=[6,10] and list=[2,5,7] are my inputs. I want to add all nodes in a (6 and 10) to the best places in list (like adding a node to a TSP tour). There are two possible positions for insertion of 6 in list. A: between 2 and 5 B: between 5 and 7. Since Cost[2,6,5,7] &lt; Cost[2,5,7,6], option A provides lowest cost. Now list=[2,6,5,7]. Again for insertion of node 10, all three possible places should be checked A: between 2 and 6 B: between 6 and 5 C: between 5 and 7. Output would be a list like [2,6,5,10,7]

http://stackoverflow.com/comment/85264817
comment on: http://stackoverflow.com/a/49129603
has text: This doesn't seem to work when value in s1 is smaller than minimum value in s2.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49262481
tagged with: python
has comment: http://stackoverflow.com/comment/85542639
type: AnsweredQuestion
score: 0
tagged with: many-to-many
tagged with: filter
tagged with: models
has body: How to make a choice only from users who are in the group created in the admin panel? In Foreign Key, this could be done via limit_choices_to, and in MtM it is not known as. Google didn't help. class Application(models.Model): STATUS_CHOICES = ( ('In the work', 'В работе'), ('New', 'Новая'), ('Complited', 'Завершена') ) author = models.ForeignKey(User, related_name = 'author', null = True) title = models.CharField(max_length=50) text = models.TextField() room = models.CharField(max_length = 5) published_date = models.DateField(blank=True, null=True, default = datetime.datetime.now) status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='New') owner = models.ManyToManyField(User) def __str__(self): return self.title
answer count: 1
type: Question
accepted answer: http://stackoverflow.com/a/49264930
has answer: http://stackoverflow.com/a/49264930
has title: Filtering in ManytoManyField
has comment: http://stackoverflow.com/comment/85529278
tagged with: django

http://stackoverflow.com/comment/85402716
type: QuestionComment
has text: You seem to have crammed two completely unrelated functionalities into the same function. Why not write two separate functions, that way you don't have to worry about what `v` is at all.
comment on: http://stackoverflow.com/q/49198786
score: 2
type: Comment

http://stackoverflow.com/comment/85402734
type: Comment
type: QuestionComment
score: 0
has text: Please post the code you have, so we can take it from there.
comment on: http://stackoverflow.com/q/49198728

http://stackoverflow.com/q/49155166
upvote count: 1
score: 1
favorite count: 0
has body: How can I get database's content data? I wrote in index.py, def index(): user_data = UserData.query.filter_by(id=1) return render_template('index.html', user_data=user_data) in index.html &lt;div&gt; &lt;p&gt;{{ user_data.name }}&lt;/p&gt; &lt;/div&gt; in models.py class UserData(db.Model): id = db.Column(db.Integer) name = db.Column(db.Text) When I show index.html in browser,jinja2.exceptions.UndefinedError: 'name' is undefined error happens.I rewrote in index.py, def index(): user_data = UserData.query.filter_by(id=1).all() return render_template('index.html', user_data=user_data) but same error happens.How can i get&amp; show name value whose id=1 in index.html?How should I fix this code?
has answer: http://stackoverflow.com/a/49155303
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85314953
has title: How can I get database's content data?
tagged with: python
accepted answer: http://stackoverflow.com/a/49155303
tagged with: sqlalchemy
type: Question
answer count: 1
downvote count: 0

http://stackoverflow.com/q/49243497
tagged with: python
has title: PyQt5 Making a subclass widgets
type: Question
has comment: http://stackoverflow.com/comment/85491311
upvote count: 2
tagged with: pyqt
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/70292385
downvote count: 0
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/85491008
has comment: http://stackoverflow.com/comment/85490954
favorite count: 0
tagged with: qt
score: 2
has body: so I was wondering how I could make a subclass of a widget For example if I wanted to create a widget, that inherited methods and attributes from QtWidgets.QPushButton, however I would create extra methods and attributes on top of that. class Coord(QtWidgets.QPushButton): def __init__(self): super(Coord, self).__init__() self.coordinates = [] #basically adding attributes to the object "QPushButton" def set_text(self,text): self.setText(text) chrcount = 100 / len(text) self.setStyleSheet("font-size: {}".format(chrcount)) #This will set the text of the button, yet will resize it appropriatly This is an example. However, it creates the "button" widget as a new window. I was wondering how I could get it to act like QPushButton would anyway, just with the extra features I'd like to add to it Edit: Fixed- replaced my "super" function from def __init__(self): super(Coord, self).__init__() to def __init__(self,parent): super(Coord, self).__init__(parent) Don't really know how that fixed it but hey ho!
has comment: http://stackoverflow.com/comment/85536886
linked to: http://stackoverflow.com/q/37918012
answer count: 1

http://stackoverflow.com/q/49149348
has comment: http://stackoverflow.com/comment/85303256
upvote count: 5
has comment: http://stackoverflow.com/comment/85303616
tagged with: python
answer count: 2
has answer: http://stackoverflow.com/a/59096042
score: 5
has title: Check if Python is installed from R
has answer: http://stackoverflow.com/a/75344923
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85304172
downvote count: 0
has comment: http://stackoverflow.com/comment/85303032
has comment: http://stackoverflow.com/comment/85303246
has comment: http://stackoverflow.com/comment/85303150
linked to: http://stackoverflow.com/q/38481980
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/25329955
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/85303363
has body: What would be the most platform-independent way of checking whether Python is installed, from R? This question is actually the inverse of Check if R is installed from python. EDIT: Sys.which() does not, as far as I have experienced return the path of the Python executable, even though from the Windows command I can directly access python (meaning that the dir of the python executable is added to %PATH% variables?).
has comment: http://stackoverflow.com/comment/85303274
has comment: http://stackoverflow.com/comment/85303081

http://stackoverflow.com/comment/85466527
has text: `sleep` tells the OS to block the process. Nothing happens on the process in the meantime. no cpu is wasted on _that_ process.
comment on: http://stackoverflow.com/q/49231589
score: 3
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85496845
type: QuestionComment
type: Comment
has text: Can you rely on the fact that `totalRank` and `playerPoints` will be in the same order (that is, that `totalRank[n][0][0] == playerPoints[n[[0]` for all n)?
comment on: http://stackoverflow.com/q/49246354
score: 0

http://stackoverflow.com/comment/85302962
comment on: http://stackoverflow.com/a/49147005
score: 0
has text: As per the docs, I got your point and most probably this should solve the issue. But I am also dependent on third-party vendor so, I am waiting for their response.
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49181512
tagged with: telegram
has answer: http://stackoverflow.com/a/49188826
accepted answer: http://stackoverflow.com/a/49188826
tagged with: python
type: AnsweredQuestion
has title: How to use ForceReply in python-telegram-bot wrapper
upvote count: 3
score: 3
has body: I've tried for quite a while, reading the python-telegram-bot wrapper APIpython-telegram-bot wrapper, telegram bot API, code snippets etc, but my lack of understanding(My programming knowledge is selective google copy-pastes) does not permit me to successfully implement the ForceReply option. (ForceReply Basically what I'm trying is when a user types /sett the bot says "Enter No." and forces the user to reply to that message. Sorry if I'm missing something obvious.
downvote count: 0
has answer: http://stackoverflow.com/a/67433208
possible better answer: http://stackoverflow.com/a/67433208
has comment: http://stackoverflow.com/comment/85382516
has comment: http://stackoverflow.com/comment/85377992
favorite count: 0
type: Question
answer count: 2
tagged with: python-telegram-bot

http://stackoverflow.com/q/49132981
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85274732
upvote count: 2
score: 1
answer count: 1
downvote count: 1
favorite count: 0
has body: I am working on a trading bot and i'm finding difficulties in accessing the open, close, high and low price of past timestamps in order to plot them in a candlestick chart. I use Bravado package to make the API call and get the data on the last timestamps. Here's what i have so far: #!/usr/bin/python import bitmex import json client = bitmex.bitmex(api_key='',api_secret='') class candle: def __init__(self, open, high, low, close, timeStamp): self.open = open self.high = high self.low = low self.close = close self.timestamp = timeStamp def get_candles(timeFrame, symbol, count): tradeHistory = client.Trade.Trade_getBucketed(binSize=timeFrame, partial=True, symbol=symbol, reverse=True, count=count).result() openPrice = tradeHistory[0][0]['open'] highPrice = tradeHistory[0][0]['high'] lowPrice = tradeHistory[0][0]['low'] closePrice = tradeHistory[0][0]['close'] timeStamp = tradeHistory[0][0]['timestamp'] c = candle(openPrice, highPrice, lowPrice, closePrice, timeStamp) print(c.open) print(c.high) print(c.low) print(c.close) print(c.timestamp) #def new_order(symbol, orderQty, ordType, price): get_candles('5m', 'XBTUSD', count=10) The variable count dictates the number of timestamps to be collected. I want to be able to make each one of these timestamps a class candle object in order to perform statistical analysis. EDIT: here is the result of the API call (print(tradeHistory)): ([{'timestamp': datetime.datetime(2018, 3, 6, 18, 35, tzinfo=tzutc()), 'symbol': 'XBTUSD', 'open': 11122.5, 'high': 11125.0, 'low': 11050.0, 'close': 11123.0, 'trades': 166, 'volume': 907181, 'vwap': 11097.5474, 'lastSize': 1, 'turnover': 8175270370, 'homeNotional': 81.7527037, 'foreignNotional': 907181.0}, {'timestamp': datetime.datetime(2018, 3, 6, 18, 30, tzinfo=tzutc()), 'symbol': 'XBTUSD', 'open': 11116.5, 'high': 11122.5, 'low': 11050.0, 'close': 11122.5, 'trades': 120, 'volume': 1103521, 'vwap': 11090.163, 'lastSize': 6567, 'turnover': 9951416522, 'homeNotional': 99.51416522, 'foreignNotion…
has comment: http://stackoverflow.com/comment/85275020
type: Question
accepted answer: http://stackoverflow.com/a/49134708
has answer: http://stackoverflow.com/a/49134708
has title: Make a list of class objects from data fetched by an API in python
tagged with: python
has comment: http://stackoverflow.com/comment/85273779

http://stackoverflow.com/q/49263518
accepted answer: http://stackoverflow.com/a/49278412
has answer: http://stackoverflow.com/a/49278412
answer count: 1
downvote count: 0
upvote count: 1
tagged with: machine-learning
tagged with: scikit-learn
has title: Clustering algorithm for grouping based on y distance from 0
type: AnsweredQuestion
score: 1
has body: To build a supervised learning model, I have taken daily st.dev of the variable of interest. I would like to find clusters of daily st.dev, i.e., group 1 with smallest st.dev, group 2 with bigger, etc etc. The result of the clustering will provide the categorical labels for a CART algorithm. It is suspected there are 4 classes. I have a 2d matrix with dates 'X', and the daily st.dev 'y-true'. After converting the date column into a numeric: mat.X = pd.to_numeric(mat['X']) Using k-means in the sklearn lib, this is the result: kmeans = KMeans(n_clusters=3) kmeans = kmeans.fit(mat)] labels = kmeans.predict(mat) plt.scatter(mat[:,0],mat[:,1], c=kmeans.labels_, cmap='rainbow') The results did not cluster the st.dev data of the Y axis. Is this a good methodology? Should the columns be switched to cluster the st.dev data?
tagged with: python
favorite count: 0
type: Question

http://stackoverflow.com/comment/85416538
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49205663
has text: what do u mean hypothetical case? Does putting the -ve part right at the back of return command affect anything?

http://stackoverflow.com/q/49209773
type: Question
has comment: http://stackoverflow.com/comment/85424037
tagged with: python-3.x
has body: I was trying to create a program that takes a sequence of decimal numbers separated by commas and prints their sum, but it gives me this error: could not convert string to float: '.' and the code doesn't work with numbers bigger than 10, may anyone help me please? This is my code: s = "1.1,2,3,4,5,6,7,8,9" v = 0 r = 0 for i in s: if i != ",": v+= float(i) else: v = 0 r += v print(r)
type: UnansweredQuestion
downvote count: 0
upvote count: 1
has title: Why do I get this error: "could not convert string to float: '.' "?Why doesn't it work with numbers bigger than 10?
has comment: http://stackoverflow.com/comment/85424136
score: 1
has answer: http://stackoverflow.com/a/49209820
answer count: 1
tagged with: python
tagged with: floating-point
favorite count: 0

http://stackoverflow.com/q/49248003
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/85499675
tagged with: numpy
tagged with: list
tagged with: vector
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49248166
score: 0
has answer: http://stackoverflow.com/a/49248166
answer count: 1
type: Question
has title: How to have multiple conditions in list comprehension for 2d array
has body: let A = [3,4] and Y be an array of multiple values like Y = [2,3,2,2,2,2,2,3,3,3,3,3] X = [[ 1. 1. 1. ..., 0. 0. 0.] [ 0. 1. 0. ..., 0. 0. 0.] [ 0. 1. 1. ..., 0. 0. 0.] ..., [ 0. 0. 0. ..., 0. 0. 0.] [ 0. 0. 0. ..., 0. 0. 0.] [ 0. 0. 1. ..., 0. 0. 0.]] then I want to select all those vectors of X where the corresponding X[Y] is in A. So I wrote the following code: Xij = [X[Y == j] for j in set(a)] print(Xij) print(shape(Xij)) Output: (3, 1, 1) [array([[ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 1., 0., ..., 0., 0., 0.], ..., [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 1., 0., ..., 0., 0., 0.]]), array([[ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], ..., [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.]]), array([[ 0., 1., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 1., 1., 0., ..., 0., 0., 0.], ..., [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0., 0., ..., 0., 0., 0.], [ 0., 1., 0., ..., 0., 0., 0.]])] but this will lead a list of 2D array. I on other hand want a normal 2D array. I even tried with append function but that also doesn't seem to work Xi = [] for j in A: m = [X[Y == j]] Xi.append([m]) Desired output: instead of 3d array I got I want a normal 2d array appended together. Any suggestion on how can I make this work?
tagged with: python

http://stackoverflow.com/q/49254848
has comment: http://stackoverflow.com/comment/85513346
answer count: 3
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/85525756
favorite count: 0
has title: How to define variables that will be used in every iteration of a function within a class in python?
type: Question
has comment: http://stackoverflow.com/comment/85514544
has answer: http://stackoverflow.com/a/49255154
downvote count: 0
upvote count: 1
tagged with: python
has body: I have a class that defines a function define_stop_words that returns a list of string tokens. I then went to apply another function called remove_stopwords, which takes raw utf8 text as input, to a pandas dataframe df which contains text. The code looks something like this class ProcessText: def __init__(self, flag): self.flag = flag # not important for this question def define_stop_words(self): names = ['john','sally','billy','sarah'] stops = ['if','the','in','then','an','a'] return stops+names def remove_stopwords(self, text): return [word for word in text if word not in self.define_stop_words()] import pandas as pd df = pd.read_csv('data.csv') parse = ProcessText(flag=True) df['text'] = df['text'].apply(parse.remove_stopwords()) My question is, will the remove_stopwords function call on and define the variable returned by define_stop_words every time - for every word in text for every row in df (for every iteration basically)? If this is the case, I don't want it to run like this, as it would be very slow and inefficient. I want to define the variable returned by define_stop_words once, almost like a "global variable" within the ProcessText class, and then use that variable in remove_stopwords multiple times (for every word and row in df). Is there a way to do this - should this be done? What is the best practice in this case?
has comment: http://stackoverflow.com/comment/85513347
has answer: http://stackoverflow.com/a/49255060
possible better answer: http://stackoverflow.com/a/49255060
has answer: http://stackoverflow.com/a/49255464
accepted answer: http://stackoverflow.com/a/49255464
tagged with: class
type: AnsweredQuestion

http://stackoverflow.com/comment/85263309
comment on: http://stackoverflow.com/a/49129333
has text: `str(val)` working for scalar, in pandas is necessary `df['col1'].astype(str)`
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/73055464
has body: I have tried this and it worked for me on windows. $env:FLASK_APP="hello.py" flask run That's it
type: Answer
answers question: http://stackoverflow.com/q/49238583
score: 0

http://stackoverflow.com/comment/85312696
has text: I'm on Windows 10 and I try to compile Pupil labs from source. I have installed everything and this is the error I get when trying to run it. https://docs.pupil-labs.com/#python-libs it looks like it's something wrong with the av module: https://github.com/pupil-labs/pyav/releases/tag/v0.3.1
score: 0
comment on: http://stackoverflow.com/q/49153792
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49240582
favorite count: 0
type: Question
score: 0
tagged with: internet-explorer
has title: Where is the handle of a new Tab? - Python Selenium
has comment: http://stackoverflow.com/comment/85490024
has comment: http://stackoverflow.com/comment/85485034
has answer: http://stackoverflow.com/a/49242446
tagged with: python
has comment: http://stackoverflow.com/comment/85485389
type: UnansweredQuestion
answer count: 1
tagged with: selenium
tagged with: web-scraping
upvote count: 1
has comment: http://stackoverflow.com/comment/85488289
downvote count: 1
has body: I am using Python's Selenium (with IE webdriver) to open a new tab... however, I cannot get the handle of the new tab. Below is sample code that shows the problem: from selenium import webdriver from selenium.webdriver.common.keys import Keys #open IE driver = webdriver.Ie() # Open new tab driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't') # Print handles print(driver.window_handles) The answer to the print statement above, is: ['5bd4ca0b-0095-4851-a36d-54f8c602c906'] I would expect to get a list with TWO items, but I only get one. The code above works if I use the Chrome webdriver. So, is this a bug in the IE webdriver?

vmd
type: Tag
tags question: http://stackoverflow.com/q/49267452
tag name: vmd

http://stackoverflow.com/comment/85481436
comment on: http://stackoverflow.com/a/49238377
score: 0
type: AnswerComment
has text: Also, I believe the result you have has words like x becoming y instead of y becoming x
type: Comment

http://stackoverflow.com/a/49155384
has comment: http://stackoverflow.com/comment/85629232
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49149442
has comment: http://stackoverflow.com/comment/85629749
type: Answer
accepted answer of: http://stackoverflow.com/q/49149442
has comment: http://stackoverflow.com/comment/85630215
has comment: http://stackoverflow.com/comment/85337204
has body: Ok I figured this one out. Because I was getting the proper format returned, that means that I was trying to communicate with db, but something was amiss with the python/javascript communication. I'm pretty sure that python does not understand javascript. That is why everything must be explictly stated as a string. For example, with: db["collection"].update({u'foo' : bar},{'$push':{u'baz' : foobaz}}). Notice how I must use 'foo' instead of foo. The same goes for the values. I am updating the values by a variable passed into a function. In order for pymongo to correctly convert this into javascript to communicate with my mongoDB database, i must also explicitly convert it into a string with str(bar) and str(foobaz). None of this would be possible with python unless I was using pymongo. So in order for pymongo to do it's magic, I must give it the proper format. This doesn't seem to apply to all versions of python and pymongo, as i've searched this problem and none of the people using pymongo had to use this specific conversion. This may also have something to do with the fact that i'm using python 2.7. I know that the typechecking/conversion is a little different in python3 in some instances. If someone can explain this in a more lucid way (using the correct python and javascript terminology) that would be great. Update: This also seems to hold true for any type. eg. in order to increment using the $inc operator with 1, I must also use int(1) to convert my int into an int explicitly. (Even though this is kind of weird, because int should be primitive, but maybe it's an object in python).

http://stackoverflow.com/comment/85341170
has text: Its impossible to say what's wrong with only two lines of code, you should include more code. Also, why are you not just using model.fit?
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49162202

http://stackoverflow.com/comment/85522323
type: Comment
comment on: http://stackoverflow.com/q/49259470
score: 0
type: QuestionComment
has text: Ok, but have to use the "with open(filename, 'r') as f:" - command again. Otherwise, I can´t print. Can I solve this without using the "with open" command twice?

http://stackoverflow.com/comment/85519257
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49258113
has text: are you sure this will work across Python processes? :^)

http://stackoverflow.com/comment/85353016
type: AnswerComment
has text: Great, I wasn't aware rolling can handle variable time windows. Will give it a try and revert back. Thanks!
comment on: http://stackoverflow.com/a/49173921
score: 0
type: Comment

http://stackoverflow.com/q/49151168
tagged with: google-colaboratory
score: 15
has answer: http://stackoverflow.com/a/73182043
has answer: http://stackoverflow.com/a/60262811
has answer: http://stackoverflow.com/a/53982547
favorite count: 0
linked to: http://stackoverflow.com/q/48905127
type: Question
has answer: http://stackoverflow.com/a/49152023
upvote count: 15
has body: I am trying to run my program on Google Colab; where my code make use of .py files written seprately. In normal system I have all files inside one folder and it works using import xyz, but when I tried using same folder in Google drive it gives import error.
has title: How to import python files in google colaboratory?
has answer: http://stackoverflow.com/a/53688741
answer count: 5
type: UnansweredQuestion
downvote count: 0
tagged with: python

http://stackoverflow.com/comment/85394332
comment on: http://stackoverflow.com/a/49170424
score: 0
type: Comment
type: AnswerComment
has text: This answer was missing `form.save()`. I've edited the answer so that it now calls save with `commit=False`, sets the usertype, then saves the user.

http://stackoverflow.com/comment/85491049
score: 0
comment on: http://stackoverflow.com/a/49243402
type: Comment
has text: I would need the value for all of the probes. I'm basically trying to normalise all of the probes against the sum of the control probes.
type: AnswerComment

http://stackoverflow.com/comment/85367056
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49180582
has text: Thanks, people pointed out to change to use equality operators. This got me thinking "theoretically" if I wanted to use how would it work. I will go with different syntax but this answer is good, thanks. :)
type: Comment

http://stackoverflow.com/q/49225416
downvote count: 2
has comment: http://stackoverflow.com/comment/85454483
has answer: http://stackoverflow.com/a/49225572
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85454482
type: Question
answer count: 2
tagged with: python
score: -2
accepted answer: http://stackoverflow.com/a/49225592
has title: How might I go about making the .sort() method sort by more than just the first digit?
has answer: http://stackoverflow.com/a/49225592
tagged with: python-3.4
has body: I am trying to sort a list. But when I try, it always seems to sort by just the first digit. This is my code: data = input("enter your data separated by spaces: ") data = data.split(' ') data.sort() My input is just numbers. eg. 1 25 3 466 4 32 5 but with this input the output is something like 1 25 3 32 466 4 5 my goal is to have the variable data sorted properly. I would like the output for the input mentioned earlier to be 1 3 4 5 25 32 466. I am new to python so i apologize if this question is simple or if my terminology is off.
type: AnsweredQuestion
upvote count: 0
possible better answer: http://stackoverflow.com/a/49225572

http://stackoverflow.com/a/49183093
has body: Your function does not return any values, it only prints them. Instead of something like: def create_table(): print("Hello, World!") output = create_table() # output is None Try: def create_table(): string_to_return = "Hello, World!" return string_to_return output = create_table() # output is "Hello, World!"
answers question: http://stackoverflow.com/q/49183032
downvote count: 0
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/a/49242833
has comment: http://stackoverflow.com/comment/85492095
has comment: http://stackoverflow.com/comment/85489532
answers question: http://stackoverflow.com/q/49242741
type: Answer
has body: First off, it looks like you've got json data there. http://www.json.org/ Python has a built in library for loading that data. https://docs.python.org/3.6/library/json.html To load it the code would look like this import json with open(completename, 'r') as f: data = json.load(f) Now to get all the column names you can look at each object and aggregate their keys column_names = set() for item in data: for column in item: column_names.add(column) After that all the column names will be in the column_names set
has comment: http://stackoverflow.com/comment/85489851
has comment: http://stackoverflow.com/comment/85492097
has comment: http://stackoverflow.com/comment/85490181
has comment: http://stackoverflow.com/comment/85490298
has comment: http://stackoverflow.com/comment/85494225
score: 0
has comment: http://stackoverflow.com/comment/85493364
has comment: http://stackoverflow.com/comment/85494240

http://stackoverflow.com/a/49269969
accepted answer of: http://stackoverflow.com/q/49269874
type: Answer
answers question: http://stackoverflow.com/q/49269874
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has body: Try using dictionary comprehension. old_values = {'the': 117, 'to': 77, '.': 77, ',': 56, 'a': 46, 'is': 46, 'and': 41, 'that': 39} m = max(old_values.values()) new_values = {k: v / m for k, v in old_values.items()} This produces a dictionary like this: {'the': 1.0, 'to': 0.6581196581196581, '.': 0.6581196581196581, ',': 0.47863247863247865, 'a': 0.39316239316239315, 'is': 0.39316239316239315, 'and': 0.3504273504273504, 'that': 0.3333333333333333}
score: 3

http://stackoverflow.com/comment/85319064
comment on: http://stackoverflow.com/q/49156995
score: 1
type: QuestionComment
has text: share the .svc file.
type: Comment

http://stackoverflow.com/a/49175797
has comment: http://stackoverflow.com/comment/85358013
has comment: http://stackoverflow.com/comment/85362016
has comment: http://stackoverflow.com/comment/85372343
has comment: http://stackoverflow.com/comment/85357603
has comment: http://stackoverflow.com/comment/85358990
accepted answer of: http://stackoverflow.com/q/49172719
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85358221
answers question: http://stackoverflow.com/q/49172719
has comment: http://stackoverflow.com/comment/85358492
has comment: http://stackoverflow.com/comment/85357667
type: AcceptedAnswer
downvote count: 0
has body: This could be done in Python 2.x as follows: from itertools import dropwhile from collections import defaultdict import glob import csv fieldnames = ['E-MAIL ADDRESS', 'FIRST TIME LOGGED IN', 'LAST TIME LOGGED IN', 'USERNAME'] emails = defaultdict(list) for csv_filename in glob.glob('*.csv'): with open(csv_filename, 'rb') as f_input: csv_reader = csv.DictReader(f_input, fieldnames=fieldnames, skipinitialspace=True) next(dropwhile(lambda x: x['E-MAIL ADDRESS'] != 'E-MAIL ADDRESS', csv_reader)) for row in csv_reader: emails[row['E-MAIL ADDRESS']].append(row) with open('output.csv', 'wb') as f_output: csv_writer = csv.DictWriter(f_output, fieldnames=fieldnames, extrasaction='ignore') csv_writer.writeheader() for email, rows in sorted(emails.items()): if len(rows) &gt; 1: csv_writer.writerows(rows) This uses the glob.glob() function to give you a list of .csv files. It writes all email addresses to output.csv where the email address is seen more than once across all CSV files found. It skips all lines until the line starting E-MAIL ADDRESS is found.
upvote count: 1
has comment: http://stackoverflow.com/comment/85358402

http://stackoverflow.com/a/49228000
has comment: http://stackoverflow.com/comment/85459513
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/85459504
has comment: http://stackoverflow.com/comment/85459490
has comment: http://stackoverflow.com/comment/85459489
type: Answer
score: -2
answers question: http://stackoverflow.com/q/49227963
has body: y = [1,2,3,4,5,6,7] result = [] for x in y: if x == 3: result.append(x) elif x == 4: result.append(x) elif x == 6: result.append(x) else: # or pass if you want to ignore result.append(None) return result
has comment: http://stackoverflow.com/comment/85459672

http://stackoverflow.com/comment/85530790
has text: List or array? Are you using numpy or vanilla python?
comment on: http://stackoverflow.com/q/49263653
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85546523
score: 0
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/4355061/how-to-wrap-and-indent-long-lines-when-using-print-in-python related?
comment on: http://stackoverflow.com/q/49271678

http://stackoverflow.com/q/49221991
type: UnansweredQuestion
tagged with: python
tagged with: selenium-webdriver
has body: I started a scraper multi pages with python and selenium for my company a couple days a go. It works, but it's very slow... arround 20seconds for each page. I would like to get him faster. My problem from this line call 3 times : browser = webdriver.Firefox() Have You got an idea how can I do it better please? This is my code : #!/usr/bin/python3 # -*- coding: utf-8 -*- from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from data_class import * import time def get_data_object(link): """ return data object with values saved """ data = Data() try: browser = webdriver.Firefox() browser.get(link) except NoSuchElementException: print(link + "\033[31m" + " => Failled" + "\033[0m") return try: data.set_title(browser.find_element_by_css_selector("h1.epi-fontLg")) except NoSuchElementException: print("\ttitle missing") data.set_extracte_date(time.time()) data.set_url(link) print(data.url) try: data.set_date_post(browser.find_element_by_css_selector("time")) except NoSuchElementException: print("\tdate missing") try: data.set_compagny_name(browser.find_element_by_css_selector("div.bw-release-companyinfo h3 span")) except NoSuchElementException: print("\tcompagny name missing") try: data.set_ticket_code(browser.find_element_by_css_selector("div#cic a span")) except NoSuchElementException: print("\tticket code missing") try: data.add_hash_tag(browser.find_elements_by_css_selector("ul.hash-tags li a.hash-tag")) except NoSuchElementException: print("\thash tag missing") try: data.add_cash_tag(browser.find_elements_by_css_selector("ul.cash-tags li a.cash-tag")) except NoSuchElementException: print("\tcash tag missing") try: data.set_content(browser.find_element_by_css_selector("div.bw-release-story")) except NoSuchElementException: print("\tcontent missing") return data def save_data_object(link): """ save data object and add it in BDD """ data = get_data_object(link) ... ADD IN BDD ... def get_links_pages(link): """ get all links from the…
score: 0
has comment: http://stackoverflow.com/comment/85448313
has title: selenium webserver multi pages
tagged with: selenium
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85447537
answer count: 0

http://stackoverflow.com/comment/85347475
comment on: http://stackoverflow.com/q/49170908
has text: I'd love to help you, what are you exactly looking for ? To me, saying `How would I in this example calculate the derivatives of T.fun() with respect to 'a' and 'b'?, you're asking for a mathematical question, a formulae. Do you wish to have your `derivative` function inside `T()` class ?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/88776716
type: Comment
has text: Right, ffmpeg should be installed (I didn't say it is already installed). Thanks.
type: AnswerComment
comment on: http://stackoverflow.com/a/49133350
score: 0

http://stackoverflow.com/q/49143689
upvote count: 2
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
has title: Python: xpath robust to get data in table
has body: I want to get the data in http://www.images.watoday.com.au/business/markets/movers for "WHOLE MARKET TOP GAINERS" only. My code as below: import requests from lxml import html page_gain = requests.get('http://www.images.watoday.com.au/business/markets/movers') gain = html.fromstring(page_gain.content) name = gain.xpath('//h2[contains(.,"Whole Market Top Gainers")]/following::a/text()') data = gain.xpath('//h2[contains(.,"Whole Market Top Gainers")]/following::td/text()') My desirable output is ['MEM','MEMPHASYS LTD','0.002','0.001','100.00','1,000,000','AUH','AUSTCHINA HOLDINGS','0.007','0.002','40.00','1,433,311'....]
tagged with: lxml
score: 2
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49144238
has answer: http://stackoverflow.com/a/49144238
tagged with: http://stackoverflow.com/tag/xml
favorite count: 0
type: Question
tagged with: xpath

http://stackoverflow.com/a/49186162
has body: for n in number_list: (do something) Pick one element from the number_list(in Pur case its a range) then save that value in a variable called 'n' , the value of the 'n' will change every time you run the for loop. the loop will exit when it encounters a 'StopIteration'. The variable 'n' will get created automatically with a value we fetch from the number_list while n in number_list &lt; 20: Here you checking a variable's value present inside the list number_list. But it is not defined. while only runs when it get True value from the condition
answers question: http://stackoverflow.com/q/49186091
type: Answer
score: 0

http://stackoverflow.com/q/49216971
has comment: http://stackoverflow.com/comment/85438551
has title: web-scrape basketball reference how to exclude the playoffs in April
has comment: http://stackoverflow.com/comment/85438211
answer count: 1
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/49217324
type: Question
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85438044
has comment: http://stackoverflow.com/comment/85438363
has comment: http://stackoverflow.com/comment/85438367
score: 0
has comment: http://stackoverflow.com/comment/85438309
has body: I'm trying to scrape this page. I was able to scrape the results for October to March but I'm having problems for April because there is a thead for the playoffs ( Playoffs ) and it is showing ValueError: Unknown string format. I would like the scraping to end or skip this specific row. Here's my code : data = [[td.getText() for td in data_rows[i].findAll(['th','td'])] for i in range(len(data_rows))]

http://stackoverflow.com/comment/85457204
type: Comment
type: QuestionComment
score: 0
has text: Please post sample of undesired results to avoid ambiguity of *I am getting mixed results*
comment on: http://stackoverflow.com/q/49226624

http://stackoverflow.com/q/49135854
tagged with: python
tagged with: mouseevent
score: 0
upvote count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85276578
answer count: 1
downvote count: 1
tagged with: interactive
has answer: http://stackoverflow.com/a/49136051
favorite count: 0
tagged with: scatter-plot
type: Question
has title: Mouse scattering with matplotlib
has body: I'd like to use matplotlib for interactive drawing. I trained a neural network to approximate a distribution and I want to manually see if it is correct. Hence, once the computation is done I want to: Mouse my mouse on the window. The pointer should be followed by a point (plt.scatter) Get coordinates of the mouse and send them to my network Using output from network, change the color of the point Any leads I could follow ? Thanks !!
tagged with: matplotlib

http://stackoverflow.com/comment/125882557
comment on: http://stackoverflow.com/a/49184051
score: 0
type: Comment
type: AnswerComment
has text: `signs = (a3[..., 0] > 0x80) * 0xFF` I think prematurely converts to int32.

http://stackoverflow.com/comment/85291647
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49142946
type: Comment
has text: thanks, this does work. However, in my data set -999999.000 occurs 10 times so I need a solution that will address beyond `index[0]`

http://stackoverflow.com/q/49204669
type: Question
tagged with: while-loop
accepted answer: http://stackoverflow.com/a/49204699
tagged with: python
has body: I'm trying to go through an array from any position l to the end, but once it reaches the last position instead of leaving the while cycle it shows me an error "list index out of range" while l &lt;= len(ordenado): ñ = ordenado[l] contador2 = contador2+ñ l = l+1 I've seen many answers about this theme but I haven't been able to apply it to my problem, also any help will be really appreciated.
has comment: http://stackoverflow.com/comment/85414656
type: AnsweredQuestion
tagged with: list
answer count: 2
has title: Python list index out of range python on an array
score: 1
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/49204699
upvote count: 1
possible better answer: http://stackoverflow.com/a/49204682
has comment: http://stackoverflow.com/comment/85415705
favorite count: 0
has answer: http://stackoverflow.com/a/49204682

http://stackoverflow.com/comment/85320139
type: Comment
type: QuestionComment
has text: `distance_index[0][0]`?
comment on: http://stackoverflow.com/q/49157647
score: 2

http://stackoverflow.com/q/49257981
tagged with: odoo
has answer: http://stackoverflow.com/a/49284451
answer count: 1
has title: Odoo8 website transfer input value from product page to cart page
tagged with: http://stackoverflow.com/tag/xml
type: Question
tagged with: javascript
tagged with: python
has body: I'm working on project in odoov8. I need to add a field on the product page and then create an order which includes this field. To be more specific, I have added Start Date field on the product page, I can select a date on it, but when I hit "Add to Cart" and I go to Cart page, product don't have the date I have selected. I need similar functionality that quantity field has. Here is the code I used to display the Date field on product page: Rent Start Date And here is how it looks: Also, I'm interested in a way to initialize this field with current date. Any help is appreciated. Thank you!
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49284451

http://stackoverflow.com/q/49261007
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/89975347
tagged with: tensorflow
type: Question
score: 0
has title: Tensorflow Object Detection Api Instance Segmentation takes up entire RAM (32 GB)
has comment: http://stackoverflow.com/comment/89629286
has body: I'm trying to train instance segmentation model using Tensorflow Object Detection API (Mask RCNN) and have followed the instructions here. I'm using a pretrained mask_rcnn_resnet50_atrous_coco to initialize weights and adapted this sample config file for the said model. I've created my tfrecord files with masks for training and evaluation sets as per create_coco_tf_record.py. I'm able to run the training script successfully but the problem is, apart from GPU memory, it takes up around 45GB of my RAM. Apart from this everything runs fine and I'm able to finish training upto 10k steps after which it decides it needs more RAM and takes up around 60GB which crashes my system. Same thing happens when I run the evaluation script after training. Following are my system specs: Ubuntu 16.04 Tensorflow 1.5.0 (installed via pip as per the docs) Python 2.7.12 CUDA 9 and CuDnn 7 Gtx 1080 (8 GB) 32 GB RAM with 32 GB Swap I'm not sure why tensorflow needs so much RAM when I'm running the model on GPU. I have only 1 foreground class and around 500 training samples with up to 50 objects/masks per image. Following are some screenshots from System Monitor and nvidia-smi and my pipeline_config file. I'll also upload my script to create tfrecord files if required. Here's my pipeline_config: # Mask R-CNN with Resnet-50 (v1), Atrous version # Configured for MSCOCO Dataset. # Users should configure the fine_tune_checkpoint field in the train config as # well as the label_map_path and input_path fields in the train_input_reader and # eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that # should be configured. model { faster_rcnn { num_classes: 1 image_resizer { keep_aspect_ratio_resizer { min_dimension: 300 max_dimension: 400 } } number_of_stages: 3 feature_extractor { type: 'faster_rcnn_resnet50' first_stage_features_stride: 8 } first_stage_anchor_generator { grid_anchor_generator { scales: [0.25, 0.5, 1.0, 2.0] aspect_ratios: [0.5, 1.0, 2.0] height_stride: 8 width…
has comment: http://stackoverflow.com/comment/89685517
tagged with: python
has comment: http://stackoverflow.com/comment/89689256
has comment: http://stackoverflow.com/comment/89991795
tagged with: object-detection-api
answer count: 0

http://stackoverflow.com/comment/85474407
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49235486
has text: Or `djangorest.settings.dev`, if the settings files are in a settings directory.

http://stackoverflow.com/comment/93300627
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49148565
type: QuestionComment
has text: @TheyDontHaveIT `pyenv activate` does that ...

http://stackoverflow.com/comment/85426766
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49211228
has text: Amend your question to include some example data and expected output on that data.
score: 1

http://stackoverflow.com/comment/85270245
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49132461
has text: When I do `Execute in terminal`, the terminal open and close immediately., without message on it. Do I have to add the line `#!/usr/bin/env python3`in all the python files call by my main script ?

http://stackoverflow.com/q/49218457
possible better answer: http://stackoverflow.com/a/70923294
tagged with: matplotlib
tagged with: python
has title: How do you suppress matplotlib output in for loop in Jupyter Notebook?
has comment: http://stackoverflow.com/comment/85442151
has body: I am looping over a list of DataFrame column names to create barplots using matplotlib.pyplot in a Jupyter Notebook. Each iteration, I'm using the columns to group the bars. Like so: %matplotlib inline import pandas as pd from matplotlib import pyplot as plt # Run all output interactively from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" df = pd.DataFrame({'col1': ['A', 'B', 'C'], 'col2': ['X', 'Y', 'Z'], 'col3': [10, 20, 30]}) #This DOES NOT suppress output cols_to_plot = ['col1', 'col2'] for col in cols_to_plot: fig, ax = plt.subplots() ax.bar(df[col], df['col3']) plt.show(); The semicolon (';') should suppress text output but when I run the code I get, after the 1st run: If I run a similar snippet outside of a for loop, it works as expected - the following successfully suppresses output: # This DOES suppress output fig, ax = plt.subplots() ax.bar(df['col1'], df['col3']) plt.show(); How do I suppress this text output when looping? Note: In a previous version of this question, I used the following code to which some of the comments refer, yet I changed it to the above to better show the issue. cols_to_boxplot = ['country', 'province'] for col in cols_to_boxplot: fig, ax = plt.subplots(figsize = (15, 10)) sns.boxplot(y=wine['log_price'], x=wine[col]) labels = ax.get_xticklabels() ax.set_xticklabels(labels, rotation=90); ax.set_title('log_price vs {0}'.format(col)) plt.show();
tagged with: jupyter-notebook
type: Question
upvote count: 4
has answer: http://stackoverflow.com/a/77543010
answer count: 3
has comment: http://stackoverflow.com/comment/85445619
accepted answer: http://stackoverflow.com/a/49220465
has answer: http://stackoverflow.com/a/70923294
has comment: http://stackoverflow.com/comment/85441649
downvote count: 0
has answer: http://stackoverflow.com/a/49220465
has comment: http://stackoverflow.com/comment/85442023
has comment: http://stackoverflow.com/comment/85444689
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/85446734
has comment: http://stackoverflow.com/comment/85443360
type: AnsweredQuestion

http://stackoverflow.com/a/49234320
score: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49234274
type: Answer
answers question: http://stackoverflow.com/q/49234274
downvote count: 0
has body: Use unstack by first level: pricemine = pricemine['Close'].unstack(0)
upvote count: 1

http://stackoverflow.com/a/49264085
has body: This often means that imread failed to read an image, which is mentioned in the docs Warning Even if the image path is wrong, it won’t throw any error, but print img will give you None So it might not be your arguments to resize that are wrong, but actually a failure to read the image (maybe a wrong path?) resulting in None being passed as the image. Your path involves using the ../ convention for a parent path, but this might not be resolving to the right directory (depending on the directory from which you invoke the interpreter). For example, look here (second answer) or here for a solution regarding how to properly reference parent paths from a given file, and as noted here about why a naive use of '..' for parent path might not work as expected (because it can be based on the path from which you invoke the interpreter, not relative to the file unless you base it on __file__). If it is getting the right directory, then likely there are corrupted images, non-image files, or other files that are causing imread to return None .. you might want to add a try ... except statement in the loop and print out file paths for the case that causes the error.
has comment: http://stackoverflow.com/comment/85542761
answers question: http://stackoverflow.com/q/49264011
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49264011

http://stackoverflow.com/comment/85550928
has text: What does that mean, "closed"? If you're running this in some environment that pops up a new window and immediately closes that window when the program ends, thus hiding any output… find a different way to run your program.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49273059
type: QuestionComment

http://stackoverflow.com/comment/85387259
has text: `for item in label_dict` iterates over what seems like a dictionary. That means it iterates over that dictionary's keys. Since dictionary are mutable, the cannot be keys of dicts and therefore `item['FEAT_1']` cannot work.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49190879

http://stackoverflow.com/comment/85250815
type: Comment
has text: the explanation is that the value does not represent a printable character
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49122688

http://stackoverflow.com/comment/85445829
has text: cannot simulate your problem. It looks ok when I used my own sample data. How do you run python? via notebook?
comment on: http://stackoverflow.com/q/49220796
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85291573
has text: `second_fraction` must be a string as @rayryeng asked.
comment on: http://stackoverflow.com/q/49143001
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49193250
answers question: http://stackoverflow.com/q/49193096
score: 0
accepted answer of: http://stackoverflow.com/q/49193096
type: AcceptedAnswer
has body: I would suggest to transform your lists into a Dataframe and then use pandas to save as csv. pandas_to_csv
has comment: http://stackoverflow.com/comment/85392149
has comment: http://stackoverflow.com/comment/85677060
has comment: http://stackoverflow.com/comment/85647443
type: Answer

http://stackoverflow.com/comment/85563619
has text: I add this code “ds.dir()”, then it print this dcm file 's attributes,however,these attributes don't contain 'PixelRepresentation',so I wonder whether this image's information is not complete，however i can show it on matlab ,so I am confused
comment on: http://stackoverflow.com/q/49278744
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/88493999
comment on: http://stackoverflow.com/a/50741905
type: AnswerComment
has text: I edited in the code for the the other side. Do you think it might be a problem with choosing the port or the source id?
score: 0
type: Comment

http://stackoverflow.com/comment/85388152
has text: But in general: An other script is always an other process. (with the exception of an other Python script being imported.) You have to use the `Popen()` class directly, not one of the convenience functions in the `subprocess` module.
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49191379

http://stackoverflow.com/q/49263973
answer count: 1
type: Question
has title: Storing the results of non-blocking reading into a list
has answer: http://stackoverflow.com/a/49265092
has comment: http://stackoverflow.com/comment/85533229
tagged with: python
type: AnsweredQuestion
tagged with: python-2.7
linked to: http://stackoverflow.com/q/1720816
score: 0
has comment: http://stackoverflow.com/comment/85532545
accepted answer: http://stackoverflow.com/a/49265092
tagged with: twisted
has body: This is a modification of my previous post. Based on this answer, I use the following for non-blocking read and write method (using Python 2.7): from __future__ import print_function from twisted.internet.task import react from twisted.internet.defer import Deferred from twisted.internet.fdesc import readFromFD, setNonBlocking def getFile(filename): with open(filename) as f: d = Deferred() fd = f.fileno() setNonBlocking(fd) readFromFD(fd, d.callback) return d def main(reactor, filename): d = getFile(filename) return d.addCallback(print) react(main, ['/Users/USER1/Desktop/testfile.txt']) In fact, I want to store the reading results into a list instead of using print in return d.addCallback(print). I tried the following: def main(reactor, filename): d = getFile(filename) X = [] return d.addCallback(X) But it seems it is not correct. How can I store the reading results into a list?

http://stackoverflow.com/a/49271338
answers question: http://stackoverflow.com/q/49269570
score: 1
type: Answer
has body: You need to perform all HTTP requests from a single "session" that remembers cookies from the login: perform s = requests.Session() once, then use s.post instead of requests.post. See https://stackoverflow.com/a/31571805/3407728 for more.
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49138118
has answer: http://stackoverflow.com/a/56791926
has title: Connect to FTP server through http proxy
has answer: http://stackoverflow.com/a/49138315
favorite count: 0
tagged with: urllib
type: Question
tagged with: ftp
tagged with: python-3.x
answer count: 2
tagged with: ftplib
type: UnansweredQuestion
tagged with: python
upvote count: 3
has body: My code belove gives me the error: socket.gaierror: [Errno 11001] getaddrinfo failed when calling the method ftp.connect(). My question is: why can I connect to google.com but when connecting to an ftp server it gives me error? And how I can connect to the ftp server from behind http proxy? import ftplib import urllib.request # ftp settings ftpusername = 'abc' ftppassword = 'xyz' ftp_host = 'host' ftp_port = 1234 proxy_url = 'http://username:password@host:port' proxy_support = urllib.request.ProxyHandler({'http': proxy_url}) opener = urllib.request.build_opener(proxy_support) urllib.request.install_opener(opener) #url works ok f = urllib.request.urlopen('http://www.google.com/') print(f.read(500)) # Connecting to ftp fails with ftplib.FTP() as ftp: ftp.connect(host=ftp_host, ftp_port=port) ftp.login(user=ftpusername, passwd=ftppassword) print(ftp.getwelcome()) print(ftp.nlst()) ftp.close() ftp.quit()
score: 3
downvote count: 0

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

http://stackoverflow.com/q/49214585
tagged with: regex-lookarounds
has answer: http://stackoverflow.com/a/49214708
downvote count: 0
has comment: http://stackoverflow.com/comment/85433916
score: 4
tagged with: negative-lookbehind
has answer: http://stackoverflow.com/a/49214712
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
tagged with: python
possible better answer: http://stackoverflow.com/a/49214712
tagged with: regex
type: Question
upvote count: 4
has body: I have a Pandas dataframe which has a column of string data that consists of two distinct parts separated by forward slash. I want to extract text patterns from the 'right hand side' of the string but not if a particular string pattern is present. The following trivial example illustrates the issue. import numpy as np import pandas as pd import re myDF = pd.DataFrame({'pet':['rabbit','mammal/rabbit','mammal/small fluffy rabbit','mammal/lop-eared rabbit','mammal/many rabbits','mammal/jack rabbit']}) So, the dataframe looks like: pet 0 rabbit 1 mammal/rabbit 2 mammal/small fluffy rabbit 3 mammal/lop-eared rabbit 4 mammal/many rabbits 5 mammal/jack rabbit I want to be able to extract rabbit-related terms but only if they occur to the right-hand side of a / separator and not if rabbit is preceded by jack (with or without an intervening space). The regex I've come up with is: rxStr = '(?P&lt;bunny&gt;(?&lt;=/)(?&lt;!jack)(?:.*rabbits?))' ...which I hoped would require any matches to be preceded by / but not if preceded by jack. However, it does not work as I had hoped. I've tried lots of variations without any luck. rxStr = '(?P&lt;bunny&gt;(?&lt;=/)(?&lt;!jack)(?:.*rabbits?))' rx = re.compile(rxStr,flags=re.I|re.X) rabbitDF = myDF['pet'].str.extract(rx,expand=True) myDF = myDF.join(rabbitDF) print(myDF) pet bunny 0 rabbit NaN 1 mammal/rabbit rabbit 2 mammal/small fluffy rabbit small fluffy rabbit 3 mammal/lop-eared rabbit lop-eared rabbit 4 mammal/many rabbits many rabbits 5 mammal/jack rabbit jack rabbit In row 0, the regex correctly fails to find a match because there is no / character. However, in row 5 jack rabbit is matched despite jack preceding rabbit. How can I write a regular expression that would identify rabbit terms but only if preceded by / and not if preceded by jack? Any explanation of why the regex given above fails would also be very much appreciated.
accepted answer: http://stackoverflow.com/a/49214708
answer count: 2
has title: Tied up in knots with lookbehind and negative lookbehind assertions in regular expressions in Python

http://stackoverflow.com/a/49209325
type: Answer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49209139
has comment: http://stackoverflow.com/comment/85423144
score: 1
has body: It looks like you're having trouble because you pass pygame.RESIZABLE as the third argument (the depth) to pygame.display.set_mode whereas you should combine it with the pygame.FULLSCREEN flag with a bitwise OR. screen = pygame.display.set_mode((1360,768), pygame.FULLSCREEN|pygame.RESIZABLE)

http://stackoverflow.com/q/49174457
score: 1
downvote count: 0
upvote count: 1
favorite count: 0
tagged with: unit-testing
type: Question
has body: I'm using Python 2.7 and boto3 to interact with S3 buckets. So far so good! What I'm trying to achieve now is an unit test for the delete bucket operation, but using mocked data, i.e., with no real interaction with the S3 storage. For other unit tests throughout the project, I've used patches and boto3's Stubber successfully, but for some reason, I'm unable to find a way to use the same techniques to mock interactions using the S3 resource and the Bucket sub-resource. This is the snippet of code I want to unit test: def delete_bucket(self, bucket_name): resource = boto3.resource('s3') bucket = resource.Bucket(bucket_name) bucket.objects.all().delete() return bucket.delete() Thanks!
tagged with: mocking
type: UnansweredQuestion
has title: How to mock an unit test for a delete bucket operation using boto3
tagged with: python
tagged with: boto3
has answer: http://stackoverflow.com/a/78043432
has answer: http://stackoverflow.com/a/49177678
tagged with: python-2.7
answer count: 2

http://stackoverflow.com/q/49258265
tagged with: python
tagged with: django-forms
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49419105
score: 1
has answer: http://stackoverflow.com/a/49419105
answer count: 1
downvote count: 0
tagged with: django
upvote count: 1
favorite count: 0
type: Question
has title: Insert new section into Django Admin UserChangeForm
has body: I am adding a section to the end of UserChangeForm using this code. from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from apps.auth_app.models import UserProfile class ProfileInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'Profile' class ProfileAdmin(UserAdmin): inlines = [ ProfileInline, ] admin.site.unregister(User) admin.site.register(User, ProfileAdmin) I would rather insert that section of code after "Personal info", but have been unable to find a way to do this with just the fieldset. I have found examples like this, but is there a way to do this without having to subclass all of the Django Admin User Form? class UserAdmin(auth_admin.UserAdmin): fieldsets = ( (None, {'fields': ('email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name')}), ('&lt;&lt;Custom Fields&gt;&gt;', {'fields': (&lt;&lt;Field Names&gt;&gt;)}), ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), ('Important dates', {'fields': ('last_login', 'date_joined')}), ) ... form = UserChangeForm

http://stackoverflow.com/a/49264036
answers question: http://stackoverflow.com/q/49263508
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85531537
has comment: http://stackoverflow.com/comment/85531853
type: Answer
has body: Edit: What I say below is not completely true as Rahul pointed out. The problem arises since the text that is skipped included a semicolon. Therefore my switching of semicolon to a coma fixes this issue since there are no commas in the skipped text. Old text: This is an issue with ; as a separator. Why I'm not sure but if you switch the text files ';' to ',' then the program runs fine. In the past I've had this work by changing the what engine pandas uses to read the file if you need it use semi colons. The file I used is called values.txt $('table').each(function(index) { $(this).find('tr').each(function() { $(this).find('td:first-child').each(function(i) { var a; var b; var c; $(this).find('a:first').each(function(i) { a = $(this).text(); }); $(this).find('p:first').each(function(i) { b = ($(this).text()); }); $(this).find('time:first').each(function(i) { c = $(this).text(); }); console.log(a + ";" + b + ";" + c); }); }); }); XA452:01 Description in Column 1,ID Column1,13.03.2018 AY102:22 Description in Column 2,ID Column2,13.03.2018 BC001:31 Description in Column 3,ID Column3,13.03.2018 DE223:34 Description in Column 4,ID Column4,13.03.2018 FG315:56 Description in Column 5,ID Column5,13.03.2018 HA212:34 Description in Column 6,ID Column6,13.03.2018 EE111:12 Description in Column 7,ID Column7,13.03.2018 Then ran it with: &gt;&gt;&gt; data = pd.read_csv('values.txt', sep=',', skiprows=19, names=['1', '2', '3']) &gt;&gt;&gt; data 1 2 3 0 XA452:01 Description in Column 1 ID Column1 13.03.2018 1 AY102:22 Description in Column 2 ID Column2 13.03.2018 2 BC001:31 Description in Column 3 ID Column3 13.03.2018 3 DE223:34 Description in Column 4 ID Column4 13.03.2018 4 FG315:56 Description in Column 5 ID Column5 13.03.2018 5 HA212:34 Description in Column 6 ID Column6 13.03.2018 6 EE111:12 Description in Column 7 ID Column7 13.03.2018
has comment: http://stackoverflow.com/comment/85531650

http://stackoverflow.com/comment/85422564
has text: Oh with the mouse wheel right. I didn't know you could scroll horizontally with the mouse wheel anyway Lol. Interesting. I'll look into some more, but it's not that high up on my priority list. Thanks for the info though.
comment on: http://stackoverflow.com/a/49208666
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85433364
has text: Thank you Mick! But the thing is that I am parsing this from the argument line and the line is coming as a single string unless we add double quotes at beginning and end of the entire line. But had given a good work around for it.
comment on: http://stackoverflow.com/a/49214326
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85475858
comment on: http://stackoverflow.com/q/49234144
type: Comment
score: 1
has text: the sizes are approx areas -- see https://stackoverflow.com/q/14827650. (The networkx draw functions use matplotlib)
type: QuestionComment

http://stackoverflow.com/a/49186630
type: Answer
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49184654
has body: The table is not available in the page source. It is loaded dynamically with an AJAX request. If you look in the Network tab under the Developer tools, the AJAX request is being made to this url - http://www.worldlifeexpectancy.com/j/country-cause?cause=95&amp;order=hight. You can see that the data is available in a JSON format. You can scrape this data using only the requests module with the help of the built-in .json() function. You can get all the data, like, rank, country and rate from this JSON data. import requests r = requests.get('http://www.worldlifeexpectancy.com/j/country-cause?cause=95&amp;order=hight') data = r.json() for row in data['chart']['countries']['countryitem']: id_ = row['id'] country = row['name'] rank = row['rank'] value = row['value'] print(rank, id_, country, value) Partial Output: 1 FI Finland 53.77 2 US United States 45.58 3 CA Canada 35.50 4 IS Iceland 34.08 5 SE Sweden 32.41 6 CH Switzerland 32.25 ... ... Also, keep in mind that the &lt;tbody&gt; element is never available in the page source. The browser inserts it. So, while scraping a table, don't use tbody in a find() function. See Why do browsers insert tbody element into table elements?.
answers question: http://stackoverflow.com/q/49184654

http://stackoverflow.com/q/49216865
downvote count: 0
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49217228
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49217276
has comment: http://stackoverflow.com/comment/85437935
answer count: 3
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/49217276
tagged with: group-by
tagged with: dataframe
score: 1
possible better answer: http://stackoverflow.com/a/49217229
has body: I have pandas dataframe something like: my_df = chr PI 2 5 2 5 2 5 2 6 2 6 2 8 2 8 2 8 2 8 2 8 3 5 3 5 3 5 3 5 3 9 3 9 3 9 3 9 3 9 3 9 3 9 3 7 3 7 3 4 ...... ...... I want to convert it into new dataframe that contains new information on the dataframe, something like: chr: unique chromosomes unq_PI : number of unique PIs within each chromosome PIs : list of "PI" values in that chromosome PI_freq: length of each "PI" in the respective chromosome So, expected output would be: chr unq_PI PIs PI_freq 2 3 5,6,8 3,2,5 3 4 5,9,7,4 4,7,2,1 I was thinking something like: new_df = pd.DataFrame({'chr': my_df['chr'].unique(), 'unq_PI': my_df('chr')['unq_PI'].nunique()), 'PIs': ......................., 'PI_freq': ..................}) The only code that works is for `chr` when used alone; any additional code just throws an error. How can I fix this?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49217229
has comment: http://stackoverflow.com/comment/85439319
has title: Aggregate values with corresponding counts in pandas

http://stackoverflow.com/a/49181010
type: Answer
accepted answer of: http://stackoverflow.com/q/49180936
upvote count: 2
type: AcceptedAnswer
has body: For example , You have tradf with column ['A_1','A_2'] With your new df you have column['A'] but only have one category 1 , you can do pd.get_dummies(df).reindex(columns=tradf.columns,fill_value=0)
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49180936

http://stackoverflow.com/q/49148607
tagged with: drag-and-drop
type: Question
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49151725
has comment: http://stackoverflow.com/comment/85302743
score: 0
has body: I want to put jpg in dropzone from other window. Can I do that? In my test I open new window (my html with jpg) and I want to drag and drop it to dropzone on my main window. I have error: Message: stale element reference: element is not attached to the page document. Maybe there is another solution for placing this file eg from a disk? I've tried several ways, including loading from a file from the disk and sending it using send keys.
tagged with: selenium
has comment: http://stackoverflow.com/comment/85303171
has title: Can i use drag and drop from other window? Python Selenium
tagged with: webdriver
answer count: 1

http://stackoverflow.com/comment/86121806
comment on: http://stackoverflow.com/a/49432228
has text: No problem! Meanwhile, u can use the same function to upload (.py) file and then to import it to your colab notebook.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85412207
type: AnswerComment
score: 0
has text: what directories am I looking in?
type: Comment
comment on: http://stackoverflow.com/a/49203152

http://stackoverflow.com/a/49209051
type: Answer
has body: Since you are accessing localhost:8000, the search path is empty string '' and in your project urls, there are only two pattern for polls and admin. That's why you are getting the error. So you need to access localhost:8000/polls to get the result from index view of polls app.
answers question: http://stackoverflow.com/q/49206835
score: 0

http://stackoverflow.com/comment/85486710
comment on: http://stackoverflow.com/q/49241077
score: 2
type: Comment
type: QuestionComment
has text: That is because you call `line.split()` with the default argument, which splits on whitespace. If you want to split on comma, you need to call `line.split(",")`. Can you edit your question to include the example input and the output? Try to create an [mcve] so others can reproduce your issue.

http://stackoverflow.com/comment/85546129
score: 0
comment on: http://stackoverflow.com/q/49257427
type: Comment
type: QuestionComment
has text: I have try numerous thing by removing each line. I found out the only thing I found is during the if path, it will fail. Timeout? Which of the timeout you refer to?`@app.cache.cached(timeout=60) ` definitely not affected the result as without it, it will still fail

http://stackoverflow.com/q/49213392
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49225489
answer count: 1
tagged with: testing
score: 0
tagged with: pytest
has title: How to repeat a test with pytest after every other test?
tagged with: python
has body: I have few test cases as described below. But i want to repeat test1() after every other test case. how can i achieve this? @pytest.mark.test1() @pytest.mark.parametrize(a,b,c) def test_test1(): ...... ...... @pytest.mark.test2() def test_test2(): ...... ...... @pytest.mark.test3() def test_test3(): ...... ...... run test1() again

http://stackoverflow.com/comment/85252436
has text: The `and` and `or` operators do not return `boolean` objects, they return either of their arguments (which could be anything)
comment on: http://stackoverflow.com/q/49123594
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49188049
accepted answer: http://stackoverflow.com/a/49188088
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
has title: conditions work separately but not together in filtering dataframe rows [ValueError: The truth value of a Series is ambiguous]
answer count: 1
favorite count: 0
type: Question
has body: Again I am trying to single out certain rows under the time condition to compute the mean/std of separate time periods. file = pd.read_csv('test/Res/1002', sep='\t', encoding = 'utf-8') print(file['hm']==47) print(file['hm']==48) print(1&lt;=file['hm']&lt;=14) I get the correctly evaluated True/False list of booleans. But in the following, instead receive this -> ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). overn_std = file[(file['hm'] == 47)| (file['hm'] == 48) | (1 &lt;= file['hm'] &lt;= 14) ] In the past I resolved the same issue by replacing condition or with |. dtype of column hm is int.
has answer: http://stackoverflow.com/a/49188088
tagged with: conditional-statements
tagged with: filter
tagged with: pandas
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/85486460
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49240364
type: QuestionComment
has text: Yes of course. As I said, make author a field on Post, make AuthorView use Author as its model, and in the template iterate though `author.post_set.all`.

http://stackoverflow.com/comment/117204881
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/66294885
score: 4
has text: The answer is identical to the already accepted one: https://stackoverflow.com/a/49189522/5537876

http://stackoverflow.com/comment/85449164
score: 0
type: AnswerComment
has text: Thanks, but that wasn't the problem for me
comment on: http://stackoverflow.com/a/49222840
type: Comment

http://stackoverflow.com/a/49248523
type: Answer
has comment: http://stackoverflow.com/comment/85501041
accepted answer of: http://stackoverflow.com/q/49248076
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49248076
has body: At first you have to specify parameters for function2: I guess you want to define function2 in this way: def function2(a): if a == 'jump': print('good boy') else: print('bad boy') And you may want funtion2 output 'good boy', In this way, you could try: function2(function1(*main())) Which will give the output as you want.
score: 0

http://stackoverflow.com/q/49161977
type: UnansweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49162027
has body: This is my question: I have to write a function that accepts 2 integer values as parameters and returns the sum of all the integers between the two values, including the first and last values. The parameters may be in any order (i.e. the second parameter may be smaller than the first). This is the example of the result: This is what I've tried: def sum_range(int1,int2): count = 0 for i in range(int1,int2+1): count = count + i return count but for this example: result = sum_range(3, 2) print(result) I got the wrong result, can anyone help?
score: 2
has answer: http://stackoverflow.com/a/49162028
has answer: http://stackoverflow.com/a/49162009
has title: How to loop a range with python
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/49163394
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/a/49229717
has body: Use one of the many compression formats supported by pandas read_csv/to_csv methods: df.to_csv('file.csv', compression='gzip') This saves your data as a compressed CSV, which occupies considerably less space (~60%+ compression is possible based on my experience). When loading, you'll need the equivalent; df = pd.read_csv('file.csv', compression='gzip') Other supported formats are bz2 and xz.
downvote count: 0
has comment: http://stackoverflow.com/comment/85463413
score: 1
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/85463389
answers question: http://stackoverflow.com/q/49229643

http://stackoverflow.com/a/49232142
has body: Strings can be divided up through slice notation. a='101010101010' &gt;&gt;&gt;a[0] '1' &gt;&gt;&gt;a[0:5] '10101' &gt;&gt;&gt;a[0:int(len(a)/2)] '101010' That's something you should read up on, if you're getting into Python.
score: 0
answers question: http://stackoverflow.com/q/49231584
type: Answer

http://stackoverflow.com/q/49206399
favorite count: 0
type: Question
score: 2
upvote count: 2
tagged with: nltk
type: UnansweredQuestion
downvote count: 0
tagged with: python
has title: nltk part of speech multiple verbs
answer count: 0
has body: I have an nltk application that requires parts of speech (pos) tagging, with the principal goal of identify verbs. Sentences that contain a comma separated sequence of verbs are common in the application. For example: I run, swim, and skate in the park. Consider the following code: import nltk nltk.pos_tag(nltk.tokenize.word_tokenize('I run, swim, and skate in the park')) which incorrectly tags skate and swim as nouns: [('I', 'PRP'), ('run', 'VBP'), (',', ','), ('swim', 'NN'), (',', ','), ('and', 'CC'), ('skate', 'NN'),('in', 'IN'), ('the', 'DT'), ('park', 'NN')] When in a sentence with each verb on its own, the verb is correctly tagged. For example: nltk.pos_tag(nltk.tokenize.word_tokenize('I swim in the park')) produces: [('I', 'PRP'), ('swim', 'VBP'), ('in', 'IN'), ('the', 'DT'), ('park', 'NN')] and nltk.pos_tag(nltk.tokenize.word_tokenize('I skate in the park')) produces [('I', 'PRP'), ('skate', 'VBP'), ('in', 'IN'), ('the', 'DT'), ('park', 'NN')] What is involved in tagging "I run, swim, and skate in the park", such that run, swim, and skate are all recognized as verbs? Thanks in advance! Brian

http://stackoverflow.com/comment/85435512
has text: Nice find. Thanks!. Would you you mind telling me how you came to find that URL? Don't think I would have ever worked that out
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49215100
type: Comment

http://stackoverflow.com/a/49212722
downvote count: 0
has comment: http://stackoverflow.com/comment/85430150
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85430062
accepted answer of: http://stackoverflow.com/q/49212526
has body: Your guesser solves a regression problem, not classification (this question explains the difference). Try this: classifier = tf.estimator.DNNRegressor( feature_columns=my_feature_columns, hidden_units=[10,10], )
has comment: http://stackoverflow.com/comment/85430115
type: Answer
answers question: http://stackoverflow.com/q/49212526
has comment: http://stackoverflow.com/comment/85429962

http://stackoverflow.com/q/49177801
tagged with: jupyter-notebook
type: Question
answer count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49177946
has title: I am getting a file not found error when trying to read a csv file using pandas. I am sure I have used the correct path to the file
tagged with: data-science
has body: I am trying to read a CSV file using pandas read_csv function but I keep getting a file not found error. Here is the code I used and although I said I am sure I have used the correct path I could still be wrong, please point errors out to me if that is the case. Please note I am using Jupyter Notebook as part of Anaconda. import pandas as pd melbourne_file_path = 'Downloads\melb_data.csv' melbourne_data = pd.read_csv(melbourne_file_path) print(melbourne_data.describe()) The error I get is FileNotFoundError Traceback (most recent call last) &lt;ipython-input-3-f31a03883307&gt; in &lt;module&gt;() 2 3 melbourne_file_path = 'Downloads\melb_data.csv' ----&gt; 4 melbourne_data = pd.read_csv(melbourne_file_path) 5 print(melbourne_data.describe()) ~\Anaconda3\lib\site-packages\pandas\io\parsers.py in parser_f(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, dayfirst, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, escapechar, comment, encoding, dialect, tupleize_cols, error_bad_lines, warn_bad_lines, skipfooter, skip_footer, doublequote, delim_whitespace, as_recarray, compact_ints, use_unsigned, low_memory, buffer_lines, memory_map, float_precision) 707 skip_blank_lines=skip_blank_lines) 708 --&gt; 709 return _read(filepath_or_buffer, kwds) 710 711 parser_f.__name__ = name ~\Anaconda3\lib\site-packages\pandas\io\parsers.py in _read(filepath_or_buffer, kwds) 447 448 # Create the parser. --&gt; 449 parser = TextFileReader(filepath_or_buffer, **kwds) 450 451 if chunksize or iterator: ~\Anaconda3\lib\site-packages\pandas\io\parsers.py in __init__(self, f, engine, **kwds) 816 self.options['has_index_names'] = kwds['has_index_names'] 817 --&gt; 818 self._make_engine(…
has answer: http://stackoverflow.com/a/49177905
score: 0
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python

http://stackoverflow.com/a/49155037
has body: Part of the problem is that you are attaching to the session as soon as you create it (which requires a terminal; perhaps that is why you are trying to run bash rather than tmux directly). You should be able to simply start the session with the -d option to avoid attaching to it. def __init__(self, session_name, param): self.name = session_name self.p = subprocess.Popen(['tmux', 'new', '-d', '-s', session_name]) You should also use subprocess for the other methods instead of os.system.
answers question: http://stackoverflow.com/q/49123717
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85316931
score: 2

http://stackoverflow.com/q/49218316
has answer: http://stackoverflow.com/a/62642515
downvote count: 0
tagged with: pulp
has comment: http://stackoverflow.com/comment/85447718
favorite count: 0
has comment: http://stackoverflow.com/comment/85440701
has title: Transport optimization (PuLP)
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/85449195
tagged with: arrays
has body: In the transport optimization problem of PuLP: from pulp import * Warehouses = ["A","B"] # Creates a dictionary for the number of units of supply for each supply node supply = {"A": 1000, "B": 4000} # Creates a list of all demand nodes Bars = ["1", "2", "3", "4", "5"] # Creates a dictionary for the number of units of demand for each demand node demand = {"1": 500, "2": 900, "3": 1800, "4": 200, "5": 700} # Creates a list of costs of each transportation path costs = [ #Bars #1 2 3 4 5 [2,4,5,2,1],#A Warehouses [3,1,3,2,3] #B ] # Creates the prob variable to contain the problem data prob = LpProblem("Beer Distribution Problem",LpMinimize) # Creates a list of tuples containing all the possible routes for transport Routes = [(w,b) for w in Warehouses for b in Bars] # A dictionary called route_vars is created to contain the referenced variables (the routes) route_vars = LpVariable.dicts("Route",(Warehouses,Bars),0,None,LpInteger) While running, the following code: # The objective function is added to prob first prob += lpSum([route_vars[w][b]*costs[w][b] for (w,b) in Routes]), "Sum of Transporting Costs" I get the following error: TypeError: list indices must be integers, not str
has answer: http://stackoverflow.com/a/49224994
tagged with: python
has comment: http://stackoverflow.com/comment/85448157
has comment: http://stackoverflow.com/comment/85447708
has comment: http://stackoverflow.com/comment/85442557
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/62642515
answer count: 2
tagged with: mathematical-optimization
accepted answer: http://stackoverflow.com/a/49224994
score: 2

http://stackoverflow.com/comment/85492439
type: Comment
comment on: http://stackoverflow.com/a/49243866
score: 0
type: AnswerComment
has text: I'm still learning python and have not yet covered try/except. But already I see so many options for it. Thank you for showing me something new!!

list-comprehension
tags question: http://stackoverflow.com/q/49265404
type: Tag
tags question: http://stackoverflow.com/q/49124574
tags question: http://stackoverflow.com/q/49275927
tags question: http://stackoverflow.com/q/49203044
tags question: http://stackoverflow.com/q/49248003
tags question: http://stackoverflow.com/q/49276183
tags question: http://stackoverflow.com/q/49220538
tags question: http://stackoverflow.com/q/49192189
tags question: http://stackoverflow.com/q/49263464
tags question: http://stackoverflow.com/q/49128622
tags question: http://stackoverflow.com/q/49141671
tags question: http://stackoverflow.com/q/49259659
tags question: http://stackoverflow.com/q/49202497
tags question: http://stackoverflow.com/q/49278692
tags question: http://stackoverflow.com/q/49189529
tag name: list-comprehension
tags question: http://stackoverflow.com/q/49205082
tags question: http://stackoverflow.com/q/49230426
tags question: http://stackoverflow.com/q/49121764

http://stackoverflow.com/comment/85424672
has text: Thanks @jonrsharpe, but it seems like the documentation points out how to mock the actual context manager call. The problem I have is that I am concerned with method calls that happen *within* the context manager. It could very well be my limited understanding of them, but I can't figure out how to descend in scope to get to the method called inside of them.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49209712

combinations
tags question: http://stackoverflow.com/q/49224066
tags question: http://stackoverflow.com/q/49183510
type: Tag
tag name: combinations

http://stackoverflow.com/q/49122455
accepted answer: http://stackoverflow.com/a/49142254
has body: How can I set the number of CPUs to use in MXNET Gluon to a certain number, say 12? I don't see the answer in the documentation anywhere and by default MXNET uses all the CPUs.
tagged with: mxnet
tagged with: python
type: AnsweredQuestion
tagged with: gluon
score: 0
has comment: http://stackoverflow.com/comment/85250377
upvote count: 1
answer count: 1
has title: Limit number of CPUs using MXNET
downvote count: 1
has answer: http://stackoverflow.com/a/49142254
favorite count: 0
linked to: http://stackoverflow.com/q/44558127
type: Question

http://stackoverflow.com/comment/85331620
score: 1
comment on: http://stackoverflow.com/a/49162844
has text: That will definitely give the same dictionary but I am not familiar with the source code of locals method and the returned dictionary may or may not be safe for editing outside the method. So I added the dict() to be on the safer side.
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85307549
type: QuestionComment
comment on: http://stackoverflow.com/q/49140513
has text: With the other problems this brings up apart, stashing the keywords on the class itself would be the correct way to do it. The copying function could simply use no keywords if the stashing attribute were not found, with no problems.
score: 0
type: Comment

powerset
tags question: http://stackoverflow.com/q/49160456
tag name: powerset
type: Tag

http://stackoverflow.com/q/49125359
linked to: http://stackoverflow.com/q/4688599
favorite count: 0
type: Question
upvote count: 4
has comment: http://stackoverflow.com/comment/85258828
has comment: http://stackoverflow.com/comment/85256525
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85255782
answer count: 1
tagged with: python
tagged with: flask
has comment: http://stackoverflow.com/comment/85256122
score: 3
has title: (pymysql.err.IntegrityError) (1451, 'Cannot delete or update a parent row: a foreign key constraint fails...') in Flask
has comment: http://stackoverflow.com/comment/85260246
has comment: http://stackoverflow.com/comment/85257232
has comment: http://stackoverflow.com/comment/85256650
has comment: http://stackoverflow.com/comment/85255527
has body: I'm aware that there are many questions about the error in the title, but I could't find a suitable solution. My problem is that while deleting a row using Session.delete() it's throwing sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1451, 'Cannot delete or update a parent row: a foreign key constraint fails (`transport`.`driver`, CONSTRAINT `driver_ibfk_1` FOREIGN KEY (`owner_id`) REFERENCES `truckcompany` (`id`))') [SQL: 'DELETE FROM truckcompany WHERE truckcompany.id = %(id)s'] [parameters: {'id': 4}] Models: class Truck_company(Base): __tablename__ = 'truckcompany' id = Column(BigInteger, primary_key=True) class Driver(Base): __tablename__ = 'driver' id = Column(BigInteger, primary_key=True) owner_id = Column(BigInteger, ForeignKey('truckcompany.id')) owner = relationship(Truck_company) The view with the failing delete: @app.route('/values/deleteuser/&lt;int:id&gt;', methods=['POST', 'GET']) def delete_truck(id): value_truckcompany = sqlsession.query(Truck_company).filter(Truck_company.id == id).first() if value_truckcompany: sqlsession.delete(value_truckcompany) sqlsession.commit() return redirect('/static/truckcompanyview', )
has comment: http://stackoverflow.com/comment/85255553
downvote count: 1
linked to: http://stackoverflow.com/q/5033547
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/85260372
has comment: http://stackoverflow.com/comment/85256871
has answer: http://stackoverflow.com/a/49128472

http://stackoverflow.com/a/49262945
answers question: http://stackoverflow.com/q/49262558
type: Answer
score: 3
has body: In python every function returns a value. If you do not specify it will return None. If you print the function invocation on that It will print None. def none_func(): pass print(none_func()) None In your code you are substantially doing the same. print(equipment["armour"].block()) Here you are printing the invocation of block() method.
upvote count: 3
downvote count: 0

scipy
tags question: http://stackoverflow.com/q/49254111
tags question: http://stackoverflow.com/q/49151096
tags question: http://stackoverflow.com/q/49189637
tags question: http://stackoverflow.com/q/49214915
tags question: http://stackoverflow.com/q/49207957
tags question: http://stackoverflow.com/q/49265027
tags question: http://stackoverflow.com/q/49230989
tags question: http://stackoverflow.com/q/49207275
tags question: http://stackoverflow.com/q/49191877
tags question: http://stackoverflow.com/q/49151557
tags question: http://stackoverflow.com/q/49162578
tags question: http://stackoverflow.com/q/49172935
tags question: http://stackoverflow.com/q/49126090
tags question: http://stackoverflow.com/q/49134256
tags question: http://stackoverflow.com/q/49130551
tags question: http://stackoverflow.com/q/49151547
tags question: http://stackoverflow.com/q/49134252
tags question: http://stackoverflow.com/q/49182331
tags question: http://stackoverflow.com/q/49185127
tags question: http://stackoverflow.com/q/49156908
tags question: http://stackoverflow.com/q/49168023
type: Tag
tags question: http://stackoverflow.com/q/49266244
tags question: http://stackoverflow.com/q/49211783
tags question: http://stackoverflow.com/q/49141352
tags question: http://stackoverflow.com/q/49264076
tags question: http://stackoverflow.com/q/49155540
tag name: scipy
tags question: http://stackoverflow.com/q/49140965
tags question: http://stackoverflow.com/q/49163125
tags question: http://stackoverflow.com/q/49136617
tags question: http://stackoverflow.com/q/49179155
tags question: http://stackoverflow.com/q/49271293
tags question: http://stackoverflow.com/q/49196195
tags question: http://stackoverflow.com/q/49266014
tags question: http://stackoverflow.com/q/49214620
tags question: http://stackoverflow.com/q/49234682
tags question: http://stackoverflow.com/q/49173681
tags question: http://stackoverflow.com/q/49179463
tags question: http://stackoverflow.com/q/49228896
tags question: http://stackoverflow.com/q/49150255
tags question: http://stackoverflow.com/q/49256917
tags question: http://stackoverflow.com/q/49223219
tags question: http://stackoverflow.com/q/49205948

http://stackoverflow.com/q/49256594
has body: In order to rewrite a basic Flask example with Flask-Restplus, I would like to create a POST with only a plain text body. The below example does what I want, but of course the documentation is not correct as I do not expect a mapping with fields, but rather the value directly. How can I adjust the example, so that the UI Shows that I need a plain text payload (without fields)? from flask import Flask, request, jsonify from flask_restplus import Resource, Api, fields app = Flask(__name__) api = Api(app) all_data = [] @api.route('/data') class Data(Resource): def get(self): return jsonify(all_data) @api.expect(api.model("NewData", {"newdata": fields.String})) def post(self): json = request.json print("Adding", json) all_data.append(json) return "" if __name__ == '__main__': app.run(debug=True, port=8080) It is important that I want my data in the payload and not the URL. And while JSON input with fields might be a more solid solution, I would like to finish this version first. (And if I go for JSON payload (not URL), is there a way to show separate input lines for the fields, such that Flask-Restplus will assemble the JSON?)
tagged with: flask-restplus
answer count: 0
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/92134279
tagged with: flask
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: How to expect a plain text payload in flask-restplus?
upvote count: 6

http://stackoverflow.com/a/60741669
has body: This worked for me: conda env remove --name tensorflow
downvote count: 1
score: 5
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/49127834
has comment: http://stackoverflow.com/comment/108547491

http://stackoverflow.com/a/49262195
accepted answer of: http://stackoverflow.com/q/49262089
has comment: http://stackoverflow.com/comment/85529017
upvote count: 3
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49262089
has body: Something like l=[ None if df1[df1.LabelId==1].empty else df1[df1.LabelId==1] for _, df1 in df.groupby(df.LabelId.eq(0).cumsum())] l Out[402]: [ eventTime velocity LabelId 2 2017-08-1912:53:55.100 4 1 3 2017-08-1912:53:55.150 180 1 4 2017-08-1912:53:55.200 2 1, None, eventTime velocity LabelId 7 2017-08-1912:53:55.100 4 1 8 2017-08-1912:53:55.150 70 1 9 2017-08-1912:53:55.200 2 1, None] New group key detail df.LabelId.eq(0).cumsum() Out[398]: 1 1 2 1 3 1 4 1 5 2 6 3 7 3 8 3 9 3 10 4 Name: LabelId, dtype: int32
downvote count: 0
has comment: http://stackoverflow.com/comment/85528549
has comment: http://stackoverflow.com/comment/85528431
has comment: http://stackoverflow.com/comment/85569738
has comment: http://stackoverflow.com/comment/85528952
has comment: http://stackoverflow.com/comment/85528344
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/85528653

http://stackoverflow.com/q/49227963
linked to: http://stackoverflow.com/q/7129285
has title: how to do i return data from a loop in python
has answer: http://stackoverflow.com/a/49228000
tagged with: list
score: -5
upvote count: 0
has comment: http://stackoverflow.com/comment/85459673
has body: I have a loop as y = [1,2,3,4,5,6,7] for x in y: if x == 3: return(x) elif x == 4: return(x) elif x = 6: return(x) else: return('not found') I don't wanna print data, I just want to return the data and if the data gets returned, is there a way to handle all of such returned data at once a list?
has comment: http://stackoverflow.com/comment/85459424
has comment: http://stackoverflow.com/comment/85459508
has answer: http://stackoverflow.com/a/49228028
favorite count: 0
has comment: http://stackoverflow.com/comment/85459627
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85459408
tagged with: return
has comment: http://stackoverflow.com/comment/85459425
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49228184
has answer: http://stackoverflow.com/a/49228330
downvote count: 5
tagged with: python
answer count: 4

http://stackoverflow.com/comment/85408255
has text: Yes, you are correct. What was happening is that the indexes on `series1` and `series2` are not 0, 1, 2,... But the new `Series` **is** indexed 0, 1, 2,... so that when putting them together, the new series gets reordered.
comment on: http://stackoverflow.com/a/49200908
type: Comment
score: 0
type: AnswerComment

import
tags question: http://stackoverflow.com/q/49121732
type: Tag
tags question: http://stackoverflow.com/q/49136230
tags question: http://stackoverflow.com/q/49266792
tags question: http://stackoverflow.com/q/49214690
tags question: http://stackoverflow.com/q/49179052
tags question: http://stackoverflow.com/q/49129300
tags question: http://stackoverflow.com/q/49192768
tags question: http://stackoverflow.com/q/49142463
tag name: import
tags question: http://stackoverflow.com/q/49171994
tags question: http://stackoverflow.com/q/49139877
tags question: http://stackoverflow.com/q/49219193
tags question: http://stackoverflow.com/q/49162032
tags question: http://stackoverflow.com/q/49221544
tags question: http://stackoverflow.com/q/49235082

http://stackoverflow.com/q/49278425
score: 2
answer count: 0
upvote count: 2
tagged with: boost
downvote count: 0
has comment: http://stackoverflow.com/comment/85584410
has comment: http://stackoverflow.com/comment/85560620
has comment: http://stackoverflow.com/comment/85696692
favorite count: 0
type: Question
tagged with: boost-python
has title: Boost Python Tutorial Linker Errors
has body: I would like to use the Boost.Python Framework. At the Moment i am trying to get the Tutorial done. My Boost Version is 1.66. I have Python 3.4 installed and my operating system is Windows 7. What I have done so far: 1) Downloaded zip File for Windows: http://www.boost.org/users/download/ 2) Unziped it in C:/boost => resulting directory is C:/boost/boost_1_66_0 3) Install Boost.Build (5.2.1 http://www.boost.org/doc/libs/1_66_0/more/getting_started/windows.html) with --prefix=C:\boost\boost_1_66_0\boost_build and the option --with-python 4) Added following user-config.jam File: using msvc : 10.0 ; using python : 3.4 # Version : C:\\Python34\\python.exe # Python Path : C:\\Python34\\include # include path : C:\\Python34\\libs # lib path(s) ; 5) Changed the Jamfile in the Tutorial directory (C:\boost\boost_1_66_0\libs\python\example\tutorial) as follws: # Copyright Stefan Seefeld 2016. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import python ; project tutorial : requirements &lt;include&gt;../../../../ &lt;location&gt;. ; python-extension hello_ext : hello.cpp ; run-test hello : hello_ext hello.py ; alias test : hello ; explicit test ; 6) Now in the folder are Jamefile, hello.cpp, hello.py. 7) Run in command prompt bjam toolset=msvc --verbose-test test C:\boost\boost_1_66_0\libs\python\example\tutorial&gt;bjam toolset=msvc --verbose-test test ...patience... ...found 1029 targets... ...updating 4 targets... msvc.link.dll hello_ext.pyd Fatal error LNK1181: cannot open input file 'boost_python.lib' call "C:\Users\YANNIC~1\AppData\Local\Temp\b2_msvc_10.0_vcvarsall_x86.cm d" &gt;nul link /NOLOGO /INCREMENTAL:NO /DLL /NOENTRY /DEBUG /MACHINE:X86 /MANIFEST/sub system:console /out:"hello_ext.pyd" /IMPLIB:"hello_ext.pdb" /LIBPATH:"C:\Python34\l ibs" @"hello_ext.pyd.rsp" IF %ERRORLEVEL% NEQ 0 EXIT %ERRORLEVEL% ...failed msvc.link.dll hello_ext.pyd hello_ext.pdb... ...ski…
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/85338021
type: QuestionComment
comment on: http://stackoverflow.com/q/49165954
has text: Show the full traceback that leads up to `raise Exception`
type: Comment
score: 1

http://stackoverflow.com/q/49221084
has answer: http://stackoverflow.com/a/49221219
tagged with: python
has body: I've got a few Docker-based projects that all depend on each other: project 1 depends on python:3-alpine project 2 depends on project 1 project 3 depends on project 1 etc. etc. As such, all of my automated builds are linked as above. When I update project 2, projects 3 4 5 are all automatically rebuilt. It's a pretty slick feature. The thing is, this means that whenever a lower-level project is updated, this triggers lots of rebuilds of lots of projects. In the case of something very low-level being updated, like python or node, I can imagine that Docker Hub is triggering a lot of rebuilds. My question then is: doesn't this put a lot of load on package hosts like PyPI? As each of my projects include a line something like: RUN pip install -r requirements.txt This hits PyPI to pull down all of the requirements, re-downloading each time without the ability to use a local cache because the Docker container is "brand new" for each build. Is there something I can do to lessen the impact my projects are making, or is this somehow fixed with "magic" on Docker Hub? In the absence of such magic, is there a Best Practise I should be following?
tagged with: pypi
type: Question
tagged with: dockerhub
has title: Does Docker Hub put a big strain on package hosts?
type: UnansweredQuestion
answer count: 1
upvote count: 1
tagged with: dockerfile
downvote count: 1
favorite count: 0
tagged with: docker
score: 0

http://stackoverflow.com/comment/85358183
type: AnswerComment
has text: Glad to help !!
type: Comment
comment on: http://stackoverflow.com/a/49176398
score: 0

http://stackoverflow.com/q/49212453
favorite count: 0
type: Question
has body: I have wrapped up my django project using pyinstaller and later used Inno Setup to make installer. Since django command prompt running background looks ugly, I use the runhidden flag in Inno Setup. But when I click on desktop icon the application starts running by hiding the command prompt, and when I run it again without closing the previously opened app then the command prompt becomes visible. I want to make command prompt always hidden. For more details have a look on my ISS script: [Run] Filename: "{app}\{#MyAppExeName}"; Description: "Start Crumbs For table"; Flags: waituntilidle postinstall runhidden skipifsilent
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pyinstaller
tagged with: django
tagged with: python
has title: The Inno Setup Runhidden flag is not working, how do I make it work?
answer count: 0
score: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49243612
tagged with: python
score: -1
tagged with: pygame
has title: Invalid syntax on single quotes
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85491020
has answer: http://stackoverflow.com/a/49243659
answer count: 1
downvote count: 1
favorite count: 0
type: Question
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/49243659
has comment: http://stackoverflow.com/comment/85491044
has body: I'm working on a text adventure game and wanted to play a sound when you get a game over. I'm using PyGame to do this but it gives me an invalid syntax error on the last single quote when I try to load the sound file. here is the code: import pygame import time pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.init() snd_dir = path.join(path.dirname (_Dog-Walking-Simulator_) 'Game_Over_Yeah.wav')
upvote count: 0

http://stackoverflow.com/comment/85543968
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49270094
has text: Using `subprocess` didn't work. I actually put the `get_water_pid()` function in the `water.py` file. In the `web_plants.py` file, inside the `auto_water(toggle)` function, I added the following: `pid = water.get_water_pid() os.kill(pid, signal.SIGTERM)` All my imports are correct as in both files I have imported os, signal and subprocess. And in the `web_plants.py`, I have imported `water` which works fine.
type: Comment

http://stackoverflow.com/comment/85580171
type: QuestionComment
has text: It turns out, the issue was with where I called element.clear(). After moving it to the end of get_structure, everything behaved as expected. My biggest frustration in this process was trying to find a definitive list of fields that are supposed to be available at the start event. The best I could find was this message from Fredrik Lundh to the XML-SIG list in 2005: https://mail.python.org/pipermail/xml-sig/2005-January/010838.html
comment on: http://stackoverflow.com/q/49245454
score: 0
type: Comment

http://stackoverflow.com/q/49139542
accepted answer: http://stackoverflow.com/a/49139639
has answer: http://stackoverflow.com/a/49139639
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85284564
type: AnsweredQuestion
has body: Assuming I have a dictionary whose keys are tuples. Is it possible to to iterate over the keys of the dictionary and only return the keys which are have a certain value in the first position of their tuple? For example: my_dict = {('a','a'):'b', ('a','b'):'b', ('b','a'):'a'} def function(given): for (given,x) in my_dict: print((given,x)) function('a') I want the function to print the following: &gt;&gt; ('a','a') &gt;&gt; ('a','b') Is there a way to do this in Python?
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85284492
has answer: http://stackoverflow.com/a/49139555
has comment: http://stackoverflow.com/comment/85284412
has title: Iterating over keys in dictionary, which are tuples
type: Question
tagged with: python-3.x
tagged with: tuples
possible better answer: http://stackoverflow.com/a/49139555

http://stackoverflow.com/comment/85286263
type: Comment
has text: No, I intend to assign 0.1 to 2, as I want to assign inverse_weight solely based on the value of b.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49140441

http://stackoverflow.com/comment/85400860
has text: Do you need it as a fraction like that?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49197937

http://stackoverflow.com/q/49132090
upvote count: 2
answer count: 1
downvote count: 0
favorite count: 0
type: Question
has title: How to trucnate/round to hour a localized datetime column in pandas
tagged with: truncate
tagged with: timezone
type: UnansweredQuestion
tagged with: datetime
has body: I want to truncate/round to hour a localized datetime column in pandas python. For example if I have 2017-10-15 15:03:25+02:00 I would like to obtain 2017-10-15 15:00:00+02:00. Notice that I want to keep the timezone information. The first thing I've tried is: DF['dtColumn'].dt.floor('H') This aparently works truncating to hour and keeping timezone information, the problem comes when the dst day comes, for example on 2017-10-29. Given the following code: dt1 = datetime.datetime(2017,10,29,0,1) dt2 = datetime.datetime(2017,10,29,1,1) df = pd.DataFrame([('whatever', dt1),('whatever',dt2)]) df[1] = df[1].dt.tz_localize('UTC').dt.tz_convert('Europe/Madrid') df[1].dt.floor('H') It produces the given error: Traceback (most recent call last): File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2882, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-90-8319339cf020&gt;", line 5, in &lt;module&gt; df[1].dt.floor('H') File "C:\Python27\lib\site-packages\pandas\core\base.py", line 210, in f return self._delegate_method(name, *args, **kwargs) File "C:\Python27\lib\site-packages\pandas\tseries\common.py", line 132, in _delegate_method result = method(*args, **kwargs) File "C:\Python27\lib\site-packages\pandas\tseries\base.py", line 101, in floor return self._round(freq, np.floor) File "C:\Python27\lib\site-packages\pandas\tseries\base.py", line 93, in _round self._shallow_copy(result, **attribs)) File "C:\Python27\lib\site-packages\pandas\tseries\base.py", line 213, in _ensure_localized result = result.tz_localize(self.tz) File "C:\Python27\lib\site-packages\pandas\util\decorators.py", line 91, in wrapper return func(*args, **kwargs) File "C:\Python27\lib\site-packages\pandas\tseries\index.py", line 1826, in tz_localize errors=errors) File "pandas\tslib.pyx", line 4380, in pandas.tslib.tz_localize_to_utc (pandas\tslib.c:75768) AmbiguousTimeError: Cannot infer dst time from Timestamp('2017-10-29 02:00:00'), try using the…
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/71179613
tagged with: pandas

http://stackoverflow.com/comment/85356415
has text: @flyingdutchman ... See my comment above where you can set *autocommit*.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49157506
score: 0

http://stackoverflow.com/q/49192661
has title: object arrays are not currently supported
favorite count: 0
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/85390854
has body: I'm not sure why I'm getting this error. (I'm using python 3 on canopy) Here is a sample of my code: dat =pd.read_csv('myfile',sep=',') dat=dat.values P=np.ones((240,1)) Y=dat[:,15] for i in range (2,15): X= np.column_stack((P,(dat[:,i]))) Xt = np.transpose(X) p=np.matmul(Xt,X) I originally input my data as a dataframe but changed it to an np array, and when I check all the data types in X they are floats, and X is created okay, however, when I try to use matmul on it returns the error TypeError: object arrays are not currently supported I'm confused as all the elements seem to be floats but it won't multiply. Thanks
tagged with: python
has comment: http://stackoverflow.com/comment/85390983
type: Question
tagged with: numpy
answer count: 0
has comment: http://stackoverflow.com/comment/85391066
upvote count: 1
has comment: http://stackoverflow.com/comment/85391007
has comment: http://stackoverflow.com/comment/85390446
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85390415

http://stackoverflow.com/comment/85531875
has text: A bit of lateral thinking and sure not what you asked, but I'm pretty sure that if you open Task Manager and kill the process, `finally` will not run. Or the same if the computer crashes before :D
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49262379

http://stackoverflow.com/q/49165220
has answer: http://stackoverflow.com/a/50529438
possible better answer: http://stackoverflow.com/a/50529438
tagged with: user-interface
has comment: http://stackoverflow.com/comment/128075498
tagged with: google-colaboratory
favorite count: 0
type: AnsweredQuestion
answer count: 5
has body: Can someone explain or give a notebook example how to use the new Form feature? It looks really exciting, but I cannot find any example or even an announcement anywhere.
has answer: http://stackoverflow.com/a/49665572
accepted answer: http://stackoverflow.com/a/49665572
has answer: http://stackoverflow.com/a/49428774
tagged with: python
tagged with: forms
has answer: http://stackoverflow.com/a/49206221
type: Question
has title: The new Form feature in Google Colaboratory
upvote count: 20
score: 20
downvote count: 0
has answer: http://stackoverflow.com/a/52913464

http://stackoverflow.com/a/49275664
score: 2
has comment: http://stackoverflow.com/comment/85563147
answers question: http://stackoverflow.com/q/49267496
upvote count: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49267496
has body: Unfortunately there is no such stopping functionality in Orange yet. The developers of Orange are working towards making widgets compute in threads, which can let us control stopping. The Test &amp; Learn widget, for example, already works in a separate thread. There, if the user changes options while widget is already working, it stops the current computation and starts a new one. But even there, there is no GUI option to just stop the computation.

http://stackoverflow.com/comment/85428456
score: 0
type: AnswerComment
has text: @jtlz2 I'm using the Visual Studio compiler on Windows. `cl /LD test.c`. `/LD` creates a DLL. If my answer is useful, consider upvoting or accepting :^)
comment on: http://stackoverflow.com/a/49179133
type: Comment

http://stackoverflow.com/a/49157105
score: 1
accepted answer of: http://stackoverflow.com/q/49156969
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49156969
has body: You need to explicitly tell the IE driver to ignore the protected mode settings. from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities caps = DesiredCapabilities.INTERNETEXPLORER caps['ignoreProtectedModeSettings'] = True driver = webdriver.Ie('C:\\workspace\\IEDriverServer.exe', capabilities=caps) driver.get("http://wwww.facebook.com")
type: Answer

http://stackoverflow.com/comment/85274494
type: QuestionComment
has text: The issue is a cross compatibility issue. My command line variable python was using python 2.7 while it should've been using python 3.6. Changing the environmental variable to python 3.6 solved my issue. Thank you
comment on: http://stackoverflow.com/q/49134554
type: Comment
score: 2

http://stackoverflow.com/comment/85342229
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49168456
has text: Yes, in that case it's clear why you're not seeing the output conditional on done status.
score: 0

http://stackoverflow.com/comment/85425720
score: 1
has text: @Jerin no, that is the model save method. OP said this was the form.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49210590

http://stackoverflow.com/comment/85463858
type: Comment
type: QuestionComment
has text: Imho a question about cluster analysis will get better answers on [Cross Validated](https://stats.stackexchange.com/)
comment on: http://stackoverflow.com/q/49228191
score: 0

http://stackoverflow.com/comment/85531456
score: 0
has text: @JermellBeane I'm looking into your issue and try to reproduce. Will give you an update this afternoon. Thanks.
type: Comment
comment on: http://stackoverflow.com/q/49176813
type: QuestionComment

http://stackoverflow.com/q/49133716
has comment: http://stackoverflow.com/comment/85272311
type: Question
has title: Apparent limit to re.findall in Python
upvote count: 3
downvote count: 0
answer count: 1
favorite count: 0
type: AnsweredQuestion
score: 3
tagged with: data-analysis
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/49134718
has comment: http://stackoverflow.com/comment/85294264
has body: I have a file containing data (defining some mathematical objects) in a format which is inconvenient and I would like to convert it to JSON using Python 3. Since the file is huge (it contains 921,497 objects, each needing several lines to be defined), I used the module mmap to load content that I analyse using re.findall. My problem is that I get only the first 99999 entries, and I am wondering where does the limit come from? I don't get any error and I could not find an explanation for this. I have made some small tests to find limits, but the number I obtained are much bigger than 99999: &gt;&gt;&gt; import re &gt;&gt;&gt; len(re.search(r"a{1,9999999}", "a"*(2*10**6)).group()) 2000000 &gt;&gt;&gt; len(re.findall(r"a", "a"*(2*10**6))) 2000000 &gt;&gt;&gt; import sre_constants &gt;&gt;&gt; sre_constants.MAXGROUPS 2147483647 Does anyone have an idea of how to surpass this limit, or of a better approach to collect the data? My code (up to saving the files) is the following: """ Transform dataset for CICY 4-fold to JSON arxiv: 1303.1832 http://www-thphys.physics.ox.ac.uk/projects/CalabiYau/Cicy4folds/index.html """ import os, mmap, json, tarfile, tempfile import regex as re CICY4_REGEX = b"""\ MATRIX NUMBER :\s+(\d+) SIZE :\s+(\d+)\s+(\d+) EULERNUMBER :\s+(\d+) ([\d\s\|]+) """ cicy4_pattern = re.compile(CICY4_REGEX, re.MULTILINE) json_data = {} last_ind = 0 with open('cicy4folds.txt', 'r') as f,\ mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m: for data in cicy4_pattern.findall(m): dic = {"vec": [], "matrix": []} ind = int(data[0]) if ind != last_ind + 1: print(ind) last_ind = ind #dic["id"] = int(data[0]) dic["size"] = (int(data[1]), int(data[2])) dic["euler"] = int(data[3]) for line in data[4].decode("utf-8").split("\n")[:-1]: ind, row = line.split(" | ") dic["vec"].append(int(ind)) dic["matrix"].append(list(map(int, row.split()))) json_data[int(data[0])] = dic print("Size: ", len(json_data)) The file cicy4folds.txt can be found here. Here are two examples of …
has answer: http://stackoverflow.com/a/49134718

http://stackoverflow.com/comment/85318217
score: 0
type: AnswerComment
has text: Thanks, this was a useful answer because it addressed the misunderstandings I had in my question and led to a solution. I will also add to my question the short example that I wrote up based on your answer.
comment on: http://stackoverflow.com/a/49150884
type: Comment

http://stackoverflow.com/comment/85287957
has text: Your code for removing the label will never be executed. There are no actions for removing it in the `btn2_clicked`. As far as I can see the only code that can remove the label is "dead" branch of the `if` statement.
comment on: http://stackoverflow.com/q/49140391
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/87550064
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50252271
has text: yeah it helped a bit
type: AnswerComment

http://stackoverflow.com/comment/85494851
comment on: http://stackoverflow.com/q/49243572
type: Comment
type: QuestionComment
has text: @GAEfan... We are talking about Python not js
score: 0

http://stackoverflow.com/a/49215583
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85435759
accepted answer of: http://stackoverflow.com/q/49215406
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85435448
has comment: http://stackoverflow.com/comment/85435496
answers question: http://stackoverflow.com/q/49215406
has comment: http://stackoverflow.com/comment/85435615
score: 3
has body: You can use re.findall that way: x= re.findall(r'[0-9]+','iama5559348number')[0] print(x) or that: x= re.findall(r'\d+','iama5559348number')[0] print(x)
type: Answer
has comment: http://stackoverflow.com/comment/85435357

http://stackoverflow.com/q/49247241
score: -4
has body: Hello I am trying to learn python from the beginning and I keep running into an issue when importing modules. I am running python 3.6.4 and it was installed via anaconda 4.4.10. Here is an example of my issue: If I go to cmd line and run 'pip install requests' I get 'requirements already satisfied' Yet if I try to run this simple section of code in spyder: import requests from bs4 import BeautifulSoup import operator def: word_list I get an error on the first line right after the from, saying invalid syntax. Any advice would be greatly appreciated! Also Sorry for any violations this is my first post!
has comment: http://stackoverflow.com/comment/85498189
accepted answer: http://stackoverflow.com/a/49247274
favorite count: 0
has title: Unable to import modules into python 3
type: Question
has answer: http://stackoverflow.com/a/49247274
tagged with: anaconda
has answer: http://stackoverflow.com/a/49247259
tagged with: python
has comment: http://stackoverflow.com/comment/85498574
type: AnsweredQuestion
answer count: 2
downvote count: 4
possible better answer: http://stackoverflow.com/a/49247259
upvote count: 0

multidimensional-array
tags question: http://stackoverflow.com/q/49145315
tags question: http://stackoverflow.com/q/49134111
tags question: http://stackoverflow.com/q/49191058
tags question: http://stackoverflow.com/q/49200619
tags question: http://stackoverflow.com/q/49243295
type: Tag
tags question: http://stackoverflow.com/q/49222880
tags question: http://stackoverflow.com/q/49197801
tag name: multidimensional-array
tags question: http://stackoverflow.com/q/49201693

http://stackoverflow.com/q/49221505
has answer: http://stackoverflow.com/a/49221548
has comment: http://stackoverflow.com/comment/85446635
type: AnsweredQuestion
has title: Regular expression issue in python
score: 1
has comment: http://stackoverflow.com/comment/85446525
favorite count: 0
type: Question
has body: Why infinite wildcard (*) in the regular expression is treated differently in python? Please tell me why in case one I'm getting different output than case two? CASE ONE: import re b= None a=None while a!='chk': a=input() b= re.findall('[A-Z][a-z]{1,400}',a) if b!=None: print(b,bool(b),type(b)) if a=='chk': break output: CAPITALLETTERSsmallletters ['Ssmallletters'] True &lt;class 'list'&gt; CASE TWO: import re b= None a=None while a!='chk': a=input() b= re.findall('[A-Z][a-z]*',a) if b!=None: print(b,bool(b),type(b)) if a=='chk': break output: CAPITALLETTERSsmallletters ['C', 'A', 'P', 'I', 'T', 'A', 'L', 'L', 'E', 'T', 'T', 'E', 'R', 'Ssmallletters'] True &lt;class 'list'&gt;
answer count: 1
downvote count: 0
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/49221548

neural-network
tags question: http://stackoverflow.com/q/49146798
tags question: http://stackoverflow.com/q/49244066
type: Tag
tags question: http://stackoverflow.com/q/49218304
tags question: http://stackoverflow.com/q/49161652
tags question: http://stackoverflow.com/q/49129162
tags question: http://stackoverflow.com/q/49227490
tags question: http://stackoverflow.com/q/49206550
tags question: http://stackoverflow.com/q/49263487
tags question: http://stackoverflow.com/q/49149699
tags question: http://stackoverflow.com/q/49212257
tags question: http://stackoverflow.com/q/49239478
tags question: http://stackoverflow.com/q/49240482
tags question: http://stackoverflow.com/q/49202952
tags question: http://stackoverflow.com/q/49275827
tags question: http://stackoverflow.com/q/49213432
tags question: http://stackoverflow.com/q/49193453
tags question: http://stackoverflow.com/q/49218443
tags question: http://stackoverflow.com/q/49255972
tags question: http://stackoverflow.com/q/49162276
tags question: http://stackoverflow.com/q/49124622
tags question: http://stackoverflow.com/q/49135929
tags question: http://stackoverflow.com/q/49190288
tags question: http://stackoverflow.com/q/49256788
tags question: http://stackoverflow.com/q/49162202
tags question: http://stackoverflow.com/q/49266801
tags question: http://stackoverflow.com/q/49200461
tags question: http://stackoverflow.com/q/49226440
tags question: http://stackoverflow.com/q/49208326
tags question: http://stackoverflow.com/q/49145544
tags question: http://stackoverflow.com/q/49129858
tags question: http://stackoverflow.com/q/49242500
tags question: http://stackoverflow.com/q/49262623
tags question: http://stackoverflow.com/q/49192536
tags question: http://stackoverflow.com/q/49223358
tags question: http://stackoverflow.com/q/49200423
tag name: neural-network
tags question: http://stackoverflow.com/q/49163835
tags question: http://stackoverflow.com/q/49240648
tags question: http://stackoverflow.com/q/49129123
tags question: http://stackoverflow.com/q/49215615
tags question: http://stackoverflow.com/q/49177169

http://stackoverflow.com/comment/85374325
type: Comment
comment on: http://stackoverflow.com/q/49184126
type: QuestionComment
has text: i am not able to find no of hands in the matfile which needs image_mat[0][0].shape?
score: 0

http://stackoverflow.com/comment/85549985
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49273588
has text: Thanks both, works like a charm, using the more implicit combination

http://stackoverflow.com/a/49255814
score: 1
has comment: http://stackoverflow.com/comment/85551915
type: AcceptedAnswer
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49254224
has body: You have to have a capture group when using .extract() in pandas. Your capture group before the OR, |, is finding the dates with slashes. But after the OR, you only have a non-capture group. Here I have placed a capture around the entire search pattern, and each side of the OR also has a non-capturing group. import pandas as pd df = pd.DataFrame({'text': ['My birthday is 2/21/19', 'Your birthday is 4/1/20', 'my best friend\'s birthday is 24 Jan 2001.']}) df.text.str.extract( r'((:?\d+[/-]\d+[/-]?\d*)|' + r'(:?\d{1,2}\s(:?Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s\d+))', expand=False)[0] # returns: 0 2/21/19 1 4/1/20 2 24 Jan 2001
answers question: http://stackoverflow.com/q/49254224
type: Answer

http://stackoverflow.com/q/49208444
has comment: http://stackoverflow.com/comment/85422322
tagged with: statistics
has title: Linear Discriminant Analysis in python
has body: I am doing Linear Discriminant Analysis in python but having some problems. Using the tutorial given here is was able to calculate linear discriminant analysis using python and got a plot like this: Using this code given below: import pandas as pd feature_dict = {i:label for i,label in zip( range(4), ('sepal length in cm', 'sepal width in cm', 'petal length in cm', 'petal width in cm', ))} df = pd.io.parsers.read_csv( filepath_or_buffer='https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None, sep=',', ) df.columns = [l for i,l in sorted(feature_dict.items())] + ['class label'] df.dropna(how="all", inplace=True) from sklearn.preprocessing import LabelEncoder X = df[[0,1,2,3]].values y = df['class label'].values enc = LabelEncoder() label_encoder = enc.fit(y) y = label_encoder.transform(y) + 1 label_dict = {1: 'Setosa', 2: 'Versicolor', 3:'Virginica'} from matplotlib import pyplot as plt import numpy as np import math np.set_printoptions(precision=4) mean_vectors = [] for cl in range(1,4): mean_vectors.append(np.mean(X[y==cl], axis=0)) print('Mean Vector class %s: %s\n' %(cl, mean_vectors[cl-1])) S_W = np.zeros((4,4)) for cl,mv in zip(range(1,4), mean_vectors): class_sc_mat = np.zeros((4,4)) # scatter matrix for every class for row in X[y == cl]: row, mv = row.reshape(4,1), mv.reshape(4,1) # make column vectors class_sc_mat += (row-mv).dot((row-mv).T) S_W += class_sc_mat # sum class scatter matrices print('within-class Scatter Matrix:\n', S_W) overall_mean = np.mean(X, axis=0) S_B = np.zeros((4,4)) for i,mean_vec in enumerate(mean_vectors): n = X[y==i+1,:].shape[0] mean_vec = mean_vec.reshape(4,1) # make column vector overall_mean = overall_mean.reshape(4,1) # make column vector S_B += n * (mean_vec - overall_mean).dot((mean_vec - overall_mean).T) print('between-class Scatter Matrix:\n', S_B) eig_vals, eig_vecs = np.linalg.eig(np.linalg.inv(S_W).dot(S_B)) for i in range(len(eig_vals)): eigvec_sc = eig_vecs[:,i].reshape(4,1) print('\nEig…
has comment: http://stackoverflow.com/comment/85422652
tagged with: matplotlib
tagged with: python
type: Question
score: 0
answer count: 0
type: UnansweredQuestion
tagged with: linear-discriminant
tagged with: plot
has comment: http://stackoverflow.com/comment/85424713

http://stackoverflow.com/comment/85503118
type: Comment
score: 0
type: QuestionComment
has text: So I tried using random initialization and even that isn't helping reduce the cost.
comment on: http://stackoverflow.com/q/49237369

http://stackoverflow.com/a/49262664
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49262379
has comment: http://stackoverflow.com/comment/132023027
has comment: http://stackoverflow.com/comment/132157293
downvote count: 1
has comment: http://stackoverflow.com/comment/132064578
upvote count: 301
has comment: http://stackoverflow.com/comment/85548264
has comment: http://stackoverflow.com/comment/85569641
has comment: http://stackoverflow.com/comment/132083636
answers question: http://stackoverflow.com/q/49262379
has comment: http://stackoverflow.com/comment/134878751
type: Answer
has comment: http://stackoverflow.com/comment/132020262
has comment: http://stackoverflow.com/comment/132072874
has comment: http://stackoverflow.com/comment/85562116
has comment: http://stackoverflow.com/comment/85559811
has comment: http://stackoverflow.com/comment/132157396
has comment: http://stackoverflow.com/comment/134878912
has comment: http://stackoverflow.com/comment/132065622
has comment: http://stackoverflow.com/comment/85576053
has comment: http://stackoverflow.com/comment/132020158
has comment: http://stackoverflow.com/comment/85563671
has comment: http://stackoverflow.com/comment/132157338
score: 300
has body: "Guaranteed" is a much stronger word than any implementation of finally deserves. What is guaranteed is that if execution flows out of the whole try-finally construct, it will pass through the finally to do so. What is not guaranteed is that execution will flow out of the try-finally. A finally in a generator or async coroutine might never run, if the object never executes to conclusion. There are a lot of ways that could happen; here's one: def gen(text): try: for line in text: try: yield int(line) except: # Ignore blank lines - but catch too much! pass finally: print('Doing important cleanup') text = ['1', '', '2', '', '3'] if any(n &gt; 1 for n in gen(text)): print('Found a number') print('Oops, no cleanup.') Note that this example is a bit tricky: when the generator is garbage collected, Python attempts to run the finally block by throwing in a GeneratorExit exception, but here we catch that exception and then yield again, at which point Python prints a warning ("generator ignored GeneratorExit") and gives up. See PEP 342 (Coroutines via Enhanced Generators) for details. Other ways a generator or coroutine might not execute to conclusion include if the object is just never GC'ed (yes, that's possible, even in CPython), or if an async with awaits in __aexit__, or if the object awaits or yields in a finally block. This list is not intended to be exhaustive. A finally in a daemon thread might never execute if all non-daemon threads exit first. os._exit will halt the process immediately without executing finally blocks. os.fork may cause finally blocks to execute twice. As well as just the normal problems you'd expect from things happening twice, this could cause concurrent access conflicts (crashes, stalls, ...) if access to shared resources is not correctly synchronized. Since multiprocessing uses fork-without-exec to create worker processes when using the fork start method (the default on Unix), and then calls os._exit in the worker once the worker's job is done,…
has comment: http://stackoverflow.com/comment/134312724

http://stackoverflow.com/comment/85425248
comment on: http://stackoverflow.com/q/49208617
type: QuestionComment
score: 0
has text: Of course there is such a possibility. But it's better to have somewhat balanced data for retraining. Or maybe you should just try lot less iterations for new data.
type: Comment

http://stackoverflow.com/a/49316664
downvote count: 1
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49143787
has body: The iterator object only support next() or for ... statement. You can reference it from here: https://wiki.python.org/moin/Iterator If you want output as [('a','l'), ('b','m'), ...] you should not write the code like that. By the way, please check if this is what you want: def myzip(*args): iters = map(iter, args) while iters: res = [i for i in next(iters)] yield tuple(res) list(myzip('abc', '1mnop')) And the output would be: [('a', 'b', 'c'), ('1', 'm', 'n', 'o', 'p')]
upvote count: 1

http://stackoverflow.com/a/49239620
type: Answer
has comment: http://stackoverflow.com/comment/85487884
has comment: http://stackoverflow.com/comment/96338538
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49239437
has body: This is my solution from the two sum question on LeetCode (modified to fit into your class) but it should work the same here: class TwoSum: @staticmethod def find_two_sum(numbers, target_sum): seen = {} for i, num in enumerate(numbers): try: return (seen[num], i) except KeyError: seen[target_sum - num] = i return (-1, -1)
type: AcceptedAnswer
score: 4
answers question: http://stackoverflow.com/q/49239437
downvote count: 0

http://stackoverflow.com/q/49163709
has comment: http://stackoverflow.com/comment/85333091
tagged with: python
tagged with: dictionary
score: 0
has comment: http://stackoverflow.com/comment/85333141
answer count: 2
has title: Convert string to dict and sort in ascending
has comment: http://stackoverflow.com/comment/85333087
upvote count: 1
has answer: http://stackoverflow.com/a/49163738
downvote count: 1
tagged with: string
has body: {“timid”:”34567”, “version”:”1”,”binary_data”:”fsfdsfsdfasdfasdfsfasfdsa”,”seqNumber”:”101”} {“timid”:”32567”, “version”:”1”,”binary_data”:”fsfsdfdsfdsfdsfsfsdfpipi”,”seqNumber”:”109”} {“timid”:”36567”, “version”:”1”,”binary_data”:”fsfdsfsdfafsdfdsfsfasdfsfasfdsa”,”seqNumber”:”100”} I have a file with strings in the above format, I want to convert the string into dictionary and sort the records using seq number in python3. I have been trying below method, but not successful. Any help is much appreciated! Thanks in advance import json import ast filename = 'u-data' with open(filename) as f: string1 = f.read() # ast.literal_eval(string1) data = dict(string1.split(':') for x in string1.split(',')) f.close() # string1 = string1[1:-2] print(data)
favorite count: 0
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49163798
type: UnansweredQuestion

http://stackoverflow.com/comment/85361893
comment on: http://stackoverflow.com/q/49178167
type: Comment
has text: You're not the only one with similar issue https://stackoverflow.com/questions/48361123/f90wrap-on-windows-python-wrapper-for-fortran-90 and check https://synchroversum.wordpress.com/2016/03/03/windows-f2py-f90wrap-mingw-gfortran/
score: 0
type: QuestionComment

http://stackoverflow.com/a/49128343
has comment: http://stackoverflow.com/comment/85269874
has comment: http://stackoverflow.com/comment/85268835
has comment: http://stackoverflow.com/comment/85270335
accepted answer of: http://stackoverflow.com/q/49127464
has comment: http://stackoverflow.com/comment/85267700
has comment: http://stackoverflow.com/comment/85267537
has comment: http://stackoverflow.com/comment/85269964
has comment: http://stackoverflow.com/comment/85267807
has comment: http://stackoverflow.com/comment/85270733
type: Answer
has comment: http://stackoverflow.com/comment/85270876
answers question: http://stackoverflow.com/q/49127464
score: 2
has comment: http://stackoverflow.com/comment/85267574
has comment: http://stackoverflow.com/comment/85261895
has comment: http://stackoverflow.com/comment/85267605
has comment: http://stackoverflow.com/comment/85267842
upvote count: 2
has comment: http://stackoverflow.com/comment/85267042
has comment: http://stackoverflow.com/comment/85267754
has comment: http://stackoverflow.com/comment/85268748
has body: This can be done using re.sub() to replace all matching text in one go: import re set_value = "_Number_" replace_with = "Two" filename = 'input.txt' with open(filename) as f_input: text = re.sub(r'(\w+)({})'.format(set_value), r'{}\2'.format(replace_with), f_input.read()) with open(filename, 'w') as f_output: f_output.write(text) For your example text this would update your file as: Two_Number_ = "0" if [ Two_Number_ == "0" ] To also list all of the matches before writing the new file and to add a bespoke replacement function: import re set_value = "_Number_" filename = 'input.txt' re_set = re.compile(r'(\w+)({})'.format(set_value)) def replace(re_match): values = {'one':'two', 'One':'Two', 'ONE':'TWO'} word = re_match.group(1) print('Word is', word) return '{}{}'.format(values[word], set_value) with open(filename) as f_input: text = re_set.sub(replace, f_input.read()) with open(filename, 'w') as f_output: f_output.write(text) So if your file contained: One_Number_ = "0" if [ One_Number_ == "0" ] one_Number_ = "0" if [ one_Number_ == "0" ] ONE_Number_ = "0" if [ ONE_Number_ == "0" ] The output would now be: Two_Number_ = "0" if [ Two_Number_ == "0" ] two_Number_ = "0" if [ two_Number_ == "0" ] TWO_Number_ = "0" if [ TWO_Number_ == "0" ] Just update the dictionary with any necessary conversions. Or use your own logic. re_match.group(1) contains the matching word. So you just need to build a suitable replacement string and return it. You could also add a print(re_match.group(1)) to show you each of the matched words, rather than the second findall() loop.
has comment: http://stackoverflow.com/comment/85268151
has comment: http://stackoverflow.com/comment/85266710
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85269017
has comment: http://stackoverflow.com/comment/85270457
has comment: http://stackoverflow.com/comment/85261643

http://stackoverflow.com/a/49219602
score: 4
has comment: http://stackoverflow.com/comment/85443421
upvote count: 4
has comment: http://stackoverflow.com/comment/85443962
has comment: http://stackoverflow.com/comment/85483659
has body: The docs have your solution. save is optimal, but is there to easily save and load the entire state for continuous work. You need much less if I understand correctly: Saving/loading only a model's architecture json_string = model.to_json() yaml_string = model.to_yaml() Saving/loading only a model's weights model.save_weights('my_model_weights.h5') Both I guess are much leaner then the entire working area. You can use these to recreate the model later on, as stated in the docs (load_weights, load_from_json, etc.).
has comment: http://stackoverflow.com/comment/85475016
downvote count: 0
answers question: http://stackoverflow.com/q/49219474
has comment: http://stackoverflow.com/comment/85446557
has comment: http://stackoverflow.com/comment/85442809
has comment: http://stackoverflow.com/comment/85446624
type: Answer
has comment: http://stackoverflow.com/comment/85443705

http://stackoverflow.com/a/49132001
has comment: http://stackoverflow.com/comment/92408109
downvote count: 0
has comment: http://stackoverflow.com/comment/85314703
has comment: http://stackoverflow.com/comment/85316101
has comment: http://stackoverflow.com/comment/85273772
type: Answer
has comment: http://stackoverflow.com/comment/85315175
has comment: http://stackoverflow.com/comment/85269672
answers question: http://stackoverflow.com/q/49129817
score: 2
has body: The problem is that when you create the empty environment, it installs absolutely no packages, even pip and Python. Therefore, when you use pip to install ipykernel, you're using the pip from the base environment. You need to create the environment with pip and python conda create -n testenv python You can check this by typing which pip after you create the blank environment. Finally, you should use conda to install all packages, including ipykernel, if at all possible.
upvote count: 2
has comment: http://stackoverflow.com/comment/85323810
has comment: http://stackoverflow.com/comment/85273462

http://stackoverflow.com/comment/85305025
type: Comment
type: AnswerComment
has text: i agree: a sorted list in python should always be a trigger to go for `bisect`.
comment on: http://stackoverflow.com/a/49150196
score: 0

http://stackoverflow.com/comment/85260346
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49126816
score: 0
has text: you're right. Once you indent, you should mantain the same indentation level. Here the problem is because the first 2 lines have 2 tabs (or 8 spaces) and the next lines have 1 tab (or 4 spaces). The problem may also be solved indenting everything at 2tabs (8spaces)

rounding
tags question: http://stackoverflow.com/q/49153253
tags question: http://stackoverflow.com/q/49174657
tag name: rounding
type: Tag
tags question: http://stackoverflow.com/q/49229610
tags question: http://stackoverflow.com/q/49236564

http://stackoverflow.com/a/49244571
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49244438
type: Answer
has body: Python provides a lot of ways to do this. You can do something like: [[a0, b0] for a0 in a for b0 in b]

http://stackoverflow.com/comment/85530743
type: QuestionComment
has text: What do you mean by, "Where are this both guys [ and ]"?
type: Comment
comment on: http://stackoverflow.com/q/49263550
score: 1

http://stackoverflow.com/q/49270521
has comment: http://stackoverflow.com/comment/85544552
has title: Why in python -11%5 evaluate to 4?
answer count: 3
upvote count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/3883004
has body: I am familiar with the usual mod result but not for negative numbers. What is the logic?
score: -7
downvote count: 7
has answer: http://stackoverflow.com/a/49270603
favorite count: 0
has answer: http://stackoverflow.com/a/49270608
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49270584
tagged with: modulus
linked to: http://stackoverflow.com/q/3883004

http://stackoverflow.com/comment/85504617
type: AnswerComment
has text: Well, nevwrmind, `astype` does make a copy. But there's a no-copy solution in the comments to the question.
comment on: http://stackoverflow.com/a/49250415
score: 0
type: Comment

http://stackoverflow.com/q/49126118
type: Question
accepted answer: http://stackoverflow.com/a/49127668
has body: I have some data like this, u'1 股票 2 债券 3 TOT-我司单个信托计划（穿透式） 4 TOT-我司多个信托计划 5 TOT-外部信托计划 6 FOF-指定单个外部产品 7 FOF-指定多个外部产品 8 股票定增 9 股票质押 10 私募基金（我司） 99 其他 '. I want transfer those to pandas dataframe. So,what should I do?
has title: python how to transfer data like u'**\t**\r**\t**\r' to dataframe
has answer: http://stackoverflow.com/a/49127668
tagged with: dataframe
tagged with: python
possible better answer: http://stackoverflow.com/a/49127101
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49127101
answer count: 2
score: 0
has comment: http://stackoverflow.com/comment/85256913
has comment: http://stackoverflow.com/comment/85256944
has comment: http://stackoverflow.com/comment/85258096

http://stackoverflow.com/comment/85496228
score: 0
has text: But I have it defined at the top doesnt that count?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49206140

http://stackoverflow.com/q/49239136
answer count: 1
downvote count: 0
tagged with: tensorflow
favorite count: 0
type: Question
has title: What happens when you add a tensor with a numpy array?
tagged with: python
score: 4
upvote count: 4
has body: tensorflow 1.6 I was very surprised when I noticed that the following code works: a = tf.constant(5) b = a + np.array(25) b.eval() # 30 I was expecting that this throws an error. How does tensorflow handle this case? Is the numpy array added as a constant tensor to the graph so that everything can still be run on GPU? Or will there be some break to compute things on CPU? In other words, are there any drawbacks in writing it this way, in contrast to defining a proper tf.constant tensor by hand?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49239220
has answer: http://stackoverflow.com/a/49239220

http://stackoverflow.com/comment/85318208
comment on: http://stackoverflow.com/a/49155823
type: Comment
score: 0
type: AnswerComment
has text: You can create any methods that you like. But it doesn't make sense to create a method that doesn't use any data from the class itself; that sort of thing should be a standalone function, or at the very least a staticmethod.

http://stackoverflow.com/a/49278537
type: Answer
answers question: http://stackoverflow.com/q/49278353
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85559548
score: 0
accepted answer of: http://stackoverflow.com/q/49278353
has body: You're getting an infinite loop by calling my1() within my1(). I would make the following edits: def my1(a): if a is '': print('You have not entered anything') else: b=int(a)**2 print (b) my1(input("Enter a Number"))

http://stackoverflow.com/comment/85349583
comment on: http://stackoverflow.com/a/49136049
score: 0
has text: Hi Martin, if I were to save the excel file as a .csv would I still need to install a package for python to read it? As I'm trying to avoid installing further packages if possible. Or is there any other potential solutions without requiring further installations? Cheers
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49134133
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/85273695
has comment: http://stackoverflow.com/comment/85329069
has body: I'm creating a custom "upload from csv" function in my Django application, using a custom model.Manager method that receives the result of applying csv.DictReader on the csv data. My tests on normal models are okay, but they are failing on models with ForeignKey constraints. The relevant source codes are as follows models.py class PledgeManager(models.Manager): """Custom manager for model Pledge.""" def from_upload(self, data): """Process data from Pledge upload.""" for obj in data: try: # get the prospect &amp; fund by natural key obj['prospect'] = Prospect.objects.get_by_natural_key( obj['prospect']) obj['pledge_fund'] = Fund.objects.get_by_natural_key( obj['pledge_fund']) obj['pledge_date'] = datetime.strptime( obj['pledge_date'], r'%d/%m/%Y') try: with transaction.atomic(): self.create(**obj) ccall_log.debug('Created Pledge object: %s', obj) except IntegrityError: ccall_log.error('Cannot create Pledge object: %s', obj) except Prospect.DoesNotExist: # no prospect ccall_log.error( 'Cannot create Pledge object, no Prospect: %s', obj) except Fund.DoesNotExist: # no fund ccall_log.error( 'Cannot create Pledge object, no Fund: %s', obj) except BaseException as exc_: ccall_log.exception(exc_) ccall_log.error( 'Exception encountered during processing: %s', obj) class Pledge(models.Model): """Model for a Pledge.""" objects = PledgeManager() pledge_amount = models.DecimalField( verbose_name='Pledge amount', decimal_places=2, max_digits=12, validators=[MinValueValidator(0)]) pledge_fund = models.ForeignKey(Fund, on_delete=models.CASCADE) pledge_date = models.DateField(verbose_name='Pledge date') prospect = models.ForeignKey(Prospect, on_delete=models.CASCADE) test_models.py class TestPledge(TestCase): """Test cases for Pledge.""" @classmethod def setUpTestData(cls): prospect_obj = { 'ic': 'Test Prospect', ... } Prospect.objects.create(**prospect_obj) Fund.objects.create(name='Test Fund') cls.pledge_obj_add_1 = { 'prospect': 'Test Prospect', 'pledge_amount': '50', 'pledge_f…
has comment: http://stackoverflow.com/comment/85348730
has comment: http://stackoverflow.com/comment/85415030
has comment: http://stackoverflow.com/comment/85415117
has title: Tests failed on ForeignKey constraints
has comment: http://stackoverflow.com/comment/85982480
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85332052
has comment: http://stackoverflow.com/comment/85456970
has comment: http://stackoverflow.com/comment/85313507
has comment: http://stackoverflow.com/comment/85456853
has comment: http://stackoverflow.com/comment/85427796
type: Question
has comment: http://stackoverflow.com/comment/85274937
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85977997
has comment: http://stackoverflow.com/comment/85274822

http://stackoverflow.com/a/49162194
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/49162051
has body: Try using: df_tickets = df_tickets.groupby(df_tickets['id']).sum() This should work.
score: 1
has comment: http://stackoverflow.com/comment/85331231

http://stackoverflow.com/q/49264116
tagged with: mongodb
accepted answer: http://stackoverflow.com/a/49265025
tagged with: python
has answer: http://stackoverflow.com/a/49265025
type: AnsweredQuestion
has title: Mongodb: Shard a collection within my python code
score: 1
has body: I have a distributed MongoDB 3.2 database. The system is mounted on two nodes with RedHat operating system. Using python and the PyMongo driver (or some other), I want enable the sharding of a collection, specifying the compound shard key. In the mongo shell this works: &gt; use mongotest &gt; sh.enableSharding("mongotest") &gt; db.signals.createIndex({ valueX: 1, valueY: 1 }, { unique: true }) &gt; sh.shardCollection("mongotest.signals", { valueX: 1, valueY: 1 }) ('mongotest' is the DB, and 'signals' is the collection) The last two lines I want to make them within my code. Does anyone know if this is possible in python? If so, how is it done? thank you very much, sorry for my bad English
answer count: 1
tagged with: pymongo
downvote count: 0
tagged with: sharding
upvote count: 1
favorite count: 0
type: Question

dictionary
tags question: http://stackoverflow.com/q/49184828
tags question: http://stackoverflow.com/q/49203269
tags question: http://stackoverflow.com/q/49131591
tags question: http://stackoverflow.com/q/49185342
tags question: http://stackoverflow.com/q/49169800
tags question: http://stackoverflow.com/q/49226738
tags question: http://stackoverflow.com/q/49173394
tags question: http://stackoverflow.com/q/49129604
tags question: http://stackoverflow.com/q/49142012
tags question: http://stackoverflow.com/q/49183510
tags question: http://stackoverflow.com/q/49186618
tags question: http://stackoverflow.com/q/49178952
tags question: http://stackoverflow.com/q/49229254
tags question: http://stackoverflow.com/q/49123464
tags question: http://stackoverflow.com/q/49140169
tags question: http://stackoverflow.com/q/49250225
tags question: http://stackoverflow.com/q/49225591
tags question: http://stackoverflow.com/q/49188130
tags question: http://stackoverflow.com/q/49275799
tags question: http://stackoverflow.com/q/49238107
tags question: http://stackoverflow.com/q/49204684
tags question: http://stackoverflow.com/q/49133657
tags question: http://stackoverflow.com/q/49177869
tags question: http://stackoverflow.com/q/49193164
tags question: http://stackoverflow.com/q/49199998
tags question: http://stackoverflow.com/q/49185974
tags question: http://stackoverflow.com/q/49269874
tags question: http://stackoverflow.com/q/49121526
tags question: http://stackoverflow.com/q/49202764
tags question: http://stackoverflow.com/q/49158367
tags question: http://stackoverflow.com/q/49176404
tags question: http://stackoverflow.com/q/49226716
tags question: http://stackoverflow.com/q/49225394
tags question: http://stackoverflow.com/q/49269134
tags question: http://stackoverflow.com/q/49247648
tags question: http://stackoverflow.com/q/49156749
tags question: http://stackoverflow.com/q/49138516
tags question: http://stackoverflow.com/q/49264594
tags question: http://stackoverflow.com/q/49194107
tags question: http://stackoverflow.com/q/49184885
tags question: http://stackoverflow.com/q/49175851
tags question: http://stackoverflow.com/q/49241332
tags question: http://stackoverflow.com/q/49199558
tags question: http://stackoverflow.com/q/49126700
tags question: http://stackoverflow.com/q/49147553
tags question: http://stackoverflow.com/q/49126664
tags question: http://stackoverflow.com/q/49131704
tags question: http://stackoverflow.com/q/49129934
tags question: http://stackoverflow.com/q/49226978
tags question: http://stackoverflow.com/q/49274426
tags question: http://stackoverflow.com/q/49248551
tags question: http://stackoverflow.com/q/49140499
tags question: http://stackoverflow.com/q/49125810
tags question: http://stackoverflow.com/q/49274532
tags question: http://stackoverflow.com/q/49210418
tags question: http://stackoverflow.com/q/49259580
tags question: http://stackoverflow.com/q/49271730
tags question: http://stackoverflow.com/q/49206263
tags question: http://stackoverflow.com/q/49176797
tags question: http://stackoverflow.com/q/49181337
tags question: http://stackoverflow.com/q/49201897
tags question: http://stackoverflow.com/q/49157285
tags question: http://stackoverflow.com/q/49186115
tags question: http://stackoverflow.com/q/49184578
tags question: http://stackoverflow.com/q/49130520
tags question: http://stackoverflow.com/q/49208794
tags question: http://stackoverflow.com/q/49197103
tags question: http://stackoverflow.com/q/49216669
tags question: http://stackoverflow.com/q/49186689
tags question: http://stackoverflow.com/q/49244982
tags question: http://stackoverflow.com/q/49218302
tags question: http://stackoverflow.com/q/49175373
tags question: http://stackoverflow.com/q/49257103
tags question: http://stackoverflow.com/q/49270248
tags question: http://stackoverflow.com/q/49215898
tags question: http://stackoverflow.com/q/49255529
type: Tag
tags question: http://stackoverflow.com/q/49191952
tags question: http://stackoverflow.com/q/49195394
tags question: http://stackoverflow.com/q/49143787

http://stackoverflow.com/q/49260932
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85525446
duplicate of: http://stackoverflow.com/q/43717739
has body: Im using this code from Sci Kit Learns website for a regression algorithm and then plotting Deviance &amp; variable importance with matplotlib. [Sci Kit Learn Gradient Boost regression][1] The Sci Kit Learn examples the famous Boston housing project data set that is built into the Sci Kit Learn Package when data is plotted matplotlib references boston.feature_names and I am trying to find away around this with my Pandas data frame. plt.yticks(pos, boston.feature_names[sorted_idx]) Can this be retrofitted for Y ticks to be my column header name in my Pandas dataframe?
type: UnansweredQuestion
tagged with: matplotlib
has title: Sci Kit Learn Y ticks Matplotlib
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85526978
upvote count: 0
has comment: http://stackoverflow.com/comment/85526690
has answer: http://stackoverflow.com/a/49264863
linked to: http://stackoverflow.com/q/43717739
downvote count: 1
answer count: 1
tagged with: machine-learning
tagged with: scikit-learn
tagged with: data-science

http://stackoverflow.com/comment/87161882
type: Comment
comment on: http://stackoverflow.com/q/49201651
type: QuestionComment
score: 0
has text: The above script works only if you are added as a collaborator in the repository. If you are not added as a collaborator then the code will return a 403 Response which means you are not authorized to access the repository.

http://stackoverflow.com/a/49132838
type: Answer
has body: Here's one way In [127]: df.groupby(['id', 'name']).marks.agg( lambda x: 'pass' if x.ge(40).all() else 'fail' ).reset_index(name='result') Out[127]: id name result 0 1 a pass 1 2 b fail 2 3 c pass Another way, inspired from jpp's solution, use replace or map In [132]: df.groupby(['id', 'name']).marks.min().ge(40).replace( {True: 'pass', False: 'fail'} ).reset_index(name='result') Out[132]: id name result 0 1 a pass 1 2 b fail 2 3 c pass
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49132537

flask
tags question: http://stackoverflow.com/q/49204634
tags question: http://stackoverflow.com/q/49266786
tags question: http://stackoverflow.com/q/49193564
tags question: http://stackoverflow.com/q/49275602
tags question: http://stackoverflow.com/q/49245762
tags question: http://stackoverflow.com/q/49237550
tags question: http://stackoverflow.com/q/49268491
tags question: http://stackoverflow.com/q/49261727
tags question: http://stackoverflow.com/q/49181442
tags question: http://stackoverflow.com/q/49266877
tags question: http://stackoverflow.com/q/49257427
tags question: http://stackoverflow.com/q/49140718
tags question: http://stackoverflow.com/q/49143581
tags question: http://stackoverflow.com/q/49178607
tags question: http://stackoverflow.com/q/49200946
tags question: http://stackoverflow.com/q/49215197
tags question: http://stackoverflow.com/q/49241455
tags question: http://stackoverflow.com/q/49208779
tags question: http://stackoverflow.com/q/49123852
tags question: http://stackoverflow.com/q/49251077
tags question: http://stackoverflow.com/q/49148280
tags question: http://stackoverflow.com/q/49256594
tags question: http://stackoverflow.com/q/49221539
tags question: http://stackoverflow.com/q/49152603
tags question: http://stackoverflow.com/q/49135178
tags question: http://stackoverflow.com/q/49215541
tags question: http://stackoverflow.com/q/49207457
tags question: http://stackoverflow.com/q/49150413
tags question: http://stackoverflow.com/q/49224204
tags question: http://stackoverflow.com/q/49129272
tags question: http://stackoverflow.com/q/49226187
tags question: http://stackoverflow.com/q/49126335
tags question: http://stackoverflow.com/q/49244469
tags question: http://stackoverflow.com/q/49215207
tags question: http://stackoverflow.com/q/49251306
tags question: http://stackoverflow.com/q/49201142
tags question: http://stackoverflow.com/q/49268154
tags question: http://stackoverflow.com/q/49267094
tags question: http://stackoverflow.com/q/49227958
tags question: http://stackoverflow.com/q/49238871
tags question: http://stackoverflow.com/q/49126777
tags question: http://stackoverflow.com/q/49124937
tags question: http://stackoverflow.com/q/49207257
tags question: http://stackoverflow.com/q/49188956
tags question: http://stackoverflow.com/q/49255545
tags question: http://stackoverflow.com/q/49238583
tags question: http://stackoverflow.com/q/49171144
tags question: http://stackoverflow.com/q/49241724
tags question: http://stackoverflow.com/q/49196720
tags question: http://stackoverflow.com/q/49171039
tags question: http://stackoverflow.com/q/49254756
tags question: http://stackoverflow.com/q/49172153
tags question: http://stackoverflow.com/q/49191508
tags question: http://stackoverflow.com/q/49254588
tags question: http://stackoverflow.com/q/49189246
tags question: http://stackoverflow.com/q/49255283
tags question: http://stackoverflow.com/q/49241194
tags question: http://stackoverflow.com/q/49267744
tags question: http://stackoverflow.com/q/49121503
tags question: http://stackoverflow.com/q/49226626
tags question: http://stackoverflow.com/q/49205097
tags question: http://stackoverflow.com/q/49209916
tags question: http://stackoverflow.com/q/49245479
tag name: flask
tags question: http://stackoverflow.com/q/49231130
tags question: http://stackoverflow.com/q/49135157
tags question: http://stackoverflow.com/q/49220617
tags question: http://stackoverflow.com/q/49153216
tags question: http://stackoverflow.com/q/49276099
tags question: http://stackoverflow.com/q/49206406
tags question: http://stackoverflow.com/q/49273725
tags question: http://stackoverflow.com/q/49200605
tags question: http://stackoverflow.com/q/49141017
tags question: http://stackoverflow.com/q/49261149
tags question: http://stackoverflow.com/q/49213200
tags question: http://stackoverflow.com/q/49219050
tags question: http://stackoverflow.com/q/49235082
tags question: http://stackoverflow.com/q/49266584
tags question: http://stackoverflow.com/q/49225564
tags question: http://stackoverflow.com/q/49269343

http://stackoverflow.com/comment/85303246
has text: how about calling `python` from `R` and catching the error?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49149348
score: 0

http://stackoverflow.com/comment/85474486
comment on: http://stackoverflow.com/q/49235545
score: 1
type: QuestionComment
type: Comment
has text: I have added an edit to the question with all the information. Thanks!

http://stackoverflow.com/a/49137161
score: 3
has body: Not really an answer, just some considerations. I see a few difficulties to consider if using GCS for storing the shared models: importing the models in your app code would be a bit more complex, you'll need to use GCS libraries to read the file(s) for dynamic importing as they would not be available in the local filesystem. As a side effect of the dynamic importing you may loose some development capabilities in your IDE (like auto-completion, object structure verifications, etc) Preserving them might be possible, but probably not trivial. splitting the model definitions across model files (for partial reuse, inheritance and/or inter-model references for example) would not be a simple task. The point above would need to be addressed in the model files as well, in addition to the application code. deploying the app code on GAE and the models on GCP will always be non-atomic, extra care for coordinating the deployments and probably backward/forward compatibility would be needed to minimize/eliminate transient failures. IMHO the symlinks would be a simpler approach.
type: Answer
has comment: http://stackoverflow.com/comment/85281630
answers question: http://stackoverflow.com/q/49136417
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85284657

http://stackoverflow.com/a/49139150
has comment: http://stackoverflow.com/comment/85286888
has comment: http://stackoverflow.com/comment/85283672
has comment: http://stackoverflow.com/comment/85286114
has comment: http://stackoverflow.com/comment/85285024
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85286001
has body: Since you have a ratio of 1/6 between the x limit ranges of the two plots, those plots need to deviate by a factor of 6 in size as well if they should preserve the same height. (Note that apparently there might have been a bug in earlier versions of matplotlib, which made the below code not working as expected; however, it runs fine with matplotlib 2.2) import matplotlib.pyplot as plt import numpy as np fig, (ax1,ax2) = plt.subplots(ncols=2, sharey=True, subplot_kw=dict(aspect='equal'), gridspec_kw=dict(width_ratios=[6,1])) def create_data(xmin,xmax): delta = 0.025 x = np.arange(xmin, xmax, delta) y = np.arange(-3,3,delta) X, Y = np.meshgrid(x, y) Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 10 * (Z1 - Z2) nr, nc = Z.shape # put NaNs in one corner: Z[-nr//6:, -nc//6:] = np.nan # contourf will convert these to masked Z = np.ma.array(Z) # mask another corner: Z[:nr//6, :nc//6] = np.ma.masked # mask a circle in the middle: interior = np.sqrt((X**2) + (Y**2)) &lt; 0.5 Z[interior] = np.ma.masked return X,Y,Z X,Y,Z=create_data(-2,4) ax1.contourf(X,Y,Z) ax1.set_ylim(-1,1) ax1.set_xlim(-2,4) X,Y,Z=create_data(-1,0) ax2.contourf(X,Y,Z) ax2.set_ylim(-1,1) ax2.set_xlim(-1,0) plt.show()
has comment: http://stackoverflow.com/comment/85283602
has comment: http://stackoverflow.com/comment/85285960
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/49138888
has comment: http://stackoverflow.com/comment/85285167
type: Answer
has comment: http://stackoverflow.com/comment/85283725
has comment: http://stackoverflow.com/comment/85285544
answers question: http://stackoverflow.com/q/49138888
has comment: http://stackoverflow.com/comment/85286218

http://stackoverflow.com/a/49209915
has comment: http://stackoverflow.com/comment/85442450
accepted answer of: http://stackoverflow.com/q/49208949
has comment: http://stackoverflow.com/comment/85445130
downvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49208949
has body: From the Netlib documentation If LWORK = -1, then a workspace query is assumed; the routine only calculates the optimal size of the WORK array, returns this value as the first entry of the WORK array, and no error message related to LWORK is issued by XERBLA. You haven't asked for a calculation - you've just asked how big you should make the workspace array. You can either follow this up with a second call with an appropriately sized workspace array, or just allocate a workspace array according to the documentation (optimally max( 1, MN + max( MN, NRHS )*NB )) and pass the size of that as LWORK.
has comment: http://stackoverflow.com/comment/85426217
type: Answer
upvote count: 2
score: 2

http://stackoverflow.com/q/49198623
tagged with: python
type: Question
tagged with: daemon
has comment: http://stackoverflow.com/comment/85402592
tagged with: raspberry-pi
type: UnansweredQuestion
has title: Python CSV not working on daemon but works when launch manually
answer count: 1
has body: I have a python script that launch with a daemon at the start of the raspberry pi 3. That's a script I modified and it was working perfectly before. The script get the ID of a card from a RFID reader, then it post a request on a local server. I modified the script just to write the card ID and the date in a CSV file. When I run the script manually everything works well, it write the data in the CSV and everything perfectly. But when I reboot the raspberry, the writing in the CSV file doesn't works. The post request works. I've no error, the script continue to works anyway. I've no clue of what's going on. Here is my script: import requests import binascii import sys import time import subprocess import Adafruit_PN532 as PN532 import csv import datetime duration = 20000 def post_url(uid, duration): url = 'http://localhost:1339/app=web/uid=%s/duration=%d' % (uid, duration) requests.post(url) def get_url(uid, duration): url = 'http://localhost:1339/app=web/uid=%s/duration=%d' % (uid, duration) requests.get(url) # RPI GPIO pins configuration CS = 18 MOSI = 23 MISO = 24 SCLK = 25 # Create an instance of the PN532 class pn532 = PN532.PN532(cs=CS, sclk=SCLK, mosi=MOSI, miso=MISO) # Call beign to initialize communication with the PN532 pn532.begin() pn532.SAM_configuration() # Main loop to detect cards and read a block with open('log.csv', 'a') as log: while True: # Check if a card is available to read uid = pn532.read_passive_target() # Try again if no card is available if uid is None: continue # Transforming card ui into hex format for comparison against # registereed uid cards card_uid = '0x{0}'.format(binascii.hexlify(uid)) if card_uid is not None: subprocess.call("date") print('Hello') writer = csv.writer(log) data=[card_uid, datetime.datetime.now()] writer.writerow([data[0], date[1]]) post_url(card_uid, duration) time.sleep(5) else: continue .sh file : DIR=my/path/to/file DAEMON=$DIR/card_read.py DAEMON_NAME=card_read # Add any command line options for your daemon her…
has answer: http://stackoverflow.com/a/49224911
score: 0
has comment: http://stackoverflow.com/comment/85410558
has comment: http://stackoverflow.com/comment/85406723
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85408750

http://stackoverflow.com/comment/85500503
has text: Thanks a lot, I shall implement it and get back to you.
comment on: http://stackoverflow.com/a/49248456
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85288375
has text: Try replacing `channel` with `channels`.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49141345

http://stackoverflow.com/q/49131464
accepted answer: http://stackoverflow.com/a/49132036
tagged with: classification
has body: I have a three-class classification problem. I train the classifier and then plot the ROC for the different classes. I need to get the threshold for each class which maximizes the TPR and minimizes the FPR. In Matlab, this is returned. Is there a way to retrieve this in python / sklearn? Thanks.
answer count: 1
has answer: http://stackoverflow.com/a/49132036
tagged with: machine-learning
tagged with: scikit-learn
type: Question
tagged with: roc
has comment: http://stackoverflow.com/comment/85268234
tagged with: python
has title: sklearn classifier - predict_proba threshold that maximizes auc
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85267777

http://stackoverflow.com/comment/85482493
comment on: http://stackoverflow.com/q/49239437
has text: Aside: If you've got a class that's only there to have a static method - you don't need a class...
score: 1
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85461227
has text: Also, why is regex a requirement; what's wrong with just `isalpha` here?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49228915
score: 0

http://stackoverflow.com/comment/85380239
comment on: http://stackoverflow.com/q/49187493
type: Comment
type: QuestionComment
score: 0
has text: `page` has data in it?

http://stackoverflow.com/a/56306600
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49215194
has body: By copying the lines that make pyenv work right into the post-receive hook script before using Python the first time, pyenv can be used as expected. export PYENV_ROOT="$HOME/.pyenv" export PATH="$PYENV_ROOT/bin:$PATH" if command -v pyenv 1&gt;/dev/null 2&gt;&amp;1; then eval "$(pyenv init -)" fi
downvote count: 0
type: Answer

http://stackoverflow.com/a/49182218
type: AcceptedAnswer
downvote count: 0
has body: UPDATED: Now accounts for multiple matches from bs4 import BeautifulSoup s = ''' * Group I-want-ya * Group I-want-you-2 ''' soup = BeautifulSoup(s, 'html.parser') divs = soup.find_all('div', attrs={'class': 'labelx'}) for div in divs: try: div.find('a', {'title': 'Group'}) print(div.findNext('div', {'class': 'input'}).text) except: print('No match.') Gives: I-want-ya I-want-you-2
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49181878
answers question: http://stackoverflow.com/q/49181878
score: 1
has comment: http://stackoverflow.com/comment/85371574
type: Answer

http://stackoverflow.com/q/49157680
tagged with: webcam
tagged with: detection
score: 1
downvote count: 0
answer count: 1
has title: Opencv webcam camera check variable status after a time period
upvote count: 1
favorite count: 0
type: Question
tagged with: opencv
type: UnansweredQuestion
tagged with: gesture
tagged with: python
has body: I writing a code to detect human fist inside a box from the webcam. What i want is after checking there is a fist inside, the program will wait for 2 seconds. After 2 seconds, if there is still a fist inside, then it will put a text "FIST" Here is my code : import cv2 import numpy as np from detect import detect_fist import time cap = cv2.VideoCapture(0) isFist = 0 while (cap.isOpened()): ret, img = cap.read() img = cv2.flip(img, 1) cv2.rectangle(img, (50, 50), (150, 150), (0, 255, 0), 0) confirm = img[50:150, 50:150] # narrow the whole webcam to a box isFist = detect_fist(confirm) # a function to detect fist inside that box if isFist: timeout = int(time.time()) + 2 while 1: if int(time.time()) == int(timeout): cv2.putText(img, "Fist", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, 2) break cv2.imshow('Gesture', img) k = cv2.waitKey(10) if k == 27: break my problem is after it detect my fist in the box ,the camera display turn slowly , almost freeze. What i want is the camera still working normally and will check the fist again after 2 secs. I suggest this is due to the checking of condition if int(time.time()) == int(timeout) will be executed following the frame rate of the webcam ( which is really fast ) there for the display part cannot follow. Anyone have any idea to archive this ?
has answer: http://stackoverflow.com/a/49164379

postgresql
tags question: http://stackoverflow.com/q/49161309
tags question: http://stackoverflow.com/q/49276965
tags question: http://stackoverflow.com/q/49245216
tags question: http://stackoverflow.com/q/49189836
tags question: http://stackoverflow.com/q/49194072
type: Tag
tags question: http://stackoverflow.com/q/49241246
tags question: http://stackoverflow.com/q/49175720
tags question: http://stackoverflow.com/q/49152634
tags question: http://stackoverflow.com/q/49240581
tags question: http://stackoverflow.com/q/49223733
tags question: http://stackoverflow.com/q/49181152
tags question: http://stackoverflow.com/q/49249200
tags question: http://stackoverflow.com/q/49208063
tags question: http://stackoverflow.com/q/49136407
tags question: http://stackoverflow.com/q/49244643
tags question: http://stackoverflow.com/q/49274137
tags question: http://stackoverflow.com/q/49275868
tags question: http://stackoverflow.com/q/49177077
tags question: http://stackoverflow.com/q/49254041
tags question: http://stackoverflow.com/q/49139044
tags question: http://stackoverflow.com/q/49155485
tags question: http://stackoverflow.com/q/49226204
tag name: postgresql
tags question: http://stackoverflow.com/q/49137610

http://stackoverflow.com/a/49215247
has comment: http://stackoverflow.com/comment/85677834
has comment: http://stackoverflow.com/comment/87074986
answers question: http://stackoverflow.com/q/49158246
score: 6
upvote count: 6
type: Answer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49158246
type: AcceptedAnswer
has body: I had the same issue with selenium 3.10, but not with 3.9. Apparently, there's a bug in version 3.10 according to: https://github.com/SeleniumHQ/selenium/issues/5578 My temporary solution is to uninstall selenium 3.10, and install 3.9: pip uninstall selenium pip install selenium==3.9 And it should solve the problem.

list
tags question: http://stackoverflow.com/q/49183510
type: Tag
tags question: http://stackoverflow.com/q/49215434
tags question: http://stackoverflow.com/q/49273421
tags question: http://stackoverflow.com/q/49248645
tags question: http://stackoverflow.com/q/49277168
tags question: http://stackoverflow.com/q/49244476
tags question: http://stackoverflow.com/q/49160714
tags question: http://stackoverflow.com/q/49221386
tags question: http://stackoverflow.com/q/49191107
tags question: http://stackoverflow.com/q/49278761
tags question: http://stackoverflow.com/q/49123661
tags question: http://stackoverflow.com/q/49133320
tags question: http://stackoverflow.com/q/49275799
tags question: http://stackoverflow.com/q/49178954
tags question: http://stackoverflow.com/q/49227249
tags question: http://stackoverflow.com/q/49259274
tags question: http://stackoverflow.com/q/49162010
tags question: http://stackoverflow.com/q/49238107
tags question: http://stackoverflow.com/q/49168090
tags question: http://stackoverflow.com/q/49137041
tags question: http://stackoverflow.com/q/49215610
tags question: http://stackoverflow.com/q/49188794
tags question: http://stackoverflow.com/q/49203330
tags question: http://stackoverflow.com/q/49158499
tags question: http://stackoverflow.com/q/49171749
tags question: http://stackoverflow.com/q/49139939
tags question: http://stackoverflow.com/q/49131300
tags question: http://stackoverflow.com/q/49216060
tags question: http://stackoverflow.com/q/49206249
tags question: http://stackoverflow.com/q/49247268
tags question: http://stackoverflow.com/q/49150016
tags question: http://stackoverflow.com/q/49261197
tags question: http://stackoverflow.com/q/49268016
tags question: http://stackoverflow.com/q/49263997
tags question: http://stackoverflow.com/q/49215738
tags question: http://stackoverflow.com/q/49264805
tags question: http://stackoverflow.com/q/49262993
tags question: http://stackoverflow.com/q/49148641
tags question: http://stackoverflow.com/q/49137189
tags question: http://stackoverflow.com/q/49156749
tags question: http://stackoverflow.com/q/49205155
tags question: http://stackoverflow.com/q/49259197
tags question: http://stackoverflow.com/q/49145315
tags question: http://stackoverflow.com/q/49203044
tags question: http://stackoverflow.com/q/49248107
tags question: http://stackoverflow.com/q/49227963
tags question: http://stackoverflow.com/q/49127546
tags question: http://stackoverflow.com/q/49143433
tags question: http://stackoverflow.com/q/49227517
tags question: http://stackoverflow.com/q/49248003
tags question: http://stackoverflow.com/q/49134404
tags question: http://stackoverflow.com/q/49215820
tags question: http://stackoverflow.com/q/49162712
tags question: http://stackoverflow.com/q/49241335
tags question: http://stackoverflow.com/q/49264594
tags question: http://stackoverflow.com/q/49227337
tags question: http://stackoverflow.com/q/49274565
tags question: http://stackoverflow.com/q/49155117
tags question: http://stackoverflow.com/q/49123460
tags question: http://stackoverflow.com/q/49158789
tags question: http://stackoverflow.com/q/49243545
tags question: http://stackoverflow.com/q/49174427
tags question: http://stackoverflow.com/q/49276183
tags question: http://stackoverflow.com/q/49147553
tags question: http://stackoverflow.com/q/49220538
tags question: http://stackoverflow.com/q/49207869
tags question: http://stackoverflow.com/q/49157419
tags question: http://stackoverflow.com/q/49220428
tags question: http://stackoverflow.com/q/49140499
tags question: http://stackoverflow.com/q/49210658
tags question: http://stackoverflow.com/q/49156583
tags question: http://stackoverflow.com/q/49241059
tags question: http://stackoverflow.com/q/49163050
tags question: http://stackoverflow.com/q/49246354
tags question: http://stackoverflow.com/q/49154090
tags question: http://stackoverflow.com/q/49227033
tags question: http://stackoverflow.com/q/49182242
tags question: http://stackoverflow.com/q/49217765
tags question: http://stackoverflow.com/q/49260329

http://stackoverflow.com/a/56061541
downvote count: 0
has body: Since your going across accounts, you obviously can't follow the advice many people say of attaching directly to the lambda. Your best option is parameter store which is covered in detail here: https://aws.amazon.com/blogs/compute/sharing-secrets-with-aws-lambda-using-aws-systems-manager-parameter-store/ Simply have lambda request the credentials from there instead. That said, it's probably not going to save much time compared to STS requests... But I've not timed either process. A perhaps less-good way, that's fairly simple, is to store the credentials in /TMP and build a process around enduring the credentials remain valid -- perhaps assume role with 65 minute duration, and save to a time stamped file with the minutes/seconds dropped. If the file exists, read it in by file I/O. Keep in mind your saving credentials in a way that can be compromised if your code allows access to read the file in some way... Though as a lambda and with shared responsibility security, it's reasonably secure compared to doing this strategy on a persistent server. Always use least privilege roles. Only allow your trusted account to assume this role... I think your can even lock trust policies down to a specific incoming lambda role as allowed to assume role in. This way leaked credentials by somehow reading/outputting the file require a malicious user to compromise some other aspect of your account (if locked down by account number only), or execute remote code execution inside your lambda itself (if locked to lambda).... Though, at that point, your credentials are already available to the malicious user to use anyways.
answers question: http://stackoverflow.com/q/49133225
type: Answer
upvote count: 1
score: 1

http://stackoverflow.com/q/49268470
has body: I am using tkinter to create a small GUI for some Python scripts. For this GUI I need a Combobox named combo with three options: "none" (the user wants to hand in no data) "constant" (the user wants to hand in only one value) "adjustable" (the user wants to hand in more than one value) Depending on the choice done in combo, a different number of entrys should appear. The first option should show no entry (and delete all "leftover" entrys), the second one should show only one entry and the third one should show two entrys. For me it's no problem to create these entrys but I don't know how to make them disappear. Once they were created they stay until the GUI is closed. I tried something like this: import tkinter as tk master = tk.Tk() var1 = tk.StringVar() var2 = tk.StringVar() def submit(): if choice.get() == "none": # all entry boxes schould disappear entry1.destroy() entry2.destroy() if choice.get() == "constant": # only 1 entry box schould be visible entry1 = tk.Entry(master, textvariable = var1) entry1.grid(column = 0, row = 1) entry2.destroy() if choice.get() == "adjustable": # all entry boxes should be visible entry1 = tk.Entry(master, textvariable = var1) entry1.grid(column = 0, row = 1) entry2 = tk.Entry(master, textvariable = var1) entry2.grid(column = 0, row = 2) choice = tk.StringVar(value = "none") combo = ttk.Combobox(master, textvariable = choice, state = "readonly") combo["values"] = ("none", "constant", "adjustable") combo.grid(column = 0, row = 0) action = tk.Button(master, text = "confirm", command = submit) action.grid(column=1, row=0) master.mainloop() But as I said before, once a entry was created it did not disappear anymore. I also tried entry.grid_forget() insted of entry.destroy() but this also didn't work. I also tryed to declare entry1 and entry1 outside of submit() but then I don't know how to recreate these entrys once they were destroyed.
favorite count: 0
type: Question
tagged with: tkinter
tagged with: tkinter-entry
has answer: http://stackoverflow.com/a/49273607
type: UnansweredQuestion
has title: tkinter: dynamically create and delete entry
has comment: http://stackoverflow.com/comment/85548254
tagged with: python
has comment: http://stackoverflow.com/comment/85548212
downvote count: 0
has comment: http://stackoverflow.com/comment/85540526
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85540602
answer count: 1
has comment: http://stackoverflow.com/comment/85540684

http://stackoverflow.com/a/49250415
has comment: http://stackoverflow.com/comment/85504515
type: Answer
has body: You can split your strings using list comprehension. Then you can get the 2D array using np.asarray() as x = np.asarray(['2012-09-01_00:00:00', '2012-09-01_01:00:00', '2012-09-01_02:00:00', '2012-09-01_03:00:00', '2012-09-01_04:00:00', '2012-09-01_05:00:00', '2012-09-01_06:00:00', '2012-09-01_07:00:00', '2012-09-01_08:00:00', '2012-09-01_09:00:00', '2012-09-01_10:00:00', '2012-09-01_11:00:00', '2012-09-01_12:00:00', '2012-09-01_13:00:00', '2012-09-01_14:00:00', '2012-09-01_15:00:00', '2012-09-01_16:00:00', '2012-09-01_17:00:00', '2012-09-01_18:00:00', '2012-09-01_19:00:00', '2012-09-01_20:00:00', '2012-09-01_21:00:00', '2012-09-01_22:00:00', '2012-09-01_23:00:00']) temp = [] for i in x: temp.append([j for j in i]) np.asarray(temp, dtype = 'S1') Or in a very concise way you can do temp = [[j for j in i] for i in x] temp = np.asarray(temp, dtype = 'S1')
has comment: http://stackoverflow.com/comment/85504619
score: 0
has comment: http://stackoverflow.com/comment/85504617
has comment: http://stackoverflow.com/comment/85504546
answers question: http://stackoverflow.com/q/49250239
has comment: http://stackoverflow.com/comment/85504647
has comment: http://stackoverflow.com/comment/85504422

http://stackoverflow.com/comment/85404251
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49196121
type: Comment
has text: Does this help?

http://stackoverflow.com/comment/85347138
type: Comment
score: 3
comment on: http://stackoverflow.com/q/49170296
type: QuestionComment
has text: The importance is also normalised if you look at the [source code](https://github.com/scikit-learn/scikit-learn/blob/a24c8b464d094d2c468a16ea9f8bf8d42d949f84/sklearn/tree/_tree.pyx#L1056-L1092). The normalisation is done in such a way that the sum of the output would be equal to 1. You can also see the other details about computation there.

http://stackoverflow.com/comment/85419600
has text: your are right, but actually my output is different let me re frame the keys and values so that it will be more understandable
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49204086
type: Comment

http://stackoverflow.com/comment/86143776
comment on: http://stackoverflow.com/q/49218685
score: 1
type: Comment
type: QuestionComment
has text: Would you mind being more specific ? I'm having the same issue right now.

http://stackoverflow.com/comment/85512496
type: QuestionComment
score: 0
has text: Hi jezrael! I tried it and it wasn't working as I wanted, but I was running out of time so I had to use a completely different solution for my problem and I didn't have the chance to investigate further, I'm sorry :(
type: Comment
comment on: http://stackoverflow.com/q/49223196

tkinter
tags question: http://stackoverflow.com/q/49235995
tags question: http://stackoverflow.com/q/49168368
tags question: http://stackoverflow.com/q/49278446
tags question: http://stackoverflow.com/q/49238255
tags question: http://stackoverflow.com/q/49240453
tags question: http://stackoverflow.com/q/49184422
tags question: http://stackoverflow.com/q/49186678
tags question: http://stackoverflow.com/q/49232866
tags question: http://stackoverflow.com/q/49252844
tags question: http://stackoverflow.com/q/49274091
tags question: http://stackoverflow.com/q/49242870
tags question: http://stackoverflow.com/q/49169770
tags question: http://stackoverflow.com/q/49217783
tags question: http://stackoverflow.com/q/49216840
tags question: http://stackoverflow.com/q/49271832
tags question: http://stackoverflow.com/q/49143267
tags question: http://stackoverflow.com/q/49153502
tags question: http://stackoverflow.com/q/49185727
tags question: http://stackoverflow.com/q/49245807
tags question: http://stackoverflow.com/q/49180625
tags question: http://stackoverflow.com/q/49190088
tags question: http://stackoverflow.com/q/49215029
tags question: http://stackoverflow.com/q/49247317
tags question: http://stackoverflow.com/q/49204792
tags question: http://stackoverflow.com/q/49212790
tags question: http://stackoverflow.com/q/49209024
tags question: http://stackoverflow.com/q/49197002
tags question: http://stackoverflow.com/q/49164192
tags question: http://stackoverflow.com/q/49221919
tags question: http://stackoverflow.com/q/49207285
tags question: http://stackoverflow.com/q/49167324
tags question: http://stackoverflow.com/q/49240711
tags question: http://stackoverflow.com/q/49268470
tags question: http://stackoverflow.com/q/49249731
tags question: http://stackoverflow.com/q/49163239
tags question: http://stackoverflow.com/q/49258049
tags question: http://stackoverflow.com/q/49255916
tag name: tkinter
tags question: http://stackoverflow.com/q/49247669
tags question: http://stackoverflow.com/q/49210445
tags question: http://stackoverflow.com/q/49139315
tags question: http://stackoverflow.com/q/49277758
tags question: http://stackoverflow.com/q/49171900
tags question: http://stackoverflow.com/q/49240800
tags question: http://stackoverflow.com/q/49233188
tags question: http://stackoverflow.com/q/49258892
tags question: http://stackoverflow.com/q/49216249
tags question: http://stackoverflow.com/q/49216348
tags question: http://stackoverflow.com/q/49195601
tags question: http://stackoverflow.com/q/49136816
tags question: http://stackoverflow.com/q/49230658
tags question: http://stackoverflow.com/q/49225485
tags question: http://stackoverflow.com/q/49269755
tags question: http://stackoverflow.com/q/49262065
tags question: http://stackoverflow.com/q/49185074
tags question: http://stackoverflow.com/q/49134554
tags question: http://stackoverflow.com/q/49178434
tags question: http://stackoverflow.com/q/49239261
tags question: http://stackoverflow.com/q/49210436
tags question: http://stackoverflow.com/q/49224477
tags question: http://stackoverflow.com/q/49165440
tags question: http://stackoverflow.com/q/49177369
tags question: http://stackoverflow.com/q/49263301
tags question: http://stackoverflow.com/q/49148421
tags question: http://stackoverflow.com/q/49153332
tags question: http://stackoverflow.com/q/49177714
tags question: http://stackoverflow.com/q/49168198
tags question: http://stackoverflow.com/q/49236770
tags question: http://stackoverflow.com/q/49269976
tags question: http://stackoverflow.com/q/49221151
tags question: http://stackoverflow.com/q/49205178
tags question: http://stackoverflow.com/q/49158825
tags question: http://stackoverflow.com/q/49121492
tags question: http://stackoverflow.com/q/49195002
tags question: http://stackoverflow.com/q/49168695
tags question: http://stackoverflow.com/q/49207769
tags question: http://stackoverflow.com/q/49155875
tags question: http://stackoverflow.com/q/49248023
tags question: http://stackoverflow.com/q/49122104
tags question: http://stackoverflow.com/q/49236631

http://stackoverflow.com/comment/85274431
type: Comment
type: QuestionComment
has text: Check whether the location of tkinter is within your `$PYTHONPATH` or `sys.path`
score: 0
comment on: http://stackoverflow.com/q/49134554

http://stackoverflow.com/comment/85314177
has text: Remember, _PEP8 is only a guide_. Yes, it's the official Python code formatting guide, but it's still only a guide, not a hard and fast rule. Sometimes you may want to use a different style, and that's fine. The most important thing is being consistent. Note here I'm not saying you _should_ use wildcard `import`s - I still don't think you should - I'm simply saying be carful about how rigidly you follow PEP8.
comment on: http://stackoverflow.com/q/49154758
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/49252280
tagged with: python
has answer: http://stackoverflow.com/a/49252568
has title: open html in python: urllib.error.URLError: <urlopen error no host given>
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49252561
tagged with: nginx
has answer: http://stackoverflow.com/a/49252561
has comment: http://stackoverflow.com/comment/85508414
possible better answer: http://stackoverflow.com/a/49252568
type: Question
answer count: 2
has body: I have written a program on python to open a html-file in the browser if a button has been clicked. Unfortunatelly the file can be open manually in the browser via the nginx server typing in the url but not by the program. I do just get the following Error: urllib.error.URLError: &lt;urlopen error no host given&gt; Here are my files: GUI.py: import tkinter as tk import tkinter.ttk as ttk import urllib.request as r class MainWindow(ttk.Frame): def __init__(self, parent): self.parent = parent ttk.Frame.__init__(self, master=self.parent) self.parent.grab_set() self.parent.title("Test Data Tool") self.parent.geometry("500x500") ttk.Button(self.parent, text="Show HTML", command=self.show_html).pack() def show_html(self): r.urlopen("localhost//my_html") nginx.conf: worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; server { listen 80; server_name localhost; location / { root html; index index.html index.htm; } location /Home { alias D:/z003e42d; index test.html; } location /my_html { alias D:/z003e42d/location/of/myHtml; index My.html; # CORS config for nginx if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; # # Custom headers and headers various browsers *should* be OK with but aren't # add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; # # Tell client that this pre-flight info is valid for 20 days # add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-…

http://stackoverflow.com/q/49226370
has answer: http://stackoverflow.com/a/49226917
answer count: 2
upvote count: 0
accepted answer: http://stackoverflow.com/a/49226698
tagged with: multithreading
has comment: http://stackoverflow.com/comment/85456788
tagged with: python
has answer: http://stackoverflow.com/a/49226698
score: -1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85456774
has comment: http://stackoverflow.com/comment/85456964
has body: So i wrote a function that collects a list of files in a directory. These are cut in to sizes of 4 and fed to a multiprocess pool using a for loop. Below is the code for clairity. def Main(): allft_files = listdir(path_allft) ncores = cpu_count() start = datetime.datetime.now() for i in range(0, len(allft_files ), ncores): chuncks = [allft_files[x:x + 1] for x in range(i, i+4, 1)] pool_processes = Pool(processes=ncores) pool_processes.map(filter_allft, chuncks) My question is if all processes are completed and joined before the next iteration starts. Or does the script jump to the next iteration in the for loop when one of the processes finishes. Because processing time for each proces is slightly different. Im not really sure how pool works in that aspect.
downvote count: 1
possible better answer: http://stackoverflow.com/a/49226917
has title: initiating multiprocesses Pool in a for loop in python
favorite count: 0
tagged with: multiprocessing
type: Question

http://stackoverflow.com/a/49135298
score: 2
has comment: http://stackoverflow.com/comment/100516831
upvote count: 2
answers question: http://stackoverflow.com/q/49134634
downvote count: 0
has body: So I'm not sure the radius that you want your circle in your map, but this code will draw you a circle polygon on top of your map m: from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt from matplotlib.patches import Circle m = Basemap(projection="mill", #miller est une projection connu llcrnrlat =0,#lower left corner latitude llcrnrlon =0, urcrnrlat =10, #upper right lat urcrnrlon =10, resolution = "l") #c croud par defaut, l low , h high , f full For the circle here, I just arbitrarily chose a radius of 1/3 the entire length of your y-axis... circle = Circle(xy=m(5,5),radius=(m.ymax - m.ymin) / 3, fill=False) plt.gca().add_patch(circle) m.drawcoastlines() #dessiner les lignes m.drawcountries() m.drawstates() plt.show()
type: Answer

http://stackoverflow.com/q/49184106
has comment: http://stackoverflow.com/comment/85383631
linked to: http://stackoverflow.com/q/8253978
tagged with: flask-sqlalchemy
tagged with: sqlalchemy
favorite count: 0
type: Question
has body: I have the following SQLAlchemy Model: class MyObject2(db.Model, Timestamp): id = db.Column(UUIDType(binary=False), nullable=False, primary_key=True) myobj1_id = db.Column(UUIDType(binary=False), db.ForeignKey(MyObject1.id), nullable=False) name = db.Column(db.String(25)) def __init__(self, myobj1_id, name=None): self.id = uuid.uuid4() self.myobj1_id = myobj1_id self.name = name @classmethod def create(cls, myobj1, name=None): try: myobj2 = cls(myobj1_id=myobj1.id, name=name) db.session.add(myobj2) db.session.commit() print myobj2 #&lt;=========== LOOK AT THIS LINE! return myobj2 except Exception: db.session.rollback() raise finally: db.session.close() Notice that there is an extraneous print statement in there. See? It doesn't really do anything. Oh well. Now, here is the code that calls the create() method to create an instance of the model: myobj2 = MyObject2.create(myobj1=myobj1, name='Hello') serialized_myobj_2 = MyObject2Serializer(myobj2).data All this works fine. But as soon as I remove the unnecessary print statement, I get the following error in the last line of the caller: Instance &lt;MyObject2 at 0x7ff804ac5710&gt; is not bound to a Session; attribute refresh operation cannot proceed Why? How does the absence of the print statement cause this bug? When I googled around for this error, I found this post. But the solution given there -- to call session.expunge_all() right beforesession.close()` -- didn't work for me. What's the solution to getting rid of that print statement without breaking my code?
answer count: 0
has comment: http://stackoverflow.com/comment/85403078
upvote count: 2
duplicate of: http://stackoverflow.com/q/8253978
type: UnansweredQuestion
downvote count: 0
has title: Python SQLAlchemy Error: Instance is not bound to a Session; attribute refresh operation cannot proceed
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/93478246
tagged with: orm

http://stackoverflow.com/comment/85297618
comment on: http://stackoverflow.com/q/49146308
score: 0
has text: you can check similar discussion [here](https://stackoverflow.com/questions/26998687/calling-a-net-function-in-python-which-has-a-reference-parameter)
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85292173
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49142898
has text: AMAZING! Thanks @nitred, that solved the problem. =D
type: Comment

http://stackoverflow.com/comment/85306168
type: AnswerComment
comment on: http://stackoverflow.com/a/49147901
score: 0
has text: This is what I get : https://gist.github.com/beginner007/6bf7a4c00693067ff580bd4ad4da7e50
type: Comment

http://stackoverflow.com/a/49193639
score: 6
upvote count: 6
has comment: http://stackoverflow.com/comment/85392098
has body: Because your __new__ method returns None for any word with no space in it. Probably you want to unindent the return statement. You can even see this problem in your console output -- when you try len(Word('zhiying')) you get an error about NoneType.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49193553

http://stackoverflow.com/q/49213751
has answer: http://stackoverflow.com/a/49214023
tagged with: nan
type: Question
answer count: 1
has body: I have a problem selecting with loc the frames that have NaN values. This is the function that I use. def replace_nan(df, di): df.fillna(-1, inplace=True) for key, value in di.items(): df.loc[ (df["meter_id"]==key) &amp; (df["Values"]== np.nan), "Values"]=value return df I already check that the NaN values are np.nan values, in this case I need to replace all NaN values in Values column and having in mind some categories in other column meter_id. I want to know how to deal with that without replace the nan, because my solution was replace the nan with -1, also change the condition df["Values"]== -1 and the functon works without problem.
has title: Complex selecting with nan values
type: AnsweredQuestion
score: 0
tagged with: select
accepted answer: http://stackoverflow.com/a/49214023
tagged with: dataframe
tagged with: python

http://stackoverflow.com/a/49170411
downvote count: 0
answers question: http://stackoverflow.com/q/49169982
has body: You could define a class to hold your objects data and have a list of class objects like this. This way you could easily add extra fields to your object import random class Food: def __init__(self, name, type): self.name = name self.type = type foods = [Food('carrot', 'vegetable'), Food('apple', 'fruit'), Food('steak', 'meat')] random_food = random.choice(foods) print(random_food.name) print(random_food.type)
type: Answer
has comment: http://stackoverflow.com/comment/85345969
score: 2
upvote count: 2

http://stackoverflow.com/q/49175216
favorite count: 0
has comment: http://stackoverflow.com/comment/85377944
type: Question
has body: I want to write a gdb python script to pasrse a class. but I cannot get the type after c++ static_cast. original type class { ... private: __iter_pointer&amp; __begin_node() _NOEXCEPT {return __begin_node_;} __iter_pointer __begin_node_; ... } In other place, cast a __begin_node to a __node_pointer, and then using a data member __value_ in __node_pointer. __node_pointer __cache = static_cast&lt;__node_pointer&gt;(__begin_node()); __cache-&gt;__value_ = _VSTD::move(__t.remove(__t.begin())-&gt;__value_); the python code is: def children(self): begin = self.val['__tree_']['__begin_node_'] nodetype = begin.type size = self.val['__tree_']['__pair3_']['__first_'] fmt = lambda count,value : ('[%s]' % value['first'], value['second']) return CxxRbTreeIterator(nodetype, begin, size, fmt) hear we get a nodetype which is the type of '__begin_node',i.e. '__iter_pointer', and then we forward it to CxxRbTreeIterator. ................. In CxxRbTreeIterator, def __next__(self): count = self.count self.count = self.count + 1 if count == self.size: raise StopIteration value_ptr = self.begin.cast(self.nodetype) value = value_ptr.dereference()['__value_'] self.begin = self.get_next_node(self.begin) return self.fmt(count, value) here, value_ptr get a __iter_pointer type, and then value want to get its' member __value_, but __value_ is a member of __node_pointer rather than __iter_pointer. So python got a error, there is no member __value_.
has comment: http://stackoverflow.com/comment/85357191
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85376338
has comment: http://stackoverflow.com/comment/85359685
has title: How to get the cast type of a value after static_cast in gdb python script
tagged with: python
has comment: http://stackoverflow.com/comment/85376007
tagged with: c++
answer count: 0
tagged with: static-cast
tagged with: gdb
score: 1
has comment: http://stackoverflow.com/comment/85355834
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49158983
tagged with: python
tagged with: vectorization
has comment: http://stackoverflow.com/comment/85324164
has comment: http://stackoverflow.com/comment/85326628
type: AnsweredQuestion
answer count: 3
tagged with: pandas
has body: "Motelling" is a way to smooth response to a signal. For example: Given a time-varying signal St that takes integer values 1-5, and a response function Ft({S0...t}) that assigns [-1, 0, +1] to each signal, a standard motelling response function would return: -1 if St = 1, or if (St = 2) &amp; (Ft-1 = -1) +1 if St = 5, or if (St = 4) &amp; (Ft-1 = +1) 0 otherwise If I have a DataFrame by time of the signal {S}, is there a vectorized way to apply this motelling function? E.g., if DataFrame df['S'].values = [1, 2, 2, 2, 3, 5, 3, 4, 1] then is there a vectorized approach that would produce: df['F'].values = [-1, -1, -1, -1, 0, 1, 0, 0, -1] Or, absent a vectorized solution, is there something obviously faster than the following DataFrame.itertuples() approach I am using now? df = pd.DataFrame(np.random.random_integers(1,5,100000), columns=['S']) # First set response for time t df['F'] = np.where(df['S'] == 5, 1, np.where(df['S'] == 1, -1, 0)) # Now loop to apply motelling previousF = 0 for row in df.itertuples(): df.at[row.Index, 'F'] = np.where((row.S &gt;= 4) &amp; (previousF == 1), 1, np.where((row.S &lt;= 2) &amp; (previousF == -1), -1, row.F)) previousF = row.F With a complex DataFrame the loop portion takes O(minute per million rows)!
has answer: http://stackoverflow.com/a/49160744
score: 1
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/49198751
has answer: http://stackoverflow.com/a/49198751
has comment: http://stackoverflow.com/comment/85325250
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85376721
has answer: http://stackoverflow.com/a/49185622
linked to: http://stackoverflow.com/q/27367834
has comment: http://stackoverflow.com/comment/85324931
possible better answer: http://stackoverflow.com/a/49160744
has title: Can motelling be vectorized in pandas?
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85350465
type: AnswerComment
comment on: http://stackoverflow.com/a/49171951
type: Comment
has text: @Prayuktibid - Glad can help!
score: 0

http://stackoverflow.com/comment/85384259
comment on: http://stackoverflow.com/a/49189024
type: AnswerComment
score: 0
type: Comment
has text: Thanks, two remarks: 1) type of `a = F.max(df['p_efc_dtm']).over(ws)` is `pyspark.sql.column.Column`, which was a bit misleading. I thought it is a reference to a column then. 2) Is there any way I can see the `number` column along with the `dtm` values? I wonder if `a = df.select([F.max(df['p_efc_dtm']).over(ws), 'number'])` returns the corresponding number to the `dtm` value.

http://stackoverflow.com/q/49211426
score: 0
has comment: http://stackoverflow.com/comment/85427235
tagged with: python
has comment: http://stackoverflow.com/comment/85427228
has body: I have been trying sseveral differnet ways to get a price value from a page using this code: import requests headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "Accept_Encoding": "gzip, deflate, br", "Accept_Language": "en-GB,en-US;q=0.9,en;q=0.8", "Connection": "keep-alive", "Upgrade_Insecure_Requests": "1", "User_Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" } import csv from bs4 import BeautifulSoup #write a CSV file with open("/Users/eezar/Desktop/reverbsolid.csv","w",newline='') as f: writer = csv.writer(f) writer.writerow(["Guitar","Price"]) #get the URL of target page pages=[] for n in range(1,5,1): url=("https://reverb.com/marketplace/electric-guitars/solid-body?page={}".format(n)) #create string for URL r = requests.get(url) # get the HTML parser soup = BeautifulSoup(r.text, "html.parser") [s.extract() for s in soup('sup')] #identify the parent tag/container for the information products = soup.find_all('ul', class_ = 'tiles tiles--four-wide tiles--sidebar-width') #loop through container - give a name for the individual component e.g. title. Text.strip take out the text for title in products: Guitar = soup.find('img', alt=True) Price = soup.find('span',{'class' : 'price-display'}).text.strip() #write each line to the CSV using the loop print(Guitar) writer.writerow ([Guitar,Price]) But I get this error: File "reverbsolid.py", line 32, in &lt;module&gt; Price = soup.find('span',{'class' : 'price-display'}).text.strip() AttributeError: 'NoneType' object has no attribute 'text' I can see the value in text in the page code: &gt; &lt;span class="price-display"&gt;&lt;!-- react-text: 1023 --&gt;$450&lt;!-- &gt; /react-text --&gt;&lt;/span&gt; Don't know what to try next?
has comment: http://stackoverflow.com/comment/85427329
tagged with: attributes
type: Question
has title: AttributeError: 'NoneType' object has no attribute 'text', but text is on page
has comment: http://stackoverflow.com/comment/85427298
has comment: http://stackoverflow.com/comment/85427412
has answer: http://stackoverflow.com/a/61714191
type: UnansweredQuestion
answer count: 1
tagged with: error-handling
has comment: http://stackoverflow.com/comment/85427401
has comment: http://stackoverflow.com/comment/85432891
has comment: http://stackoverflow.com/comment/85427205
has comment: http://stackoverflow.com/comment/85427428
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/85427359
has comment: http://stackoverflow.com/comment/85427234

http://stackoverflow.com/comment/85525883
comment on: http://stackoverflow.com/a/49245730
type: Comment
score: 0
type: AnswerComment
has text: My interface has a few pages with very different layouts (different widgets grouped into a Pile/Frame etc). I'd like to switch between them via keystroke.

http://stackoverflow.com/a/49223179
answers question: http://stackoverflow.com/q/49221770
type: Answer
type: AcceptedAnswer
has body: Solution 1: This is a typical use case for the enumerate() iterator. The idea is to iterate on your list1, and get the corresponding element from list2: list1 = ['a','b','c','d','e'] list2 = ['x','y','z','t','u'] for i, e in enumerate(list1): print(e) # This is your list1 element print(list2[i]) # This is the corresponding list2 element In your specific case, your list1 is ticket_queue[0], and list2 is ticket_queue[1]. Solution 2: Let's reproduce your function: def lists(): return list1,list2 You can zip() together the two lists returned by the function, and iterate on two lists simultaneously. This is an iterator too, just like Solution 1, hence memory-friendly. for one, two in zip(*lists()): print(one) print(two) Let's fit this to your code fully: ticket_queue = get_ticket_queue() for ticket_id, ticket_summary in zip(*ticket_queue): bad_ticket_id = next_steps(ticket_id) if "good" not in bad_ticket_id: print(bad_ticket_id) print(ticket_summary) else: print "good"
downvote count: 0
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49221770

http://stackoverflow.com/q/49226204
tagged with: postgresql
tagged with: python
has body: I have a huge database (~100 variables with a few million rows) consisting of stock data. I managed to connect python with the database via sqlalchemy (postgreql+psycopg2). I am running it all on the cloud. In principle I want to do a few things: 1) Regression of all possible combinations: I am running a simple regression of each stock, i.e. ABC on XYZ AND also XYZ on ABC, this across the n=100 stocks, resulting in n(n+1) / 2 combinations. -> I think of a function that calls in the pairs of stocks, does the two regressions and compares the results and picks one based on some criteria. My question: Is there an efficient way to call in the "factorial"? 2) Rolling Windows: To avoid an overload of data, I thought to only call the dataframe of investigation, i.e. 30days, and then roll over each day, meaning my periods are: 1: 1D-30D 2: 2D-31D and so on Meaning I always drop the first day and add another row at the end of my dataframe. So meaning I have two steps, drop the first day and read in the next row from my database. My question: Is this a meaningful way or does Python has something better in its sleeve? How would you do it? 3) Expanding windows: Instead of dropping the first row and add another one, I keep the 30 days and add another 30days and then run my regression. Problem here, at some point I would embrace all the data which will probably be too big for the memory? My question: What would be a workaround here? 4) As I am running my analysis on the cloud (with a few more cores than my own pc) in fact I could use multithreading, sending "batch" jobs and let Python do things in parallel. I thought of splitting my dataset in 4x 25 stocks and let it run in parallel (so vertical split), or should I better split horizontally? Additionally I am using Jupyter; I am wondering how to best approach here, usually I have a shell script calling my_program.py. Is this the same here?
type: AnsweredQuestion
score: 0
tagged with: pandas
has title: Python+Postgresql: Ideal way to call data for computation (rolling / expanding window) + multithreading?
has comment: http://stackoverflow.com/comment/85456154
has answer: http://stackoverflow.com/a/49235066
accepted answer: http://stackoverflow.com/a/49235066
tagged with: multithreading
answer count: 1
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/a/49244210
answers question: http://stackoverflow.com/q/49244156
score: 0
has comment: http://stackoverflow.com/comment/85898423
has body: A graceful shutdown is just ending the socket session before you shutdown the server. Basically if you add a try catch to the code that handles the keyboard exception, then under that run a socket shutdown, then you're golden. But add code so we can help better. edit - spelling and grammar
has comment: http://stackoverflow.com/comment/85898317
type: Answer

django-forms
tags question: http://stackoverflow.com/q/49147284
tags question: http://stackoverflow.com/q/49125925
tags question: http://stackoverflow.com/q/49258265
tags question: http://stackoverflow.com/q/49139506
tags question: http://stackoverflow.com/q/49156945
tags question: http://stackoverflow.com/q/49162937
tags question: http://stackoverflow.com/q/49124081
tags question: http://stackoverflow.com/q/49131584
tag name: django-forms
type: Tag
tags question: http://stackoverflow.com/q/49251100
tags question: http://stackoverflow.com/q/49263244
tags question: http://stackoverflow.com/q/49125894
tags question: http://stackoverflow.com/q/49165201
tags question: http://stackoverflow.com/q/49270932

http://stackoverflow.com/q/49126007
tagged with: deep-learning
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85257645
has body: I have a small dataset of ~150 images. Each image has an object (rectangle box with white and black color) placed on the floor. The object is same in all images but the pattern of the floor is different. The objective is to train network to find the center of the image. Each image is of dimension 256x256x3. Train_X is of size 150x256x256x3 and Train_y is of size 150x2 (150 here indicates the total number of images) I understand 150 images is too small a dataset, but I am ok giving up on some accuracy so I trained data on Conv nets. Here is the architecture of convnet I used Conv2D layer (filter size of 32) Activation Relu Conv2D layer (filter size of 64) Activation Relu Flattern layer Dense(64) layer Activation Relu Dense(2) Activation Softmax model.compile(loss='mse', optimizer='sgd') Observation: Trained model always return the normalized center of image 0.5,0.5 as the center of 'object' even on the training data. I was hoping to get center of a rectangular object rather than the center of the image when I run predict function on train_X. Am I getting this output because of my conv layer selections?
tagged with: keras
downvote count: 1
has comment: http://stackoverflow.com/comment/85274789
favorite count: 0
has title: Object center detection using Convnet is always returning center of image rather than center of object
has answer: http://stackoverflow.com/a/52918725
answer count: 3
has answer: http://stackoverflow.com/a/57896853
has comment: http://stackoverflow.com/comment/85257617
score: 1
tagged with: python
tagged with: computer-vision
has answer: http://stackoverflow.com/a/63939704
has comment: http://stackoverflow.com/comment/85256759
type: Question
tagged with: conv-neural-network

http://stackoverflow.com/comment/87318187
score: 0
comment on: http://stackoverflow.com/a/49253978
type: Comment
type: AnswerComment
has text: Good day, @nolw38! I hope your coding is progressing fine. Please do not forget to upvote / choose the answer I've provided if it helped you :)

http://stackoverflow.com/a/49168341
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49167655
has body: This is provided inbuilt in spacy. Do a dependency parsing using any spacy model. See the parse tree here ( do remember to switch off punctuation &amp; phrases flags from the menu) https://demos.explosion.ai/displacy/?text=Photos%20under%20low%20lighting%20are%20poor%2C%20both%20front%20and%20back%20cameras.&amp;model=en_core_web_sm&amp;cpu=0&amp;cph=0 The parsed information in the tokens would have dep ( string ) and dep_ (numeric ) attributes, which you can use to determine what adjective is being used for a noun. The information that a particular token is a noun can be had using pos attribute of the token. &gt;&gt;&gt; import spacy &gt;&gt;&gt; nlp = spacy.load('en') &gt;&gt;&gt; parsed = nlp(u"Photos under low lighting are poor, both front and back cameras.") &gt;&gt;&gt; print(u'sentence:{0}'.format(parsed.text)) sentence:Photos under low lighting are poor, both front and back cameras. &gt;&gt;&gt; print(u'parsed_sentence_children::{0}'.format([(x.text,x.pos_,x.dep_,[(x.text,x.dep_) for x in list(x.children)]) for x in parsed])) parsed_sentence_children::[(u'Photos', u'NOUN', u'nsubj', [(u'under', u'prep')]), (u'under', u'ADP', u'prep', [(u'lighting', u'pobj')]), (u'low', u'ADJ', u'amod', []), (u'lighting', u'NOUN', u'pobj', [(u'low', u'amod')]), (u'are', u'VERB', u'ROOT', [(u'Photos', u'nsubj'), (u'cameras', u'attr'), (u'.', u'punct')]), (u'poor', u'ADJ', u'amod', []), (u',', u'PUNCT', u'punct', []), (u'both', u'DET', u'preconj', []), (u'front', u'ADJ', u'amod', [(u'both', u'preconj'), (u'and', u'cc'), (u'back', u'conj')]), (u'and', u'CCONJ', u'cc', []), (u'back', u'ADJ', u'conj', []), (u'cameras', u'NOUN', u'attr', [(u'poor', u'amod'), (u',', u'punct'), (u'front', u'amod')]), (u'.', u'PUNCT', u'punct', [])] &gt;&gt;&gt; print(u'parsed_sentence_ancestors::{0}'.format([(x.text,x.pos_,x.dep_,[(x.text,x.dep_) for x in list(x.ancestors)]) for x in parsed])) parsed_sentence_ancestors::[(u'Photos', u'NOUN', u'nsubj', [(u'are', u'ROOT')]), (u'under', u'ADP', u'prep',…

http://stackoverflow.com/q/49132429
upvote count: 1
has answer: http://stackoverflow.com/a/49166814
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49166814
score: 1
tagged with: python
has title: Can't load data from uproot in Python
tagged with: uproot
type: AnsweredQuestion
tagged with: python-3.x
has body: I am trying to load a Higgs Boson dataset from uproot. I am not comfortable with the use of uproot and the .root data type. I am using the following code which is a sort of official instructions to load the library. I have made a virtual environment and installed the necessary libraries import oamap.source.root import uproot events = uproot.open("http://scikit-hep.org/uproot/examples/HZZ.root")["events"].oamap() I am getting the following error while running the above sample code. Traceback (most recent call last): File "main.py", line 4, in &lt;module&gt; events = uproot.open("http://scikit-hep.org/uproot/examples/HZZ.root")["events"].oamap() File "/home/akash/DIANAhep/lib/python3.5/site-packages/oamap/source/root.py", line 187, in __call__ generator = self.schema.generator() File "/home/akash/DIANAhep/lib/python3.5/site-packages/oamap/source/root.py", line 184, in schema return oamap.schema.List(recurse(self.tree), starts="", stops="") File "/home/akash/DIANAhep/lib/python3.5/site-packages/oamap/source/root.py", line 138, in recurse x = frominterp(name, branch, uproot.interp.auto.interpret(branch)) File "/home/akash/DIANAhep/lib/python3.5/site-packages/oamap/source/root.py", line 100, in frominterp return oamap.schema.Primitive(interpretation.todtype, data=name) File "/home/akash/DIANAhep/lib/python3.5/site-packages/oamap/schema.py", line 346, in __init__ self.data = data File "/home/akash/DIANAhep/lib/python3.5/site-packages/oamap/schema.py", line 418, in data raise TypeError("data must be None or an array name (string), not {0}".format(repr(value))) TypeError: data must be None or an array name (string), not b'NJet' I am novice in these sort of loading dataset.
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/85378129
has text: @jasonharper or account for them moving forward, but going backwards seems more elegant (which is a funny thought).
type: Comment
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/49186232

http://stackoverflow.com/comment/85399498
type: QuestionComment
comment on: http://stackoverflow.com/q/49197280
type: Comment
has text: txt files are *plain text*. They don't support colour or any other kind of formatting. The `ESC[` characters are called control sequences and instruct the terminal to print the text in different colours.
score: 1

http://stackoverflow.com/q/49140860
has comment: http://stackoverflow.com/comment/85287453
has title: Dice roller having issues with second while loop
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85289600
possible better answer: http://stackoverflow.com/a/49141725
accepted answer: http://stackoverflow.com/a/49140947
type: AnsweredQuestion
has body: I'm a longterm lurker first time questioner. I'm trying to teach myself Python and while I've researched my question I couldn't find an answer. My below code runs if I remove the first While loop but currently it doesn't seem to enter the second while loop. I think I might be channelling my inner VBA which I use at work and this is only second time I've tried Python. I've tried changing the first while so it isn't just while true and tried variants on the second while. The intent here is to investigate a dice pool mechanic for a game I'm thinking of and model rolling multiple D6s, 5-6 explode, 3+ successes and 1-2 failures. Ultimately I want it to run roll the dice return the dice list number of successes etc and then reset asking the user for number of dice to roll again. import random Scount = 0 Xcount = 0 Fcount = 0 rollcount = 0 cheat = 0 NoOfDice = 1 Dicelist = [] while True: print ("Input number of dice to roll") NoOfDice=input() while cheat&lt;int(NoOfDice): rand = random.randint(1, 6) Dicelist.append(rand) if rand &lt;= 4: cheat += 1 if rand &gt;= 3: Scount += 1 if rand &gt;= 2: Fcount += 1 if rand &lt;= 5: Xcount += 1 print (Dicelist) print ("We rolled " + str(NoOfDice) + " you got " + str(Scount) + " number of succeses with " + str(Xcount) + " number of dice exploded with " + str(Fcount) + " dice failed") Thank you all and appreciate your time!
has answer: http://stackoverflow.com/a/49141725
has answer: http://stackoverflow.com/a/49140947
score: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/85332074
type: Question
has comment: http://stackoverflow.com/comment/85287217
has comment: http://stackoverflow.com/comment/90483843
answer count: 2

http://stackoverflow.com/comment/85420492
comment on: http://stackoverflow.com/q/49207552
has text: Do you recommend my using a parser on original_tweet and then applying your encode and decode code to that?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49210590
tagged with: python
has answer: http://stackoverflow.com/a/54582878
has title: Django: save() got an unexpected keyword argument 'commit'
has comment: http://stackoverflow.com/comment/85425657
score: 0
has comment: http://stackoverflow.com/comment/85425720
answer count: 2
has answer: http://stackoverflow.com/a/49210650
tagged with: django
has comment: http://stackoverflow.com/comment/85425634
type: Question
has body: In my forms.py I have a custom ModelForm that contains a save() method: def save(self): bus = super().save(commit=False) datei = self.upload.name original_dateiname = datei.name extension = original_dateiname.split('.')[-1] a = Datei.objects.create(file=datei, original_dateiname=original_dateiname, extension=extension) self.datei = a bus.save() return bus However, now I get the error: save() got an unexpected keyword argument 'commit' What's wrong here?
type: UnansweredQuestion

http://stackoverflow.com/comment/85514874
score: 1
comment on: http://stackoverflow.com/q/49255916
type: QuestionComment
has text: That doesn't help explain what you've tried. And that post you linked to doesn't answer your question?
type: Comment

http://stackoverflow.com/q/49266428
answer count: 1
accepted answer: http://stackoverflow.com/a/49266529
tagged with: python
favorite count: 0
score: 9
type: Question
upvote count: 9
has answer: http://stackoverflow.com/a/49266529
has body: I have a Pandas DataFrame, df, that has a price column and a year column. I want to create a boxplot after grouping the rows based on their year. Here's an example: import pandas as pd temp = pd.DataFrame({"year":[2011, 2011, 2011, 2011, 2012, 2012, 2012, 2012, 2013, 2013, 2013, 2013, 2013], "price":[190, 270, 330, 225, 138, 92, 76, 190, 110, 140, 160, 180, 170]}) price year 0 190 2011 1 270 2011 2 330 2011 3 225 2011 4 138 2012 5 92 2012 6 76 2012 7 190 2012 8 110 2013 9 140 2013 10 160 2013 11 180 2013 12 170 2013 So in this case, I'd want a boxplot for each of 2011, 2012, and 2013 based on their price column. I've looked into DataFrame.groupby but it produces a different object (a group by object).
type: AnsweredQuestion
downvote count: 0
tagged with: pandas
has title: Create Boxplot Grouped By Column
tagged with: boxplot

http://stackoverflow.com/comment/85302743
score: 0
type: Comment
type: QuestionComment
has text: Are you able to do that _Manually_ ?
comment on: http://stackoverflow.com/q/49148607

http://stackoverflow.com/q/49239645
has comment: http://stackoverflow.com/comment/85483232
has title: Remove `NaN` from Pandas Dataframe by Group
has body: I have a Dataframe that looks like this: value attribute1 attribute2 attribute3 attribute4 value1 NaN NaN foo NaN value1 bar NaN NaN NaN value1 NaN baz NaN NaN value1 NaN NaN NaN boo I am trying to find a way to condense the frame so that it looks more like this: value attribute1 attribute2 attribute3 attribute4 value1 bar baz foo boo I have not been able to find any specific solutions that will allow me to do this.
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49239867
possible better answer: http://stackoverflow.com/a/49239867
downvote count: 0
has answer: http://stackoverflow.com/a/49239694
accepted answer: http://stackoverflow.com/a/49239694
favorite count: 0
type: AnsweredQuestion
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/85483583
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/49239901
tagged with: python

http://stackoverflow.com/comment/85430304
has text: No language made in the last 20 years has mutable strings. Look into why. Better yet, go program in C and find out why.
comment on: http://stackoverflow.com/q/49212926
type: Comment
type: QuestionComment
score: 3

http://stackoverflow.com/comment/85423127
comment on: http://stackoverflow.com/a/49204887
type: Comment
score: 0
has text: A little help @theGtknerd. Could you tell me how could I make changes to my code to achieve the desired results? I am a noob and it's turning out to be a difficult for me Also I wanted to ask if it was necessary to have more than 2 stack children?
type: AnswerComment

http://stackoverflow.com/q/49238359
tagged with: pytz
has body: Given a timestamp without time zone (e.g. 2018-03-12 09:30:00) AND the timezone EST5EDT, the goal is to parse the data returning a datetime object that is time zone AND daylight saving aware. from datetime import datetime import pytz datetime(2018, 3, 8, 9, 30, tzinfo=pytz.timezone('EST5EDT')).astimezone(pytz.utc) # returns: # datetime.datetime(2018, 3, 8, 14, 30, tzinfo=&lt;UTC&gt;) datetime(2018, 3, 12, 9, 30, tzinfo=pytz.timezone('EST5EDT')).astimezone(pytz.utc) # returns: # datetime.datetime(2018, 3, 12, 14, 30, tzinfo=&lt;UTC&gt;) # BUT should return (second Sunday of march the daylight saving changes by 1 hour): # datetime.datetime(2018, 3, 12, 13, 30, tzinfo=&lt;UTC&gt;)
type: AnsweredQuestion
score: 0
answer count: 1
type: Question
tagged with: timezone
tagged with: datetime
accepted answer: http://stackoverflow.com/a/49238535
tagged with: python
has title: Daylight time saving aware conversion of timestamps in python
has answer: http://stackoverflow.com/a/49238535

http://stackoverflow.com/comment/85525157
has text: It says you need to install mpg123.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49255972
type: Comment

http://stackoverflow.com/comment/94670879
comment on: http://stackoverflow.com/a/49726448
type: AnswerComment
has text: Very nice notice. last time I did not find this and forced to edit and compile the c source code of Oracle client lib. Thank you!
score: 1
type: Comment

http://stackoverflow.com/q/49205018
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85428465
has comment: http://stackoverflow.com/comment/85416495
tagged with: gspread
has body: I'm teaching myself to code (in the early stages) and I'm trying to log serial data from an arduino to google sheets using pyserial and gspread. Data from the arduino is intermittent (0-10 entries a minute roughly) but so far I can only log the first entry repeatedly. I get that it's doing this because it's looping but I don't know how to fix it. If I were logging to a txt or csv file I could close and reopen the log file but I'm not sure if that makes sense to do with google sheets or how to do it. Can anyone point me in the right direction as to what might be a good way to log each entry only once? Here's the basic meat of my code. Please remember I'm a novice! ser = serial.Serial('/dev/ttyACM0',9600) gc = gspread.authorize(credentials) wks = gc.open("meditation_logger").sheet1 wks.resize(1) data = ser.readline().strip() date = datetime.now().strftime("%m/%d/%y") time = datetime.now().strftime("%H:%M:%S") dataToAdd = [date, time, data] while True: wks = gc.open("meditation_logger").sheet1 if data: print data, date, time wks.append_row(dataToAdd)
tagged with: pyserial
has title: How to log arduino data using pyserial and gspread only once to google sheets
score: 0
tagged with: arduino
answer count: 0
type: Question
tagged with: google-sheets

http://stackoverflow.com/a/49180776
answers question: http://stackoverflow.com/q/49180678
type: Answer
upvote count: 1
downvote count: 1
score: 0
type: AcceptedAnswer
has body: [1-12] doesn't do what you think it does. It matches anything in the range 1 to 1, or it matches a 2. See this question for some replacement regex options, like ([1-9]|1[0-2]): How to represent regex number ranges (e.g. 1 to 12)? If you want an interactive tool for experimenting with regexes, I personally recommend Regexr.
accepted answer of: http://stackoverflow.com/q/49180678
has comment: http://stackoverflow.com/comment/85367121

http://stackoverflow.com/comment/85390034
comment on: http://stackoverflow.com/q/49192522
score: 0
type: Comment
type: QuestionComment
has text: The docs tell you how to get attributes: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#attributes

http://stackoverflow.com/a/49274293
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49268459
accepted answer of: http://stackoverflow.com/q/49268459
type: Answer
score: 0
has body: Firstly, rather than using a tutorial "created a long time ago", you should use the actual tutorial for your Django version. The code you have used in your URLs is neither valid for the old regex-based routing nor for the new-style path routing. The new style is easier, you should probably just use that: path('&lt;int:question_id&gt;/',views.detail, name = "detail")

http://stackoverflow.com/comment/85275864
score: 2
type: AnswerComment
has text: The issue with the code above is that in [tag:python-2.x] neither [tag:ttk] nor `fildialog` are submodules to [tag:tkinter]. Instead there are _separate_ `ttk` and `tkFileDialog` modules which should effectively be the same to those of tkinter for [tag:python-3.x]. TL;DR: Replace `from Tkinter import ttk,filedialog` with `import ttk; import tkFileDialog as filedialog` to have the desired result.
type: Comment
comment on: http://stackoverflow.com/a/49134866

http://stackoverflow.com/comment/104250252
score: 0
has text: I think dynamic DAG is a bad practice in Airflow. On each DAG rendering, all previous DAG runs will be changed. You might lose some history/logs + you can accidentally trigger unneeded execution as tasks in old DAG runs will be added in "no state". If you touch such DAG run they will be triggered.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49139821

http://stackoverflow.com/q/49263052
tagged with: discord.py
has title: Use the start() function for the discord python extention instead of run()
has body: So I've been looking everywhere, but the only way people seemed to run the bots is by using .run(TOKEN). But I'd like to use .start() instead, but don't know how to implement it in the code. Here something very simple it should be able to run: import discord from discord.ext.commands import Bot from discord.ext import commands import asyncio client = discord.Client() client = commands.Bot(command_prefix = '!') client.start(TOKEN) @client.event async def on_ready(): print("Ready") Whenever I run this code I just get 2 Unclosed client sessions right before it closes the program
has comment: http://stackoverflow.com/comment/85529965
tagged with: python
has answer: http://stackoverflow.com/a/49263388
type: AnsweredQuestion
tagged with: bots
score: 1
answer count: 1
downvote count: 0
upvote count: 1
accepted answer: http://stackoverflow.com/a/49263388
tagged with: discord
favorite count: 0
type: Question

http://stackoverflow.com/comment/85553223
comment on: http://stackoverflow.com/a/49221643
score: 0
has text: Is it possible for you to write out the code in Python to facilitate my understanding?
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85480809
score: 0
type: Comment
has text: Thank you! I'll look into that!
type: AnswerComment
comment on: http://stackoverflow.com/a/49229356

http://stackoverflow.com/a/49749123
answers question: http://stackoverflow.com/q/49136867
upvote count: 3
downvote count: 0
has body: Given a networkX graph with weighted edges named G and a bokeh plot object named plot, I propose a more compact form: graph_renderer.edge_renderer.data_source.data["line_width"] = [G.get_edge_data(a,b)['weight'] for a, b in G.edges()] graph_renderer.edge_renderer.glyph.line_width = {'field': 'line_width'} plot.renderers.append(graph_renderer)
type: Answer
score: 3

http://stackoverflow.com/comment/85376807
type: AnswerComment
has text: What does the `.T` do at the end of the command `df.set_index('part number').T`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49185526

http://stackoverflow.com/comment/85348600
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49168338
score: 0
has text: hi nabongs, I have about 6GB of free disk space.

http://stackoverflow.com/comment/85566582
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49280190
type: AnswerComment
has text: I'm sure this method is extendible to more columns, but yes - please post as a new question so we don't divert from your original question.

http://stackoverflow.com/q/49148452
favorite count: 0
has answer: http://stackoverflow.com/a/49149022
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49149022
tagged with: mocking
has title: How to mock side effects in session in Python's request library?
tagged with: python
tagged with: python-requests
score: 2
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/49128015
answer count: 1
has body: This is a followup to a question that I asked yesterday. I am trying to mock a session of the requests library. While I got my answer as to how to mock a successful return value, I am still trying to figure out how to mock side effects such as 400, 401, or 302 etc. This is how I am mocking a session: &gt;&gt;&gt; from unittest import mock &gt;&gt;&gt; import requests, ssl &gt;&gt;&gt; class TlsAdapter: ... # mocked adapter, just for illustration purposes ... def __init__(self, *args, **kwargs): pass ... &gt;&gt;&gt; def _request_url(method, url): ... session = requests.session() ... adapter = TlsAdapter(ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1) ... session.mount("https://", adapter) ... return session.request(method, url) ... &gt;&gt;&gt; with mock.patch('requests.session') as mock_session: ... session_instance = mock_session.return_value ... mock_response = session_instance.request.return_value ... response = _request_url('METHOD', 'some url') ... assert response is mock_response ... session_instance.mount.assert_called() ... session_instance.request.assert_called_with('METHOD', 'some url') Now, as far as I have read, I need to mock session_instance.request.side_effect. If I try to do something like this, it fails: response_redirect = mock.MagicMock() response_redirect.status_code = 302 response_redirect.headers = {"location": "https://absolute"} session_instance.request.side_effect = response_redirect response = _request_url('METHOD', 'https://absolute') self.assertEqual(result, response_redirect) #Assertion error
tagged with: unit-testing

http://stackoverflow.com/comment/99166223
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49162542
has text: I am trying this as I thought this would solve my problem but I get an error saying that ```` 'row_6 ' is not defined ```` (what would've been row_25 in this example). Would you happen to know a way of trouble shooting this?

http://stackoverflow.com/comment/85494203
score: 0
has text: Was my answer useful for you? If you have issues in my answer, feel free to tell me. Such information helps me to study. Also I think that it helps other users to know the situation as an information.
comment on: http://stackoverflow.com/q/49187463
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85392514
comment on: http://stackoverflow.com/q/49193843
type: QuestionComment
has text: I guess :) I also edited my comment above, can you confirm?
type: Comment
score: 0

http://stackoverflow.com/comment/85569641
type: AnswerComment
comment on: http://stackoverflow.com/a/49262664
type: Comment
score: 8
has text: @GiacomoAlzetta: There are people out there relying on `finally` blocks as if they provided transactional guarantees. It might seem obvious that they don't, but it's not something everyone realizes. As for the generator case, there are a lot of ways a generator might not be GC'ed at all, and a lot of ways a generator or coroutine might accidentally yield after `GeneratorExit` even if it doesn't catch the `GeneratorExit`, for example if an `async with` suspends a coroutine in `__exit__`.

http://stackoverflow.com/comment/85371954
comment on: http://stackoverflow.com/q/49182978
has text: Finally, the easiest way to debug an extension module in embedded Python is to pull it out and build it as a stanxdalone extension module (commenting out any bits that depend on the embedding environment). And that has the added bonus of giving you an [mcve](https://stackoverflow.com/help/mcve) that people on StackOverflow can actually help you debug.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49241127
downvote count: 0
has body: Are you looking for something like this: # define these outside the scope of the function x = 10 y = 20 def function(): a = 3; b = 4; c = float(b+a) l = locals() print(", ".join(["{var}: {type}".format(var=v, type=type(l[v])) for v in l])) function() #a: &lt;type 'int'&gt;, c: &lt;type 'float'&gt;, b: &lt;type 'int'&gt;
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49240964
has comment: http://stackoverflow.com/comment/85507512
type: Answer
answers question: http://stackoverflow.com/q/49240964
score: 3
upvote count: 3

http://stackoverflow.com/q/49233359
has answer: http://stackoverflow.com/a/49233762
has title: How to compare two dataframes ignoring column names?
favorite count: 0
has answer: http://stackoverflow.com/a/49233487
score: 3
upvote count: 3
tagged with: pandas
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49233651
type: Question
has body: Suppose I want to compare the content of two dataframes, but not the column names (or index names). Is it possible to achieve this without renaming the columns? For example: df = pd.DataFrame({'A': [1,2], 'B':[3,4]}) df_equal = pd.DataFrame({'a': [1,2], 'b':[3,4]}) df_diff = pd.DataFrame({'A': [1,2], 'B':[3,5]}) In this case, df is df_equal but different to df_diff, because the values in df_equal has the same content, but the ones in df_diff. Notice that the column names in df_equal are different, but I still want to get a true value. I have tried the following: equals: # Returns false because of the column names df.equals(df_equal) eq: # doesn't work as it compares four columns (A,B,a,b) assuming nulls for the one that doesn't exist df.eq(df_equal).all().all() pandas.testing.assert_frame_equal: # same as equals pd.testing.assert_frame_equal(df, df_equal, check_names=False) I thought that it was going to be possible to use the assert_frame_equal, but none of the parameters seem to work to ignore column names.
answer count: 3
downvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/10710328

http://stackoverflow.com/q/49246801
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49248577
score: 1
has answer: http://stackoverflow.com/a/49248577
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
has title: Python XML Data With BeautifulSoup
has body: Ok I'm having trouble filtering out some XML data with Beautiful Soup. Here is the XML data: <ticket> 123456789 <create_date>2017-12-09</create_date> - - <diary_entry> - username - 2017-12-09 - A bunch of text in here a lot of text more text - - </diary_entry> - - <work_log> - <diary_entry> - someotheruser - 2017-12-09 - Some more text in here and other text - - </diary_entry> - </work_log> </ticket I'm trying to get only values in the correspondence/diary_entry/body section, but my code keeps also providing values in the worklog/diary_entry/body section. Here is my current code: ticket_url = "https://somelink/tickets/123456789" r = requests.get(ticket_url, auth=HTTPBasicAuth('username', 'password')) soup = BeautifulSoup(r.content,'xml') updates = soup.findAll('body') for update in updates: if "next steps:" not in update.text.lower(): print "no" print update.text.lower() else: print "yes" I'm not sure how to filter it down to only get the values. Any help is greatly appreciated.
answer count: 1

http://stackoverflow.com/comment/120416758
type: AnswerComment
has text: Getting errors : TypeError: progress_function() missing 2 required positional arguments: 'file_handle' and 'bytes_remaining'
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49241754

http://stackoverflow.com/comment/85538281
has text: And what happens? What error do you see? More importantly, what is the API you are trying to call? As @JulienSpronck suggests, perhaps the API expects a dictionary, not a string representing one. `"remember":1|0` looks highly suspicious as a parameter.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49267392

http://stackoverflow.com/q/49155657
favorite count: 0
type: Question
score: -2
possible better answer: http://stackoverflow.com/a/49155784
tagged with: python
has answer: http://stackoverflow.com/a/49155823
has answer: http://stackoverflow.com/a/49155784
tagged with: class
type: AnsweredQuestion
has title: How to solve "TypeError: tuple indices must be integers or slices" error in Python?
upvote count: 0
tagged with: list
downvote count: 2
tagged with: oop
answer count: 3
has answer: http://stackoverflow.com/a/49155924
has body: I have a student class that takes attributes and has getter and setter methods and a function called getTheFirstInClass() that takes a list of grades and returns the highest grade. But the system display this error: File "C:\Users\test\student.py", line 30, in std1.getTheFirstInClass(2.4,4.2,5.6,2.2,1.2) File "C:\Users\test\student.py", line 20, in getTheFirstInClass if grades[i] > maxValue: builtins.TypeError: tuple indices must be integers or slices, not student student.py: class student(): def __init__(self,name,age, grade): self.stdName=name self.stdAge = age self.stdGrade = grade def getName(self): print("the student name {}".format(self.stdName)) def getAge(self): print("the student age :{}".format(self.stdAge)) def getGrade(self): print("the student {0}, have a grade {1}".format(self.stdName,self.stdGrade)) def getTheFirstInClass(*grades:float): maxValue = 0 for i in grades: if grades[i] &gt; maxValue: maxValue = grades[i] i+=1 return maxValue std1 = student("georges", 17, 3.4) std1.getName() std1.getAge() std1.getGrade() std1.getTheFirstInClass(2.4,4.2,5.6,2.2,1.2)
accepted answer: http://stackoverflow.com/a/49155823

http://stackoverflow.com/comment/85306711
has text: Are you trying to install numpy *while* the matplotlib script is running?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49149312

http://stackoverflow.com/comment/85553789
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49275686
type: QuestionComment
has text: have you tried using pandas?

http://stackoverflow.com/comment/85271069
score: 0
comment on: http://stackoverflow.com/q/49132073
has text: I can't duplicate with the small amount of "data" you gave. Reading a single line containing the line you gave does not cause an error. In general, Pandas is usually smart enough to read the data as 'object' in case there are strings.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49218749
tagged with: ubuntu
linked to: http://stackoverflow.com/q/21150914
favorite count: 0
has title: Python Indicator stops updating after 3 times on Ubuntu
type: Question
type: AnsweredQuestion
score: 1
tagged with: indicator
tagged with: python
tagged with: gtk
has answer: http://stackoverflow.com/a/49222334
has comment: http://stackoverflow.com/comment/85441411
accepted answer: http://stackoverflow.com/a/49222334
downvote count: 0
upvote count: 1
answer count: 1
has body: i am writing an Indicator in Python which should update every 5 minutes. Unfortunately the label is updated only 3 times, but then the label stays the same, although the thread still runs. For demonstration purpose, I replaced the data with the current time. #!/usr/bin/env python3 import signal import gi import threading gi.require_version('Gtk', '3.0') gi.require_version('AppIndicator3', '0.1') from gi.repository import Gtk, AppIndicator3, GObject import time class Indicator(): def __init__(self): self.app = 'turtle-mining-indicator' self.menu = {} self.indicator = AppIndicator3.Indicator.new( self.app, ICON, AppIndicator3.IndicatorCategory.OTHER) self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE) self.indicator.set_menu(self.create_menu()) self.indicator.set_label("Starting ...", self.app) self.scheduler() def update(self): print("update " + time.asctime()) self.indicator.set_label(time.asctime(), self.app) self.menu["first"].set_label("First: " + time.asctime()) def scheduler(self): self.update() self.timer = threading.Timer(3, self.scheduler).start() def create_menu(self): menu = Gtk.Menu() self.menu["first"] = Gtk.MenuItem("First") menu.append(self.menu["first"]) menu.show_all() return menu Indicator() signal.signal(signal.SIGINT, signal.SIG_DFL) Gtk.main() I don't understand, why this happens. The method update() gets executed but the set_label method only works 3 times. What am I doing wrong?

http://stackoverflow.com/q/49218954
has body: I am really unable to find how can I train a svm classifier with text features that are non ordinal and can be any possible string of characters. I am using a labelled dataset like this in a row. Tajmahal | India | 21-08-1990 Now for dates I am using toordinal() function for training but clueless about the feature extraction for strings.
has title: Training svm classifier with non ordinal text features
type: UnansweredQuestion
answer count: 1
tagged with: scikit-learn
type: Question
has comment: http://stackoverflow.com/comment/85442503
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/49219564

http://stackoverflow.com/comment/85454252
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49223707
has text: Yep, it's seems so. Thank you so much. Anyway the answer is definetely more complex than I thought.
score: 0

http://stackoverflow.com/q/49189101
has body: I did a bit of research and it seems that this is the correct code according to Django documentations but for some reason it returns. AttributeError: 'tuple' object has no attribute 'permissions'. DJango groups. Here is the code. admin_group = Group.objects.get_or_create(name='Admin') admin_group.permissions.add( add_token_permission, add_user_detail_permission, change_user_detail_permission, add_user_location_permission, ) admin_group.user_set.add(self.user) admin_group.save()
answer count: 2
has answer: http://stackoverflow.com/a/49189133
downvote count: 0
tagged with: django
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/49189137
favorite count: 0
has answer: http://stackoverflow.com/a/49189137
type: Question
has title: AttributeError: 'tuple' object has no attribute 'permissions'. DJango groups
tagged with: python
possible better answer: http://stackoverflow.com/a/49189133
type: AnsweredQuestion

http://stackoverflow.com/comment/85408912
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49201719
has text: @Kevin Ah, I see what you mean, by "base case", you are referencing the case where `len(lst) == 1`. I have fixed this now :)

http://stackoverflow.com/comment/105197623
type: Comment
comment on: http://stackoverflow.com/a/49212095
score: 0
type: AnswerComment
has text: Maybe you are confusing 'baz' with 'bar'? As I understand the way to do is `d.get('baz', 'default') or 'default'`

http://stackoverflow.com/q/49234219
type: Question
has body: can logging outputs which appear on the terminal be redirected to a text file? I have tried z = open('/mnt/sdc1/Ryan/Marx/newfile.txt'.format(file), 'w') sys.stdout= sys.stderr = z print ('Running the Algoritm Now for case {}'.format(file)) run_liver_mpct_algorithms(data_paths, model_paths,[0], int(data_paths['batch_size']), data_paths['task_str'])) z.close() In th file z This gives me only the traceback of the error and print statements ,inside of the run_liver_mpct_algorithms there are many logging outputs which i would also like to go in the file. Any ideas would be helpful,Thanks !
has comment: http://stackoverflow.com/comment/85472139
has comment: http://stackoverflow.com/comment/85472144
accepted answer: http://stackoverflow.com/a/49234433
answer count: 1
has title: Logging outputs to a text file
tagged with: python
has answer: http://stackoverflow.com/a/49234433
linked to: http://stackoverflow.com/q/19425736
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85471466

http://stackoverflow.com/q/49245954
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49245991
has body: I've been working on this for a while now and it doesn't make a lot of sense to me I have some coordinate data that comes in the form of: "4.970599399999999, 'lng': -1.6918635" The first part is the latitude, and the second the longitude. This is the column: coordinates 4.970599399999999, 'lng': -1.6918635 None 4.5, 'lng': -1.69 4.9705, 'lng': -1.6 None The code i'm using is: data'latitude','longitude' = data['coordinates'].str.split('\,\s\'lng\'\w*\:\s',expand=True) I've used Regexr to confirm that my regex is perfectly fine and splitting on the right delimiter and there isn't a problem there But the error i'm getting is this: "ValueError: Columns must be same length as key" I have experienced this error before and I found it was due to having multiple matches in the string - but these strings are short and simple! It's either 'None' or the coordinates Can anyone help? Thanks a lot
tagged with: python
has title: Python: str.split string returning 'Columns must be same length as key' despite expand=True and no multiple matches for regex in string
tagged with: regex
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85495848
tagged with: pandas
upvote count: 2
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85495764
accepted answer: http://stackoverflow.com/a/49245991

http://stackoverflow.com/q/49270330
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49270474
score: 0
tagged with: raw-input
has title: How do I use raw_input with classes in a definition
tagged with: function
answer count: 1
tagged with: python-2.x
type: Question
has comment: http://stackoverflow.com/comment/85544197
has answer: http://stackoverflow.com/a/49270474
has body: Problem I'm writing a script in Python 2.7 that has the user input the atomic symbol for an element. The script then prints out information about the element. However, I'm not sure how to have a class use a variable from the raw_input. Here is the code with a couple of the 118 elements gone for readability: Code class PTable(object): def __init__(self, name, atom_num, atom_sym, atom_mass,period, group, atom_type,state): self.name = name self.atom_num = atom_num self.atom_sym = atom_sym self.atom_mass = atom_mass self.period = period self.group = group self.atom_type = atom_type self.state = state h = PTable("Hydrogen",1,"H",1.0079,1,1,"Nonmetal","Gas") he = PTable("Helium",2,"He",4.0026,1,18,"Nonmetal","Gas") li = PTable("Lithium",3,"Li",6.941,2,1,"Alkali metal","Solid") be = PTable("Beryllium",4,"Be",9.0121831,2,2,"Alkaline earth","solid") og = PTable("Oganesson",1,"H",1.008,1,1,"Nonmetal","Gas") def results(name, num, sym, mass, per, gro, typ, state): print "Name:", name print "Atomic number:", num print "Atomic symbol:", sym print "Atomic mass:", mass print "Period:", per print "Group:", gro print "Type:", typ print "State:", state # results(h.name, h.atom_num, h.atom_sym, h.atom_mass, h.period, h.group, h.atom_type, h.state) def hub(): x = raw_input("What element? ") results(%s.name, %s.atom_num, %s.atom_sym, %s.atom_mass, %s.period, %s.group, %s.atom_type, %s.state) % (x) hub() hub() Errors The code that gives me the syntax error is: results(%s.name, %s.atom_num, %s.atom_sym, %s.atom_mass, %s.period, %s.group, %s.atom_type, %s.state) % (x) The error is obvious; syntax is wrong, so I tried another way: results(x.name, x.atom_num, x.atom_sym, x.atom_mass, x.period, x.group, x.atom_type, x.state) That, too, did not work, and I got the error Traceback (most recent call last): File "C:/Users/NAME/Desktop/PTable.py", line 146, in hub() File "C:/Users/NAME/Desktop/PTable.py", line 143, in hub results(x.name, x.atom_num, x.atom_sym, x.atom_mass, x.period, x.group, x.at…
has comment: http://stackoverflow.com/comment/85544086
tagged with: python
tagged with: class

http://stackoverflow.com/comment/132293985
score: 0
type: Comment
comment on: http://stackoverflow.com/a/68218389
type: AnswerComment
has text: If you use this with TZ-naive data you get `TypeError: Cannot convert tz-naive timestamps, use tz_localize to localize` If you tz_localize to None it won't convert the TZ-aware data to UTC before it drops the TZ. -- https://pandas.pydata.org/docs/reference/api/pandas.Series.dt.tz_localize.html Neither seem good for mixed TZ-aware and TZ-naive data. (I recently had some TZ-aware data with +00 appended to a set of TZ-naive data in a sqlite3 DB, and the mixed data choked `pd.read_sql_query(...)` )

http://stackoverflow.com/q/49245355
has comment: http://stackoverflow.com/comment/85496046
has body: I'm using the bash shell in Windows 10 which makes everything feel like a unix system and I'm trying to run the following python2.7 code: from selenium import webdriver driver = webdriver.Chrome() However, I get the following error code: Traceback (most recent call last): File "seleniumtest.py", line 3, in &lt;module&gt; driver = webdriver.Chrome() File "/home/eirik/.local/lib/python2.7/sitepackages/selenium/webdriver/chrome/webdriver.py", line 68, in __init__ self.service.start() File "/home/eirik/.local/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 83, in start os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home By googeling I found that this was a quite common problem and that I had to download the chromedriver and specifiy where it was. So I changed the above to this: driver = webdriver.Chrome(executable_path = r'/path/to/chromedriver.exe') But I got the same result. After that I went into Windows Enviroment Variable and made sure that the folder where I put the chromedriver was read as PATH. It was. To check if this PATH was also read by the bash shell, I wrote the following: echo $PATH | tr ":" "\n" | nl In my bash shell. This gave the output: 1 /home/eirik/bin 2 /home/eirik/.local/bin 3 /usr/local/sbin 4 /usr/local/bin 5 /usr/sbin 6 /usr/bin 7 /sbin 8 /bin 9 /usr/games 10 /usr/local/games 11 /mnt/c/webdriver 12 /mnt/c/Program Files (x86)/NVIDIA Corporation/PhysX/Common 13 /mnt/c/ProgramData/Oracle/Java/javapath 14 /mnt/c/Program Files (x86)/Intel/iCLS Client 15 /mnt/c/Program Files/Intel/iCLS Client 16 /mnt/c/Windows/System32 17 /mnt/c/Windows 18 /mnt/c/Windows/System32/wbem 19 /mnt/c/Windows/System32/WindowsPowerShell/v1.0 20 /mnt/c/Program Files (x86)/GtkSharp/2.12/bin 21 /mnt/c/Program Files (x86)/Skype/Phone 22 /mnt/c/Program Files (x86)/Intel/Intel(R) Manag…
tagged with: selenium
has answer: http://stackoverflow.com/a/49257403
tagged with: python-2.x
linked to: http://stackoverflow.com/q/49201281
tagged with: windows-10
has title: chromedriver.exe is in PATH, but selenium gives me an error
has comment: http://stackoverflow.com/comment/85496699
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49255297
has comment: http://stackoverflow.com/comment/85496083
has comment: http://stackoverflow.com/comment/85510302
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85496204
tagged with: python
score: 0
tagged with: bash

http://stackoverflow.com/a/49240645
has body: Be very careful! In Python / float counting, 9.5/10 - 1 == -0.050000000000000044 This is one way to explicitly account for this issue via numpy. import numpy as np vals = np.abs(df.Charge1.values / df.Charge2.values - 1) cond1 = vals &lt;= 0.05 cond2 = np.isclose(vals, 0.05, atol=1e-08) df['Indicator'] = np.where(cond1 | cond2, 'RFP', '')
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49240020
type: Answer

http://stackoverflow.com/q/49143160
has title: Flask-sqlalchemy - Count how many times a REST endpoint(or db record) has been requested
answer count: 2
has body: I am making a flask app which will serve with rest endpoints to the frontend. The website is for browsing guitar chords and tabs. I want to be able to count how many times a chord been requested and store this counter persistently. the endpoint looks like this: /chord/string:chord_id Is it a good idea to add a column to each table and increment this value each time the row is accessed? Is there another way of doing this smoothly? I hope my question is clear. Thanks already!
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85293475
downvote count: 0
favorite count: 0
type: Question
tagged with: rest
has comment: http://stackoverflow.com/comment/85336036
has answer: http://stackoverflow.com/a/49162181
tagged with: python
tagged with: mysql
tagged with: flask-restful
has answer: http://stackoverflow.com/a/49164696
tagged with: sqlalchemy
score: 2

http://stackoverflow.com/comment/85433485
score: 1
type: Comment
has text: You can try to symlink "Dropbox ..." to something without spaces.
type: QuestionComment
comment on: http://stackoverflow.com/q/49214457

http://stackoverflow.com/q/49176833
has comment: http://stackoverflow.com/comment/85359395
score: 0
has answer: http://stackoverflow.com/a/49177017
linked to: http://stackoverflow.com/q/17327202
has answer: http://stackoverflow.com/a/49177106
has body: I'm' trying to convert string to JSON file using the json.dump method. Before the conversion, I need to add escape character before each char that represented as hex for example '\x00' or '\x96'. In the end I need to convert string like: '\x94\xa0aaa' To: '\\x94\\xa0aaa' How can I do it? I tried to use the replace method, but it didn't work.
type: Question
has title: How to add escape char before each hex char? Python
has answer: http://stackoverflow.com/a/49177045
has answer: http://stackoverflow.com/a/49177129
has comment: http://stackoverflow.com/comment/85359432
type: UnansweredQuestion
tagged with: python
tagged with: python-2.7
answer count: 4

http://stackoverflow.com/comment/85354113
has text: Thanks, I guess in "reality" you never need to calculate the derivatives yourself. This is just me trying to check my own implementation of back propagation manually.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49170908

http://stackoverflow.com/comment/85267690
comment on: http://stackoverflow.com/q/49131578
score: 0
type: QuestionComment
has text: The closest you can get is using a ternary: `path = output_directory if output_directory else '.'`
type: Comment

http://stackoverflow.com/comment/103939618
type: Comment
comment on: http://stackoverflow.com/a/58832008
type: AnswerComment
score: 0
has text: improve answer using enumerate

http://stackoverflow.com/q/49163978
has answer: http://stackoverflow.com/a/49164081
has comment: http://stackoverflow.com/comment/85333628
has answer: http://stackoverflow.com/a/49164090
score: 0
tagged with: printing
answer count: 3
tagged with: if-statement
has title: How to find more words in a file at once?
has comment: http://stackoverflow.com/comment/85333590
type: Question
tagged with: find
type: UnansweredQuestion
tagged with: file
has body: In my program I am reading another python program and I want to find some special python keywords. When I find them I want to print out some code in front of that keyword found and after it. This is my code: if line.find("def") == True or line.find("if") == True or line.find("elif") == True: print("",True,""," ", end="") In the print statement "True" I want it to be the value that was read by the program. I don't know if I am doing the "or" statement right but the output is not working. I don't get any error or anything . I expect my output to be the HTML code above and then the keyword found and the closing HTML code. Example Output: if def elif
has answer: http://stackoverflow.com/a/49164056
tagged with: python

http://stackoverflow.com/a/49193454
answers question: http://stackoverflow.com/q/49193164
type: Answer
has comment: http://stackoverflow.com/comment/85391508
score: 0
has body: Your problem with looping was that you are using python2 in your windows cmd. input function is little bit different from python3 version, so try to use raw_input function if you want to run this code with python2: user_guess = raw_input('what is the capital of %s?' % state) see this answer for details
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49193164

http://stackoverflow.com/comment/85311555
has text: Problem solved. Thanks a lot! I had django-cleanup added in my settings.py in installed_apps. I added it along the way but it did not fulfill my requests so I totally forgot about that modul.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49151878
type: QuestionComment

http://stackoverflow.com/q/49204639
has answer: http://stackoverflow.com/a/49205251
upvote count: 9
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85414682
tagged with: python
score: 9
type: AnsweredQuestion
has title: What exactly are the csv module's Dialect settings for excel-tab?
has body: The csv module implements classes to read and write tabular data in CSV format. It allows programmers to say, “write this data in the format preferred by Excel,” or “read data from this file which was generated by Excel,” without knowing the precise details of the CSV format used by Excel. What if I want to know?? All kidding aside, I want to know specifically which attributes and settings would create the dialect csv.excel_tab Dialect.delimiter A one-character string used to separate fields. Dialect.doublequote Controls how instances of quotechar appearing inside a field should themselves be quoted. Dialect.escapechar A one-character string used by the writer to escape the delimiter if quoting is set to QUOTE_NONE and the quotechar if doublequote is False. Dialect.lineterminator The string used to terminate lines produced by the writer. It defaults to '\r\n'. Dialect.quotechar A one-character string used to quote fields containing special characters, such as the delimiter or quotechar, or which contain new-line characters. Dialect.quoting Controls when quotes should be generated by the writer and recognised by the reader. It can take on any of the QUOTE_* constants (see section Module Contents) and defaults to QUOTE_MINIMAL. Dialect.skipinitialspace When True, whitespace immediately following the delimiter is ignored. The default is False. Dialect.strict When True, raise exception Error on bad CSV input. The default is False.
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49205251
tagged with: excel
favorite count: 0
type: Question

http://stackoverflow.com/comment/85438286
type: QuestionComment
score: 0
has text: @RahulBharadwaj Oh sorry. Yes. Thats what both return. my apolgies. so we've figured out that that's not the problem. any other suggestions?
type: Comment
comment on: http://stackoverflow.com/q/49216987

http://stackoverflow.com/q/49214921
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49215040
tagged with: python
has body: This is my test code. But it could not run. Terminal always gave me this error: Traceback (most recent call last): File "desktop/test.py", line 28, in loss =tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1])). File "/Users/sumeixu/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 898, in binary_op_wrapper y = ops.convert_to_tensor(y, dtype=x.dtype.base_dtype, name="y") File "/Users/sumeixu/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 932, in convert_to_tensor as_ref=False) File "/Users/sumeixu/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1022, in internal_convert_to_tensor ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) File "/Users/sumeixu/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/constant_op.py", line 233, in _constant_tensor_conversion_function return constant(v, dtype=dtype, name=name) File "/Users/sumeixu/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/constant_op.py", line 212, in constant value, dtype=dtype, shape=shape, verify_shape=verify_shape)) File "/Users/sumeixu/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/tensor_util.py", line 401, in make_tensor_proto raise ValueError("None values not supported."). ValueError: None values not supported. Help please. Blew is my code. Thank you so much! import tensorflow as tf import numpy as np import matplotlib.pyplot as plt def add_layer(inputs,in_size,out_size,activation_function=None): Weights=tf.Variable(tf.random_normal([in_size,out_size])) biases=tf.Variable(tf.zeros([1,out_size])+0.1) Wx_Plus_b = tf.matmul(inputs,Weights)+biases if activation_function is None: outputs=Wx_Plus_b else: outputs=activation_function(Wx_Plus_b) return outputs x_data = np.linspace(-1,1,300)[:,np.newaxis] noise=np.random.normal(0,0.05,x_data.shape) y_data=np.square(x_data)-0.5+noise xs=tf.placeholder(tf.float32,[None,1]) ys=tf.pla…
has title: Tensorflow error: ValueError: None values not supported
score: 2
upvote count: 2
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: tensorflow
favorite count: 0

http://stackoverflow.com/q/49161183
tagged with: python
tagged with: regex
has body: I am trying to do some machine learning practice, but the ID column of my dataframe is giving me trouble. I have this: 0 LP001002 1 LP001003 2 LP001005 3 LP001006 4 LP001008 I want this: 0 001002 1 001003 2 001005 3 001006 4 001008 My idea is to use a replace function, ID.replace('[LP]', '', inplace=True), but this doesn't actually change the series. Any one know a good way to convert this column?
tagged with: replace
has title: Pandas -- Replace dirty strings with int
type: AnsweredQuestion
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/85328018
tagged with: pandas
has comment: http://stackoverflow.com/comment/85328164
accepted answer: http://stackoverflow.com/a/49161346
has answer: http://stackoverflow.com/a/49161346
type: Question
possible better answer: http://stackoverflow.com/a/49161320
has answer: http://stackoverflow.com/a/49161320

http://stackoverflow.com/q/49210083
linked to: http://stackoverflow.com/q/9961563
upvote count: 1
has title: Why can't my sprite won't stop moving? Even if i stop pushing buttons the sprite is still moving
has body: After hitting a and d or left and right key , the sprite will still move without me pressing the key.He just won't stop.How can i fix this? def control(self, x, y): ''' control player movement ''' self.movex += x self.movey += y if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT or event.key == ord('a'): player.control(-steps , 0) if event.key == pygame.K_RIGHT or event.key == ord('d'): player.control(steps , 0) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == ord('a'): player.control(0 , 0) if event.key == pygame.K_RIGHT or event.key == ord('d'): player.control(0 , 0)
downvote count: 1
favorite count: 0
duplicate of: http://stackoverflow.com/q/59830738
type: Question
has comment: http://stackoverflow.com/comment/85426070
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/9961563
tagged with: python
tagged with: pygame
score: 0
has comment: http://stackoverflow.com/comment/85427058
answer count: 0

http://stackoverflow.com/comment/85320369
score: 0
type: AnswerComment
has text: I am trying to avoid global variables. Does it change anything due to the fact that the variables I want are in login which is in another subroutine signer? I tried to add to a list using " list = [signer.login.username]" but it doesn't work.
comment on: http://stackoverflow.com/a/49157290
type: Comment

http://stackoverflow.com/a/49132577
score: 1
upvote count: 1
has body: I did the following, and this should work: $ export http_proxy='http://myproxy.example.com:1234' $ python myscript.py # Using http://myproxy.example.com:1234 as a proxy
accepted answer of: http://stackoverflow.com/q/49131888
type: Answer
answers question: http://stackoverflow.com/q/49131888
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85538710
has text: I'm not sure how that can be possible; that suggests that "question" is simultaneously None and not None, which obviously can't be the case. Is there any other code that we're not seeing that could be the cause?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49267208
type: Comment

duck-typing
tags question: http://stackoverflow.com/q/49224925
type: Tag
tag name: duck-typing

http://stackoverflow.com/a/49272036
accepted answer of: http://stackoverflow.com/q/49271832
has body: Make the frames call geometry method on their master in swap_frame method: frame.master.geometry("900x650+220+20") or more generally: widget.winfo_toplevel().geometry("100x250+220+20") If you want to have distinct placements/sizes for each frame, there can be a number of ways of doing that: Collect the frame widgets in a collection type, such as a dictionary or a list, then call geometry with a mapping based on the frame Pass the mapping value explicitly, then call geometry based on the mapping for the current frame Have an attribute defined for each frame for mapping or the geometry argument directly, and simply call geometry using that argument for the current frame The example below uses the attributes as suggested in 3: def resize(widget): widget.winfo_toplevel().geometry(widget.geo) def swap_frame(frame): resize(frame) frame.tkraise() ... frame1.geo = "900x650+220+20" frame2.geo = "1000x800+220+20"
upvote count: 1
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85589408
has comment: http://stackoverflow.com/comment/85585492
has comment: http://stackoverflow.com/comment/85586943
answers question: http://stackoverflow.com/q/49271832
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85591388

http://stackoverflow.com/a/49205443
answers question: http://stackoverflow.com/q/49198719
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/85466720
has body: Why is this a problem? You can save the input file to disk before you call out to context. I'm not sure of how the command line for context works, but this is how you would save the file: import uuid import os def consultation_pdf(request, pk2, pk1): entry = Consultation.objects.get(pk=pk2) source = Patient.objects.get(pk=pk1) # context = Context({ 'consultation': entry, 'patient': source }) context = dict({'consultation': entry, 'patient': source}) template = get_template('clinic/consultation.tex') rendered_tpl = template.render(context, request) # save the file to disk filename = uuid.uuid4() # Python3 only. For python2 check out the docs! with tempfile.TemporaryDirectory() as tempdir: filename = os.path.join(tempdir, filename.hex) with open(filename, 'w', encoding='utf8') as infile: infile.write(rendered_tpl) # Create subprocess, supress output with PIPE and # run latex twice to generate the TOC properly. # Finally read the generated pdf. for i in range(2): process = Popen( ['context', filename, '-output-directory', tempdir], stdin=PIPE, stdout=PIPE,) process.communicate(rendered_tpl) with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f: pdf = f.read() r = HttpResponse(content_type='application/pdf') r.write(pdf) return r
has comment: http://stackoverflow.com/comment/85430847
has comment: http://stackoverflow.com/comment/85452958
has comment: http://stackoverflow.com/comment/85429814

http://stackoverflow.com/comment/85250500
type: QuestionComment
has text: `from df import *`, not `dy.py`.
comment on: http://stackoverflow.com/q/49122274
type: Comment
score: 0

api
tags question: http://stackoverflow.com/q/49183806
tag name: api
tags question: http://stackoverflow.com/q/49192909
tags question: http://stackoverflow.com/q/49267392
tags question: http://stackoverflow.com/q/49275824
tags question: http://stackoverflow.com/q/49173394
tags question: http://stackoverflow.com/q/49193097
tags question: http://stackoverflow.com/q/49164809
tags question: http://stackoverflow.com/q/49269570
tags question: http://stackoverflow.com/q/49155808
tags question: http://stackoverflow.com/q/49254722
tags question: http://stackoverflow.com/q/49155243
tags question: http://stackoverflow.com/q/49210649
tags question: http://stackoverflow.com/q/49156983
tags question: http://stackoverflow.com/q/49268387
tags question: http://stackoverflow.com/q/49224945
tags question: http://stackoverflow.com/q/49127155
type: Tag
tags question: http://stackoverflow.com/q/49223760

http://stackoverflow.com/a/49191521
type: Answer
has body: You can always use something relying on: np.where( np.abs(x-y) &lt; epsilon )
answers question: http://stackoverflow.com/q/49191460
downvote count: 0
score: 5
upvote count: 5

http://stackoverflow.com/a/49285286
answers question: http://stackoverflow.com/q/49239463
score: 1
type: Answer
has body: If you threshold the images to [0,1] and [0,2] and add them together you get all unique values for the different conditions. Since the values are 0 through 3 you can use those directly to index into a lookup table: lut = [[ 1, 1, 1], [ 1, 0, 0], [ 0, 1, 0], [0.5,0.5,0.5]] _, thresh_ref = cv2.threshold(reference, 75, 1, 0) _, thresh_extract = cv2.threshold(extract, 75, 2, 0) C = lut[thresh_ref + thresh_extract]
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49185067
type: Question
has answer: http://stackoverflow.com/a/49185220
accepted answer: http://stackoverflow.com/a/49185220
has title: About the type check of function return value
tagged with: python
score: -1
type: AnsweredQuestion
downvote count: 2
has body: Recently I wanted to give my personal project an idea: I want to select different feature branches based on the return type of the function For example, func() returns an instance of type A, then selects the branch that adapts to A; returns an instance of type B and selects the branch that adapts to B. It is well known that the class type of an instance can be simply implemented with the instance method, but how to determine the return value of the function.
upvote count: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/85435448
has text: @AdityaMatturi: added one case else
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49215583
type: Comment

http://stackoverflow.com/a/49126168
has comment: http://stackoverflow.com/comment/85260473
has comment: http://stackoverflow.com/comment/85257299
answers question: http://stackoverflow.com/q/49126100
score: 0
has comment: http://stackoverflow.com/comment/85260572
has body: I am not sure about how to create a pdf. But the following should write to a textfile, you would only have to add a part where the result is printed to a pdf. import os import matplotlib.pyplot as plt files = os.listdir() pdf_files = [i for i in files if i.endswith('.pdf')] #pdf_files = [ 'orange_3.pdf','blue_4.pdf','green_10.pdf'] color,nr = [],[] for fn in pdf_files: color += [fn.split('_')[0]] nr += fn.split('_')[1].strip('.pdf') nms = range(len(color)) f = plt.figure() plt.xticks(nms,color) plt.scatter(color,nms) plt.show() f.savefig('fn.pdf')
has comment: http://stackoverflow.com/comment/85261030
has comment: http://stackoverflow.com/comment/85260667
has comment: http://stackoverflow.com/comment/85262144
has comment: http://stackoverflow.com/comment/85263180
has comment: http://stackoverflow.com/comment/85261838
type: Answer
has comment: http://stackoverflow.com/comment/85260745
has comment: http://stackoverflow.com/comment/85262068
has comment: http://stackoverflow.com/comment/85260353

http://stackoverflow.com/comment/85438873
type: QuestionComment
comment on: http://stackoverflow.com/q/49216840
score: 0
has text: No one will be able tell you why your code doesn't work if you don't describe what it's meant to be doing.
type: Comment

http://stackoverflow.com/q/49240531
has comment: http://stackoverflow.com/comment/85538393
type: Question
answer count: 1
has title: how do I replace text only within a textrun
has answer: http://stackoverflow.com/a/49257946
accepted answer: http://stackoverflow.com/a/49257946
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85519032
has body: I am using the google slides API to automatically update a presentation which has some pretty detailed tables. I have a table with several cells, and within each cell I have 3 different Lines with different formatting. For example, the top line has a bigger font, the second line is smaller and green, etc. As this presentation should update automatically everyday with my inputed data, I really need to set up requests based off of the TextRun lengths rather than fixed start and end indexes (these start and end indexes will change everyday as the text will update, so I cant manually edit the index everyday) How can I either replace the text only within a TextRun or replace the text on a line by line or paragraph basis? I am adding an image here. You can see that in the first line I have one large bold number that needs to be updated, and in the second line I have 3 items that need to be updated. 1. Y/Y 2. Q/Q 3. M/M I want to be able to do this without requiring every text to be the same size. Screenshot of table in slide Here is the batch update request I have set up right now. I just cant figure out how I can get the range to always be within a textRun, rather than for the entire cell. reqs = [ { "deleteText": { "objectId": "g2f8579c174_1_6", "cellLocation": { "rowIndex": 1, "columnIndex": 1, }, "textRange": { "type": "ALL", } } }, { "insertText": { "objectId": "g2f8579c174_1_6", "cellLocation": { "rowIndex": 1, "columnIndex": 1 }, "text": "texttexttext", "insertionIndex": 0 } } ]
tagged with: google-slides-api
has comment: http://stackoverflow.com/comment/85494397
tagged with: python

http://stackoverflow.com/a/49305922
score: 5
downvote count: 0
has body: I faced an almost identical problem with my own chat page system. I wanted to be able to add a link to a number of keywords (with slight variations) that were present in the text. I only had around 200 phrases though to check. I decided to try using a standard regular expression for the problem to see how fast it would be. The main bottleneck was in constructing the regular expression. I decided to pre-compile this and found the match time was very fast for shorter texts. The following approach takes a list of phrases, where each contains phrase and link keys. It first constructs a reverse lookup dictionary: {'phrase to match' : 'link_url', 'another phrase' : 'link_url2'} Next it compiles a regular expression in the following form, this allows for matches which contain different amounts of white space between words: (phrase\s+to\s+match|another\s+phrase) Then for each piece of text (e.g. 2000 words each), it uses finditer() to get each match. The match object gives you .span() giving the start and end location of the matching text and group(1) gives the matched text. As the text can possibly have extra whitespace, re_whitespace is first applied to remove it and bring it back to the form stored in the reverse dictionary. With this, it is possible to automatically look up the required link: import re texts = ['this is a phrase to match', 'another phrase this is'] phrases = [{'phrase': 'phrase to match', 'link': 'link_url'}, {'phrase': 'this is', 'link': 'link_url2'}] reverse = {d['phrase']:d['link'] for d in sorted(phrases, key=lambda x: x['phrase'])} re_whitespace = re.compile(r'\s+') re_phrases = re.compile('({})'.format('|'.join(d['phrase'].replace(' ', r'\s+') for d in phrases))) for text in texts: matches = [(match.span(), reverse[re_whitespace.sub(' ', match.group(1))]) for match in re_phrases.finditer(text)] print(matches) Which would display the matches for the two texts as: [((0, 7), 'link_url2'), ((10, 30), 'link_url')] [((15, 23), 'link_url2')] To test how …
upvote count: 5
type: Answer
answers question: http://stackoverflow.com/q/49173770

http://stackoverflow.com/q/49163689
score: 1
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85333031
type: Question
accepted answer: http://stackoverflow.com/a/49163715
answer count: 2
has answer: http://stackoverflow.com/a/49163715
tagged with: python
possible better answer: http://stackoverflow.com/a/49163712
has title: Split text inside list
has answer: http://stackoverflow.com/a/49163712
has body: I have a list that has the following structure: input = [['Business'] ['Technology'] ['Technology Business Sports']] I'd like to split sentences into words and create the following structure: result = [['Business'] ['Technology'] ['Technology', 'Business', 'Sports']] I tried this result = input for i, s in enumerate(input): result[i] = s[0].split() print(result) But I get the error: ValueError: cannot copy sequence with size 2 to array axis with dimension 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85333007
downvote count: 0

http://stackoverflow.com/comment/85476856
has text: The current dup target is not correct, but the question is still a duplicate. [See here](https://stackoverflow.com/questions/10825926/python-3-x-rounding-behavior).
comment on: http://stackoverflow.com/q/49236564
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49214189
tagged with: pandas
tagged with: dataframe
tagged with: python
has body: I am trying to add a new row to the dataframe df based on this post but I'm getting the syntax wrong. What am I missing? df = pd.DataFrame(columns=['poll1', 'poll2','tval','pval']) temp = pd.DataFrame([0,0,1,2], columns=['poll1', 'poll2','tval','pval']) df.append(temp) print(df)
accepted answer: http://stackoverflow.com/a/49214234
has answer: http://stackoverflow.com/a/49214234
type: AnsweredQuestion
score: 0
answer count: 1
has title: Add row to dataframe syntax issue
linked to: http://stackoverflow.com/q/42701570
type: Question
has comment: http://stackoverflow.com/comment/85433807

http://stackoverflow.com/tag/c
tags question: http://stackoverflow.com/q/49132604
tags question: http://stackoverflow.com/q/49153647
tags question: http://stackoverflow.com/q/49128661
tags question: http://stackoverflow.com/q/49170635
tags question: http://stackoverflow.com/q/49257742
tags question: http://stackoverflow.com/q/49142439
tags question: http://stackoverflow.com/q/49143718
tags question: http://stackoverflow.com/q/49204627
tags question: http://stackoverflow.com/q/49155266
tags question: http://stackoverflow.com/q/49207422
tags question: http://stackoverflow.com/q/49208498
tag name: c
type: Tag
tags question: http://stackoverflow.com/q/49228106
tags question: http://stackoverflow.com/q/49175624
tags question: http://stackoverflow.com/q/49208949

http://stackoverflow.com/q/49215611
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85436032
has body: I used OpenCV to display the figure but got an error: Here is my code: import cv2 import numpy as np a = cv2.imread('xyz.jpg', -1) cv2.imshow('img', a) cv2.error: OpenCV(3.4.1) D:\Build\OpenCV\opencv-3.4.1\modules\highgui\src\window.cpp:364: error: (-215) size.width&gt;0 &amp;&amp; size.height&gt;0 in function cv::imshow The figure can be found here. How to solve this problem? Thank you very much.
has comment: http://stackoverflow.com/comment/85436041
tagged with: opencv
score: 0
has title: Unable to display figures using imshow in cv2
has comment: http://stackoverflow.com/comment/85435825
tagged with: python
has comment: http://stackoverflow.com/comment/85436129
has comment: http://stackoverflow.com/comment/85435689
has comment: http://stackoverflow.com/comment/85436218
has comment: http://stackoverflow.com/comment/85436056
type: Question
has comment: http://stackoverflow.com/comment/85436117
has comment: http://stackoverflow.com/comment/85435804

http://stackoverflow.com/comment/85297238
type: Comment
comment on: http://stackoverflow.com/a/49143239
score: 0
type: AnswerComment
has text: Thanks! You are right, there is no need for concat.

http://stackoverflow.com/comment/85458384
score: 1
has text: I think there's an opportunity here for some education. the hungry variable goes from None, to a boolean, to a string, to a boolean, etc. It's workable in this little scenario, but I don't think the OP will learn much out of this approach. I've added an answer below to explain.
type: Comment
comment on: http://stackoverflow.com/a/49227159
type: AnswerComment

http://stackoverflow.com/comment/85896464
type: AnswerComment
has text: I don't see any reference to it in the docs either, but we do have it in the in it.py files. It is possible that it is a nose test specific thing, so I would just recommend trying it. (Yeah, the underscores in the filename turned into italics)
comment on: http://stackoverflow.com/a/49296511
type: Comment
score: 0

http://stackoverflow.com/q/49275383
linked to: http://stackoverflow.com/q/20100003
tagged with: set
downvote count: 0
favorite count: 0
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49276275
score: 3
has answer: http://stackoverflow.com/a/49275665
tagged with: algorithm
has answer: http://stackoverflow.com/a/49276275
has body: There is no mention of average-case complexity for the multiple-sets intersection on Python wiki: https://wiki.python.org/moin/TimeComplexity Only the worst-case complexity is given: (n-1)*O(l) where l is max(len(s1),..,len(sn)) What is the average complexity of multiple-sets intersection operation? How is this operation implemented under the hood? set.intersection(s1,s2,s2,s4 ...sn) Is the multiple-sets intersection operation implemented in a different way than the two-sets intersection operation because their worst case complexities are different according to python-wiki: 2-sets intersection: O(len(s) * len(t)) Multiple-sets intersection: (n-1)*O(l) where l is max(len(s1),..,len(sn)) So the complexity of two sets using multiple-sets formula should be: --&gt; (2-1)*O(l) where l is max(len(s1), len(s2)` --&gt; O(max(len(s1), len(s2)) I think it is pretty different than the complexity notation of two set intersection operation. On a side note, is there a better way than set intersection for membership check between different sets? NOTE: I am looking for an explanation rather than just the complexity O() notation :)
tagged with: python
tagged with: data-structures
has title: Average complexity of multiple-sets intersection operation and its under the hood implementation
accepted answer: http://stackoverflow.com/a/49275665
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/8102478
answer count: 2
upvote count: 3

http://stackoverflow.com/a/49283416
has body: Isn't it possible to run proxi on LOWER OSI level? If yes, it would be much easier to use row sockets (from socket import socket)
answers question: http://stackoverflow.com/q/49273725
type: Answer
score: 0

http://stackoverflow.com/a/49181497
has body: As far as I know there is no gsheet hook or operator in airflow at the moment. If security is not a concern you could publish it to the web and pull it in airflow using the SimpleHttpOperator. If security is a concern I recommend going the PythonOperator route and use df2gspread library. Airflow version >= 1.9 can help obtaining credentials for df2gspread
accepted answer of: http://stackoverflow.com/q/49177246
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49177246
has comment: http://stackoverflow.com/comment/85389379
type: Answer

http://stackoverflow.com/comment/85374296
score: 0
comment on: http://stackoverflow.com/q/49184118
type: QuestionComment
type: Comment
has text: Will you always just have one `False` value or will there be an indefinite number of partitions?

http://stackoverflow.com/q/49137087
has answer: http://stackoverflow.com/a/49137177
answer count: 1
tagged with: reportlab
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49137177
tagged with: python
score: -1
type: AnsweredQuestion
upvote count: 0
has body: I am trying to insert formatted text into the last page of my PDF. I am using the PyPDF2 and reportlab libraries to do this. I am using Python 2.7. For some reason the text gets inserted without spaces and on a new line for every character (not for every CRLF). Where did I go wrong or is there a better way to do this? Thanks. PYTHON CODE: # Libs from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger; from reportlab.pdfgen import canvas; # PDF Editor 1 from reportlab.lib.pagesizes import letter; # PDF Editor 2 from reportlab.lib.units import inch; # PDF Editor 3 uniOCRText = 'This is a test string.'; # Create a new PDF with Reportlab packet = io.BytesIO(); can = canvas.Canvas(packet, pagesize=letter); textobject = can.beginText(); textobject.setTextOrigin(inch, 2.5*inch); textobject.setFont("Times-Roman", 10); i = 0; for line in uniOCRText: i = i + 1; print("i = " + str(i) + " - line = " + str(line)); textobject.textLine(line); # Error here deletes spaces!!! textobject.setFillGray(0.4); can.drawText(textobject); can.save(); # Move to the beginning of the StringIO buffer packet.seek(0); new_pdf = PdfFileReader(packet); # Add watermark output = PdfFileWriter(); page = new_pdf.getPage(0); output.addPage(page); tempFolder = "Temp/TempPDF.pdf"; outputStream = open(tempFolder, "wb"); output.write(outputStream); outputStream.close(); # Create a Merger PDF merger = PdfFileMerger(); merger.append(PdfFileReader(open(pdfFileFromLoc, 'rb'))); merger.append(PdfFileReader(open(tempFolder, 'rb'))); merger.write(pdfFileDestLoc);
tagged with: pypdf
has title: Why is PyPDF2 and reportlab removing spaces when inserting text?

http://stackoverflow.com/a/49202851
type: Answer
answers question: http://stackoverflow.com/q/49202647
score: 0
has body: The print() statement is executed after the nested j loop. It has been indented to make it a part of the outer loop i. What print() statement is actually doing here? It is used to move the cursor to the next line after each row is printed. Understand it like this: for i in range(0,range1): (indentation) for j in range(0,range2): (indentation)(indentation) print(i, end='') //loop j ends (indentation) print() //part of outer loop i

http://stackoverflow.com/q/49221412
accepted answer: http://stackoverflow.com/a/49222765
tagged with: flask-sqlalchemy
answer count: 1
has comment: http://stackoverflow.com/comment/85447224
has answer: http://stackoverflow.com/a/49222765
has comment: http://stackoverflow.com/comment/85448590
type: Question
tagged with: python
has title: Unable to query as an INT from database using Python Flask
tagged with: sqlalchemy
tagged with: python-3.x
has body: I am using python flask and have a database A that I am pulling the year from. I have defined the column in the database as an integer, but I am struggling to get my query to return integers. Right now, I am trying to find the max year in my query, so I can eventually add subsequent years. def add(): years = db.session.query(A.year.distinct().label("year")) maxyear = max(db.session.query(A.year.distinct().label("year"))) return render_template("x.html",maxyear=maxyear,years=years,type=type(maxyear)) This function currently returns it as (maxyear , type): (2017,) , &lt;class 'sqlalchemy.util._collections.result'&gt; I tried to do: maxyear = int(max(db.session.query(A.year.distinct().label("year")))) but received this error: typeError: int() argument must be a string, a bytes-like object, or a number, not 'result'. Any suggestions as to how I should adjust my query to correct this issue?
type: AnsweredQuestion
score: 0

http://stackoverflow.com/comment/85304947
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49150115
has text: By the way, I think in 3.4+ you can test this by creating a subclass of ModuleType, adding a `__del__` method to it that just prints “I’m being deleted”, and then writing a trivial .py module that sets its `__class__` to that type, then import that instead of `math`. (Also, `math` is a weird one to test in the first place, as it’s not only a C API module, but also a core module that may be part of the startup bootstrap.)

http://stackoverflow.com/q/49267033
score: 3
upvote count: 3
has body: My payloads are in XML format. I have schema for that. Is there a way, that I can define XML schema as a python class and use that to validate XML inputs? Currently I use lxml library to parse my schema.
downvote count: 0
has title: Can we define XML schema as python class and use that to validate xml inputs?
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
answer count: 0
has comment: http://stackoverflow.com/comment/85935780

http://stackoverflow.com/a/49130218
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49130192
has comment: http://stackoverflow.com/comment/85271349
downvote count: 0
score: 13
has comment: http://stackoverflow.com/comment/85265076
accepted answer of: http://stackoverflow.com/q/49130192
has comment: http://stackoverflow.com/comment/85265029
type: Answer
has comment: http://stackoverflow.com/comment/85265046
has comment: http://stackoverflow.com/comment/85265012
upvote count: 13
has body: Multiply them and test against 0: def func(a, b): return a * b &gt;= 0

http://stackoverflow.com/comment/85538959
score: 0
type: Comment
has text: If you already had imported excel data as pandas dataframe, why not just [join](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html) your list with the excel?
type: QuestionComment
comment on: http://stackoverflow.com/q/49267696

http://stackoverflow.com/comment/85373653
type: QuestionComment
has text: I am now getting some variation in the final frame number for the same bitrate. It freezes at about frame 60 when I set bitrate to `-1`.
comment on: http://stackoverflow.com/q/49183656
score: 0
type: Comment

http://stackoverflow.com/comment/85255316
has text: FYI, I have fixed this issue with copying list, see following: for i in correctedList[:]:
comment on: http://stackoverflow.com/a/49124854
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/comment/120839046
score: 0
type: Comment
comment on: http://stackoverflow.com/a/51357875
type: AnswerComment
has text: Whis is number_of_coefficients not connected to degree? degree tells you number of nodes per element

http://stackoverflow.com/q/49228744
accepted answer: http://stackoverflow.com/a/49228822
possible better answer: http://stackoverflow.com/a/66353004
has title: AttributeError: module 'attr' has no attribute 's'
has answer: http://stackoverflow.com/a/49228822
tagged with: python
has comment: http://stackoverflow.com/comment/85460963
has answer: http://stackoverflow.com/a/66353004
has comment: http://stackoverflow.com/comment/85460922
score: 46
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85461018
has body: &gt;&gt;&gt; import attr &gt;&gt;&gt; @attr.s ... class SmartClass(object): ... a=attr.ib() ... b=attr.ib() ... Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: module 'attr' has no attribute 's' &gt;&gt;&gt; I don't understand why it's not working. I have installed this module using pip and it was installed properly, but still it shows an error in the implementation part.
downvote count: 0
has comment: http://stackoverflow.com/comment/85461144
has comment: http://stackoverflow.com/comment/85460958
has comment: http://stackoverflow.com/comment/85461080
type: AnsweredQuestion
upvote count: 46
has comment: http://stackoverflow.com/comment/85461092
has comment: http://stackoverflow.com/comment/85460935
has comment: http://stackoverflow.com/comment/85460970
has comment: http://stackoverflow.com/comment/85460984

http://stackoverflow.com/a/49209745
has comment: http://stackoverflow.com/comment/85424211
answers question: http://stackoverflow.com/q/49209595
has comment: http://stackoverflow.com/comment/85424092
has comment: http://stackoverflow.com/comment/85424056
type: Answer
has body: You need to use [7:] and not [:7] the syntax is [&lt;start&gt;:&lt;end&gt;] and when omitted it will be automatically from start or end of the string. For example: val = "mailto:abc@abc.de" mailto = val[:7] # from first charater to 7th = 'mailto:' email = val[7:] # 8th character to the end.
has comment: http://stackoverflow.com/comment/85424145
has comment: http://stackoverflow.com/comment/85423990
score: 0
has comment: http://stackoverflow.com/comment/85424757

http://stackoverflow.com/comment/85538019
has text: I see. Can you get the duration of the sound in the given `.wav` file?
comment on: http://stackoverflow.com/q/49267159
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/85492095
type: AnswerComment
score: 0
has text: Well messing around with it, i fould out that its not json afterall:
comment on: http://stackoverflow.com/a/49242833
type: Comment

http://stackoverflow.com/a/49177596
accepted answer of: http://stackoverflow.com/q/49177374
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85360611
answers question: http://stackoverflow.com/q/49177374
has body: IIUC, you can use name attribute. df = pd.DataFrame({"a":[1,2], "b":[3,4]}) columns = [df.a.name, df.b.name] columns ['a', 'b']
has comment: http://stackoverflow.com/comment/85360656
type: Answer

http://stackoverflow.com/q/49181822
tagged with: object
duplicate of: http://stackoverflow.com/q/1167398
tagged with: python
has body: I am using Python 3.5 and wish to do something like this I have created a class which has variables Bitcoin, Monero , 'Etherum' ,etc with various integer values ,I wish to extract them var1="Bitcoin" value=classobj.var1 // there is a class which has a variable called Bitcoin and its value is 10 I wish to get its value using classobject.Bitcoin but the variable called var is Dynamic print (value) How do I achieve the same ? EDIT I know it is possible using switch statement but I am looking for other ways
tagged with: class
has comment: http://stackoverflow.com/comment/85370064
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49181872
has comment: http://stackoverflow.com/comment/85369362
answer count: 1
has title: Accessing data in variables in class Python 3
linked to: http://stackoverflow.com/q/1167398
accepted answer: http://stackoverflow.com/a/49181872
type: Question

http://stackoverflow.com/comment/85406271
comment on: http://stackoverflow.com/q/49200369
has text: no jupyterlab was installed through anaconda, will this cause a problem.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49291966
has comment: http://stackoverflow.com/comment/85586997
has comment: http://stackoverflow.com/comment/85586666
has body: You are looking at a Partial Dependence Plot. A PDP is a graph that represents a set of variables/predictors and their effect on the target field (in this case price). Those graphs do not estimate actual prices. It is important to realize that a PDP is not a representation of the dataset values or price. It is a representation of the variables effect on the target field. The negative numbers are logits of probabilities, not raw probabilities.
upvote count: 2
has comment: http://stackoverflow.com/comment/135747598
type: Answer
has comment: http://stackoverflow.com/comment/137292458
has comment: http://stackoverflow.com/comment/85586884
score: 2
answers question: http://stackoverflow.com/q/49247796
downvote count: 0

http://stackoverflow.com/comment/85308247
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49151878
has text: Good point old Django would automatically delete both newer versions woudn't

netezza
tags question: http://stackoverflow.com/q/49240739
tag name: netezza
type: Tag

http://stackoverflow.com/comment/85607654
type: QuestionComment
comment on: http://stackoverflow.com/q/49248432
score: 0
type: Comment
has text: OK, now that there’s enough info in the question, the problem is obvious. I’ll write an answer.

http://stackoverflow.com/q/49242899
has comment: http://stackoverflow.com/comment/85490873
downvote count: 1
has comment: http://stackoverflow.com/comment/85496137
favorite count: 0
type: Question
has body: So I have created a web scraper with selenium that infinitely crawls a web page. I am trying to create two instances of this scraper and run them in parallel so that two different portions of the site (or two different sites entirely) will be scraped at the same time. With my current code, both processes start and two chrome instances launch, but only one actually starts scraping. The other just sits on the landing page and never moves. My current scraper class looks like this class clBot(Scraper): def __init__(self, light_or_dark): light_side_xpaths = ['//*[@id="hhh"]/h4/a', '//*[@id="sss"]/h4/a/', '//*[@id="jjj"]/h4/a', '//*[@id="bbb"]/h4/a', '//*[@id="ggg"]/h4/a'] dark_side_xpaths = ['//*[@id="ccc"]/h4/a', '//*[@id="ppp"]/h4', '//*[@id="forums"]/h4/a'] if light_or_dark == "light": self.xpaths_to_scrape = light_side_xpaths self.csv_file = "lightside.csv" elif light_or_dark == "dark": self.xpaths_to_scrape = dark_side_xpaths self.csv_file = "darkside.csv" else: print('Incorrect variable entered. Please enter "light" or "dark" when initializing this class') quit() self.user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36' self.options = webdriver.ChromeOptions() #self.options.add_argument('--headless') self.options.add_argument('user-agent={self.user_agent}') self.current_region = '' self.driver = webdriver.Chrome(chrome_options=self.options) self.driver.get('https://craigslist.org') def run(self): self.navigate_pages() def identify_phone_number(self, string, phone_number_list): reg = re.findall(".*?(\(?\d{3}\D{0,3}\d{3}\D{0,3}\d{4}).*?", string) if len(reg) &gt; 0: for r in reg: if r.strip() not in phone_number_list: with open(self.csv_file, 'a') as csv: csv.write("{}\n".format(r.strip())) print("Extracted {} from listing".format(r.strip())) else: print('Phone number already in list.') def extract_phone_number(self): try: with open(self.csv_file, 'r') as csv: current_phone_numbers = csv.read() postin…
tagged with: python-multithreading
has comment: http://stackoverflow.com/comment/85527271
tagged with: python
has title: Creating Multiple Instances of a Selenium Scraper Class and running the in Parallel
tagged with: python-multiprocessing
type: AnsweredQuestion
score: 0
linked to: http://stackoverflow.com/q/20887555
has comment: http://stackoverflow.com/comment/85496105
upvote count: 1
has answer: http://stackoverflow.com/a/49246168
accepted answer: http://stackoverflow.com/a/49246168
answer count: 1
tagged with: selenium

http://stackoverflow.com/comment/85327569
score: 0
type: AnswerComment
has text: While it's not a direct FK relationship in the models due to the limitations we have in place, the `location_id` *does* match the primary key for the appropriate Location item. So I've had to manually reconcile them because I don't think there's a real "Django" way to get that relationship otherwise (because no relationship exists in the models).
type: Comment
comment on: http://stackoverflow.com/a/49159792

http://stackoverflow.com/comment/85415779
score: 0
type: QuestionComment
type: Comment
has text: The mask being the same size as the image complicates things. Is it just a [resized 3x3 grid of colors](https://i.sstatic.net/7IKV1.png) or can it be [jagged](https://i.sstatic.net/BobcV.jpg)? If so, how will you crop out the jagged piece? The source piece and target piece that you feed into your transfer function may not be of the same size.
comment on: http://stackoverflow.com/q/49204280

http://stackoverflow.com/a/49211972
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49210553
type: Answer
score: 2
has body: I would try to do it this way class PriceInlineAdmin(admin.TabularInline): def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "name": kwargs["queryset"] = Price.objects.exclude(color__name="blue") return super().formfield_for_foreignkey(db_field, request, **kwargs)
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49210553
downvote count: 0

http://stackoverflow.com/q/49244908
possible better answer: http://stackoverflow.com/a/51083782
score: 10
tagged with: python
tagged with: tqdm
type: AnsweredQuestion
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/51083782
upvote count: 10
accepted answer: http://stackoverflow.com/a/70849161
favorite count: 0
type: Question
has title: How to help tqdm figure out the total in a custom iterator
has answer: http://stackoverflow.com/a/70849161
has body: I'm implementing my own iterator. tqdm does not show a progressbar, as it does not know the total amount of elements in the list. I don't want to use "total=" as it looks ugly. Rather I would prefer to add something to my iterator that tqdm can use to figure out the total. class Batches: def __init__(self, batches, target_input): self.batches = batches self.pos = 0 self.target_input = target_input def __iter__(self): return self def __next__(self): if self.pos &lt; len(self.batches): minibatch = self.batches[self.pos] target = minibatch[:, :, self.target_input] self.pos += 1 return minibatch, target else: raise StopIteration def __len__(self): return self.batches.len() Is this even possible? What to add to the above code... Using tqdm like below.. for minibatch, target in tqdm(Batches(test, target_input)): output = lstm(minibatch) loss = criterion(output, target) writer.add_scalar('loss', loss, tensorboard_step)

http://stackoverflow.com/comment/85436457
type: Comment
has text: @jkff, yes, that's correct. The `PipelineResult` class in the Apache Beam Java SDK has a method `waitUntilFinish()`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49198653

kivy
tags question: http://stackoverflow.com/q/49255389
type: Tag
tags question: http://stackoverflow.com/q/49171059
tags question: http://stackoverflow.com/q/49225685
tags question: http://stackoverflow.com/q/49234333
tag name: kivy
tags question: http://stackoverflow.com/q/49122655
tags question: http://stackoverflow.com/q/49199533
tags question: http://stackoverflow.com/q/49186958
tags question: http://stackoverflow.com/q/49235731
tags question: http://stackoverflow.com/q/49175245
tags question: http://stackoverflow.com/q/49202274
tags question: http://stackoverflow.com/q/49253272
tags question: http://stackoverflow.com/q/49132195
tags question: http://stackoverflow.com/q/49236212
tags question: http://stackoverflow.com/q/49261143
tags question: http://stackoverflow.com/q/49277692
tags question: http://stackoverflow.com/q/49205744
tags question: http://stackoverflow.com/q/49167891
tags question: http://stackoverflow.com/q/49265887
tags question: http://stackoverflow.com/q/49165289
tags question: http://stackoverflow.com/q/49184804
tags question: http://stackoverflow.com/q/49133875
tags question: http://stackoverflow.com/q/49197119
tags question: http://stackoverflow.com/q/49259036
tags question: http://stackoverflow.com/q/49178348

http://stackoverflow.com/q/49220892
answer count: 0
has title: TFrecord creation error
type: UnansweredQuestion
tagged with: tfrecord
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85446785
favorite count: 0
has comment: http://stackoverflow.com/comment/85506670
score: 1
tagged with: python
tagged with: tensorflow
has body: Tried to create tfrecords for input image files. Tried two different versions of the Tfrecord creation script and encountered two different problems. Following are the details. Verison 1: Hard code image path, height and width for a single image. Result: Tfrecord is generated for the single image file along with "An exception has occurred, use %tb to see the full traceback. SystemExit" Version 2: A set of 5 images - their path, height and weight - are passed as a function call for tfrecord creation. Result: Tfrecord is generated for the first of the five images followed by kernel died message in QTConsole of Jupyter. Version 1 code: ### ### def create_tf_example(label_and_data_info): # TODO START: Populate the following variables from your example. height = 256 # Image height - hardcoded width = 256 # Image width - hardcoded filename = 'C:\\Users\\Sethu\\Desktop\\Encoding\\0b2e702f90aee4fff2bc6e4326308d50cf04701082e718d4f831c8959fbcda93.png' # Filename of the image - hardcoded filename = filename.encode() with tf.gfile.GFile(filename, 'rb') as fid: encoded_image = fid.read() encoded_image_data = encoded_image # Encoded image bytes image_format = b'png' # b'jpeg' or b'png' xmins = [56/256] # List of normalized left x coordinates in bounding box xmaxs = [200/256] # List of normalized right x coordinates in bounding box ymins = [56/256] # List of normalized top y coordinates in bounding box ymaxs = [200/256] #List of normalized bottom y coordinates in bounding box classes_text = ['a'.encode()] # List of string class name of bounding box classes = [1] # List of integer class id of bounding box # TODO END tf_label_and_data = tf.train.Example(features=tf.train.Features(feature={ 'image/height': dataset_util.int64_feature(height), 'image/width': dataset_util.int64_feature(width), 'image/filename': dataset_util.bytes_feature(filename), 'image/source_id': dataset_util.bytes_feature(filename), 'image/encoded': dataset_util.bytes_feature(encoded_image_data), 'image/format': da…
type: Question

http://stackoverflow.com/comment/85279133
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49136765
has text: http://docs.python-requests.org/en/master/user/advanced/#proxies
score: 0

http://stackoverflow.com/q/49158802
tagged with: replace
upvote count: 2
score: 1
answer count: 1
tagged with: string
downvote count: 1
accepted answer: http://stackoverflow.com/a/49159055
favorite count: 0
type: Question
type: AnsweredQuestion
tagged with: split
has answer: http://stackoverflow.com/a/49159055
has comment: http://stackoverflow.com/comment/85322869
linked to: http://stackoverflow.com/q/6475328
has comment: http://stackoverflow.com/comment/85322849
has comment: http://stackoverflow.com/comment/101393761
tagged with: python
has body: I have a dictionary dict with some words (2000) and I have a huge text, like Wikipedia corpus, in text format. For each word that is both in the dictionary and in the text file, I would like to replace it with word_1. with open("wiki.txt",'r') as original, open("new.txt",'w') as mod: for line in original: new_line = line for word in line.split(): if (dict.get(word.lower()) is not None): new_line = new_line.replace(word,word+"_1") mod.write(new_line) This code creates a new file called new.txt with the words that appear in the dictionary replaced as I want. This works for short files, but for the longer that I am using as input, it "freezes" my computer. Is there a more efficient way to do that? Edit for Adi219: Your code seems working, but there is a problem: if a line is like that: Albert is a friend of Albert and in my dictionary I have Albert, after the for cycle, the line will be like this:Albert_1_1 is a friend of Albert_1. How can I replace only the exact word that I want, to avoid repetitions like _1_1_1_1? Edit2: To solve the previous problem, I changed your code: with open("wiki.txt", "r") as original, open("new.txt", "w") as mod: for line in original: words = line.split() for word in words: if dict.get(word.lower()) is not None: mod.write(word+"_1 ") else: mod.write(word+" ") mod.write("\n") Now everything should work
has title: Replace words of a long document in Python

http://stackoverflow.com/q/49159725
has comment: http://stackoverflow.com/comment/85325615
type: Question
has comment: http://stackoverflow.com/comment/85325908
has body: I have two dataframes to merge into one. The main_id frame contains lists of unique ids. The ref_data frame contains some data about the objects in main_id. Some of the ids are referenced twice, some only once, so I think I need a one-to-many join. I want to capture both the period value and its corresponding quantity, with some identifying suffix linking the two. I've reviewed the pandas documentation on merge but didn't really see something mentioning this use case. Any help gratefully received. Example main_id frame: main_id = pd.DataFrame(data = [123,456,789], columns=['id']) main_id Out[109]: id 0 123 1 456 2 789 ref_data frame: ref_data = pd.DataFrame() ref_data['main_id'] = main_id['id'].append(main_id['id'].loc[1:]) ref_data = ref_data.reset_index(drop=True) ref_data['period'] = ['24hr', 'Day', 'Day', 'Night', 'Night'] ref_data['quantity'] = [3,4,6,5,2] ref_data Out[111]: main_id period quantity 0 123 24hr 3 1 456 Day 4 2 789 Day 6 3 456 Night 5 4 789 Night 2 Desired output: Out[112]: id period_1_ref period_1_val period_2_ref period_2_val 0 123 24hr 3 NaN NaN 1 456 Day 4 Night 5.0 2 789 Day 6 Night 2.0
answer count: 2
downvote count: 0
upvote count: 1
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/49162069
accepted answer: http://stackoverflow.com/a/49162069
possible better answer: http://stackoverflow.com/a/49162793
tagged with: pandas
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49162793
has title: Transform rows with common key to single row with multiple columns
favorite count: 0

http://stackoverflow.com/comment/85311082
type: Comment
type: QuestionComment
has text: You never call `counter_label`. Read over the tutorial code again.
score: 7
comment on: http://stackoverflow.com/q/49153332

http://stackoverflow.com/a/49277327
has body: You are half way there. Just link your 2 dictionaries and remember to never named variables after classes, e.g. use d not dict. from collections import Counter d = {'bob': ('farmer', 9), 'sue': ('farmer', 9), 'tim': ('farmer', 5), 'jill': ('chef', 8)} x = Counter(x for x in d.values()) res = Counter({k: x[v] for k, v in d.items()}) # Counter({'bob': 2, 'jill': 1, 'sue': 2, 'tim': 1})
type: Answer
has comment: http://stackoverflow.com/comment/85719893
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49275799
accepted answer of: http://stackoverflow.com/q/49275799

http://stackoverflow.com/a/49188088
upvote count: 1
has comment: http://stackoverflow.com/comment/85381593
answers question: http://stackoverflow.com/q/49188049
type: Answer
accepted answer of: http://stackoverflow.com/q/49188049
has comment: http://stackoverflow.com/comment/85381758
score: 1
has body: I think need split (1 &lt;= file['hm'] &lt;= 14) to 2 separate conditions chained by &amp; for AND: overn_std = file[(file['hm'] == 47) | (file['hm'] == 48) | ((file['hm'] &gt;= 1) &amp; (file['hm'] &lt;= 14)) ] You can also create each mask separately: m1 = (file['hm'] == 47) m2 = (file['hm'] == 48) m3 = (file['hm'] &gt;= 1) m4 = (file['hm'] &lt;= 14) overn_std = file[m1 | m2 | (m3 &amp; m4 )] Better is use isin with between: overn_std = file[(file['hm'].isin([47,48])) | (file['hm'].between(1,14)) ] Sample: file = pd.DataFrame({ 'hm': range(50) }) overn_std = file[(file['hm'].isin([47,48])) | (file['hm'].between(1,14)) ] print (overn_std) hm 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 12 13 13 14 14 47 47 48 48
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85367234
comment on: http://stackoverflow.com/a/49142253
type: AnswerComment
has text: @munk: Yeah, if it didn't work for non-special-method names, `__getattr__` and `__getattribute__` wouldn't exist. And dynamic proxies (for bridges, ORMs, RPCs, etc.) often need it. I wasn't suggesting you remove it from your answer, just making a comment.
score: 1
type: Comment

http://stackoverflow.com/q/49208794
has comment: http://stackoverflow.com/comment/85422216
has body: Its a bit strange to know that i keep getting a KeyError exception only in one scenario. I tried zip on two string sequences and that object was then used inside the dict function. But when i try to index this sequence out i keep getting KeyError. &gt;&gt;&gt; rawdata = "acbd" &gt;&gt;&gt; l1 = "abcd" &gt;&gt;&gt; l2 = "cdef" &gt;&gt;&gt; zp1 = zip(l1, l2) &gt;&gt;&gt; type(zp1) &lt;class 'zip'&gt; &gt;&gt;&gt; # zp1 is basically used for mapping. So every character in l1 is mapped to l2. So this would be ... # used to alter the rawdata object. Meaning every char in raw data would basically act as a key ... # to the below dictionary object and return a value which is then used in the join function. ... &gt;&gt;&gt; newstring = '' &gt;&gt;&gt; newstring = ''.join([dict(zp1)[x] for x in rawdata]) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 1, in &lt;listcomp&gt; KeyError: 'c' The funny this is the same code works properly if i dont use the zp1 object rather i use zip(l1, l2) inside dict directly. Why does this happen? Any clues? Below is the code that works well. &gt;&gt;&gt; rawdata = "acbd" &gt;&gt;&gt; l1 = "abcd" &gt;&gt;&gt; l2 = "cdef" &gt;&gt;&gt; newstring = ''.join([dict(zip(l1, l2))[x] for x in rawdata]) &gt;&gt;&gt; print(newstring) # Working as expected, without any exception cedf
has title: KeyError while mapping a zip object into dictionary in python
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/85422535
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/85422223
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/17777219
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/25336726
tagged with: python
has comment: http://stackoverflow.com/comment/85422142
tagged with: dictionary

http://stackoverflow.com/q/49136106
type: AnsweredQuestion
score: 3
upvote count: 3
has title: fill missing days in pandas dataframe
tagged with: pandas
downvote count: 0
answer count: 1
has body: Given the dataframe df = pd.DataFrame(data=[[1,1,3],[1,2,6],[1,4,3],[2,2,6]],columns=['ID','Day','Value']) df Out[58]: ID Day Value 0 1 1 3 1 1 2 6 2 1 4 3 3 2 2 6 As you can see for ID = 1 the Value related to Day3 is missing and for ID =2 the value related to Day1 is missing... I would like to fill these gaps adding np.nan and the missing day... Out[59]: ID Day Value 0 1 1 3.0 1 1 2 6.0 2 1 3 NaN 3 1 4 3.0 4 2 1 NaN 5 2 2 6.0
tagged with: nan
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49136271
accepted answer: http://stackoverflow.com/a/49136271
tagged with: missing-data
tagged with: dataframe
tagged with: python

http://stackoverflow.com/comment/85409505
has text: Also, once you have provided [mcve], please explain what type of join you require (inner / outer?), (left / right?)..
comment on: http://stackoverflow.com/q/49202052
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49247414
answers question: http://stackoverflow.com/q/49246713
has comment: http://stackoverflow.com/comment/85541331
score: 0
type: Answer
has body: I have test it with Centos 6.8 and Centos 7.4, can't reproduce your error. Please use this command to install Azure CLI: # 1. Install a package with repository for your system: # On CentOS, install package centos-release-scl available in CentOS repository: $ sudo yum install centos-release-scl # 2. Install the collection: $ sudo yum install python27 # 3. Start using software collections: $ scl enable python27 bash # 4. Import the Microsoft repository key. $ sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc # 5. Create local azure-cli repository information. $ sudo sh -c 'echo -e "[azure-cli]\nname=Azure CLI\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc" &gt; /etc/yum.repos.d/azure-cli.repo' # 6. Install with the yum install command. $ sudo yum install azure-cli Please try it.

http://stackoverflow.com/q/49194575
answer count: 2
upvote count: 2
linked to: http://stackoverflow.com/q/44184869
has body: I'm receiving the following error when executing the dev_appserver.py: from google.auth import app_engine File "/google/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/ python/runtime/sandbox.py" , line 1147, in load_module raise ImportError('No module named %s' % fullname) ImportError: No module named google.auth Odd thing is when I deploy the app, it works fine. I tried: dev_appserver.py MY_DIRECTORY cd /google/google-cloud-sdk/bin/; python dev_appserver.py MY_DIRECTORY python dev_appserver.py hello_world/ Installed updated gcloud components install app-engine-go Additional info: No virtual env is being used. path to dev_appserver: /google/google-cloud-sdk/bin/dev_appserver.py I'm using Google's Console Cloudshell Here are the SDK versions: Google Cloud SDK 192.0.0 alpha 2017.09.15 app-engine-go app-engine-java 1.9.63 app-engine-php " " app-engine-python 1.9.67 app-engine-python-extras 1.9.63 beta 2017.09.15 bq 2.0.29 cbt cloud-datastore-emulator 1.4.1 core 2018.03.02 datalab 20180213 docker-credential-gcr gcd-emulator v1beta3-1.0.0 gsutil 4.28 kubectl pubsub-emulator 2018.02.02 Files: app.yaml runtime: python27 api_version: 1 threadsafe: true handlers: - url: /.* script: main.app libraries: - name: flask version: 0.12 - name: six version: "1.9.0" appengine_config.py from google.appengine.ext import vendor import os vendor.add(os.path.join(os.path.dirname(os.path.realpath(__file__)),'lib')) main.py import logging from flask import Flask from sheets import data app = Flask(__name__) @app.route('/') def hello(): return 'Hello World!{}'.format(data) @app.errorhandler(500) def server_error(e): # Log the error and stacktrace. logging.exception('An error occurred during a request.') return 'An internal error occurred.', 500 sheets.py from google.auth import app_engine import googleapiclient.discovery SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.read…
type: UnansweredQuestion
tagged with: google-app-engine
has comment: http://stackoverflow.com/comment/85397852
has comment: http://stackoverflow.com/comment/85397945
downvote count: 0
tagged with: python
has answer: http://stackoverflow.com/a/56884902
favorite count: 0
has comment: http://stackoverflow.com/comment/85398835
score: 2
has title: App Engine not finding google.auth file in dev_appserver.py
has answer: http://stackoverflow.com/a/49207283
has comment: http://stackoverflow.com/comment/85396501
has comment: http://stackoverflow.com/comment/85397498
type: Question
tagged with: google-sheets-api
has comment: http://stackoverflow.com/comment/85398531

http://stackoverflow.com/comment/85320278
score: 0
has text: This is abstract Vector spaces with each word counting as a dimension in the vector space - this is maybe not something to tackle if you are "bad at math".
comment on: http://stackoverflow.com/q/49156075
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49271716
tagged with: python-xarray
has body: I am reading NetCDF files using xarray. Each variable have 4 dimensions (Times, lev, y, x). After reading the variable, I calculate the mean of the variable QVAPOR along (Times,lev) dimensions. After calculation I get variable QVAPOR_mean which is a 2D variable with shape (y: 699, x: 639). Xarray took only 10micro seconds to read the data with shape (Times:2918, lev:36, y:699, x:639); but took more than 60 minutes to plot the filled contour of the data of shape (y: 699, x: 639). I am wondering how come Xarray is taking extremely long time (more than 60 mins) to plot the contourf of array with size (y: 699, x: 639). I use following code for reading the files and perform computation. flnm=xr.open_mfdataset('./WRF_3D_2007_*.nc',chunks={'Times': 100}) QVAPOR_mean=flnm.QVAPOR.mean(dim=('Times','lev') QVAPOR_mean.plot.imshow() The last command takes more than 60 mins to complete. Help is appreciated. Thank You
tagged with: dask
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49283615
has comment: http://stackoverflow.com/comment/85563166
score: 0
tagged with: netcdf
has title: Plotting 2D data using Xarray takes a surprisingly long time?
answer count: 1
has comment: http://stackoverflow.com/comment/85568662
type: Question

http://stackoverflow.com/q/49273932
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49274393
has comment: http://stackoverflow.com/comment/85551946
linked to: http://stackoverflow.com/q/31483253
answer count: 2
has body: After executing the following code to generate a copy of a text file with Python, the newfile.txt doesn't have the exact same file size as oldfile.txt. with open('oldfile.txt','r') as a, open('newfile.txt','w') as b: content = a.read() b.write(content) While oldfile.txt has e.g. 667 KB, newfile.txt has 681 KB. Is there an explanation for that?
has comment: http://stackoverflow.com/comment/85550516
tagged with: read-write
downvote count: 0
has title: File size changes after read/write txt file in Python
has comment: http://stackoverflow.com/comment/85551652
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/49274133
has answer: http://stackoverflow.com/a/49274393
tagged with: filesize
upvote count: 3
has comment: http://stackoverflow.com/comment/97714479
has answer: http://stackoverflow.com/a/49274133
tagged with: python
has comment: http://stackoverflow.com/comment/137749087
has comment: http://stackoverflow.com/comment/137749085

http://stackoverflow.com/comment/135846655
comment on: http://stackoverflow.com/a/75994510
type: Comment
has text: Note, in this case you have to switch to http or provide custom SSL certificate
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85424470
comment on: http://stackoverflow.com/q/49205948
has text: Sorry I couldn't follow, what should I do?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85487664
score: 2
type: AnswerComment
has text: With the font Ananda Hastakchyar, pyvips with libvips 8.6.3 fails to allow enough space along the top and bottom. This is because this hand-styled font deliberately scribbles outside the usual inking area -- if you try selecting the font in a word processor, for example, you'll find descenders on one line will overlap ascenders on the line below. I've fixed this in HEAD 8.6 and the improvement will be in 8.6.4, thanks for pointing this out. https://github.com/jcupitt/libvips/commit/878c77a035ef0a32db7c249ccb31118932e790d3
type: Comment
comment on: http://stackoverflow.com/a/49169747

http://stackoverflow.com/comment/85457442
comment on: http://stackoverflow.com/a/49226751
score: 1
type: Comment
has text: That is awesome! Thank you, Adam. Was baffled so I spent ages looking at the source code. Should have realized it was something simple. The documentation is confusing, on page 74, it briefly mentions checkboxes. https://www.reportlab.com/docs/reportlab-userguide.pdf
type: AnswerComment

http://stackoverflow.com/comment/85547547
type: Comment
comment on: http://stackoverflow.com/q/49257427
type: QuestionComment
has text: I meant Remove the annotation given to the method. Yes it is failing inside the if condition mostly because the get call is returning a None object. Can you print what app.cache.get is returning.
score: 0

http://stackoverflow.com/a/49211348
score: 3
has body: This is a simple GUI using tkinter for python try: import tkinter as tk # python v3 except: import Tkinter as tk # python v2 # This function is called when the submit button is clicked def submit_callback(input_entry): print("User entered : " + input_entry.get()) return None ####################### GUI ########################### root = tk.Tk() root.geometry('300x150') #Set window size # Heading heading = tk.Label(root, text="A simple GUI") heading.place(x = 100, y = 0) input_label = tk.Label(root, text="Enter some text") input_label.place(x = 0, y = 50) input_entry = tk.Entry(root) input_entry.place(x = 100, y = 50) submit_button = tk.Button(root, text = "Submit", command = lambda: submit_callback(input_entry)) submit_button.place(x = 200, y = 90) root.mainloop() #############################################################
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/49211172
downvote count: 0

http://stackoverflow.com/q/49157033
has comment: http://stackoverflow.com/comment/85318943
answer count: 1
has answer: http://stackoverflow.com/a/49157290
type: Question
has title: Calling a function using variables from other functions as parameters/arguments
type: UnansweredQuestion
tagged with: function
tagged with: arguments
tagged with: python
tagged with: variables
has comment: http://stackoverflow.com/comment/85318977
tagged with: parameters
score: 0
has body: I am trying to call a set of subroutines I created which use arguments from other subroutines. For example, the variable 'username' should be able to be passed into 'db_username_searcher'. def signer(): def login(): username = entry_user.get() password = entry_user.get() if username in admin_array: admin_pass = 'pass' return username, password, admin_pass win = tkinter.Tk() win.title('Sign In') win.geometry('800x800') lbl_user = tkinter.Label(win, text='Username ') entry_user = tkinter.Entry(win) lbl_pwd = tkinter.Label(win, text='Password ') entry_pwd = tkinter.Entry(win, show='x') lbl_output = tkinter.Label(win) btn_signin = tkinter.Button(win, text='Sign in', command=login) lbl_user.pack() entry_user.pack() lbl_pwd.pack() entry_pwd.pack() lbl_output.pack() btn_signin.pack() entry_user.focus_set() win.mainloop() This is the code where 'username' is assigned and returned: def db_username_sercher(username, password): conn = sqlite3.connect('passwordDbase.db') c = conn.cursor() c.execute("SELECT * FROM passwordDb WHERE employee_username=?", (username, )) r = c.fetchone() if r: message = 'correct' else: message = ' ' if message == 'correct': dbpassword = c.execute("SELECT employee_password FROM passwordDb WHERE employee_username=?", (username, )) if dbpassword == password: message = 'correct' else: message = ' ' conn.commit() c.close() conn.close() return message When I try to call the two functions, I am not aware of how to deal with the arguments: signer() db_username_searcher(username, password) "unresolved reference 'password' " How do I call this properly?, Thanks in advance.

http://stackoverflow.com/a/49162357
has comment: http://stackoverflow.com/comment/85394910
downvote count: 0
answers question: http://stackoverflow.com/q/49162302
has comment: http://stackoverflow.com/comment/85330944
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85330749
accepted answer of: http://stackoverflow.com/q/49162302
has comment: http://stackoverflow.com/comment/85405978
type: Answer
has comment: http://stackoverflow.com/comment/85331106
score: 4
upvote count: 4
has body: You can use a positive lookahead and positive lookbehind: import re strings = ["AAPL1809A170", "XOM1809C123"] final_results = [re.findall('(?&lt;=\d)[A-Z]{1}(?=\d)', s)[0] for s in strings] Output: ['A', 'C']

http://stackoverflow.com/comment/85408260
type: Comment
has text: Have you tried a normal polyfit? https://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html
type: QuestionComment
comment on: http://stackoverflow.com/q/49201515
score: 3

http://stackoverflow.com/q/49238722
has answer: http://stackoverflow.com/a/49238872
downvote count: 0
answer count: 1
upvote count: 1
has title: Using reindex with duplicated axis
has comment: http://stackoverflow.com/comment/85481064
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
score: 1
has body: Let's say I have a dataframe with dates as index. Each row contains information about a certain event on that date. The problem is that there could be more than one event on said date. This is an example DataFrame, df2: one two 1/2 1.0 1.0 1/2 1.0 1.0 1/4 3.0 3.0 1/5 NaN 4.0 I want to add missing dates to the dataframe, and I used to be able to do it with .loc. Now .loc raises the following warning: Passing list-likes to .loc or [] with any missing label will raise KeyError in the future, you can use .reindex() as an alternative. This is my code (it works but raises warning): # I want to add any missing date- in this example, 1/3. df2.loc[["1/2","1/3","1/4","1/5"]] one two 1/2 1.0 1.0 1/2 1.0 1.0 1/3 NaN NaN 1/4 3.0 3.0 1/5 NaN 4.0 I've tried using reindex as it suggests, but my index contains duplicated values so it doesn't work: #This doesn't work df2.reindex(["1/2","1/3","1/4","1/5"]) ValueError: cannot reindex from a duplicate axis What can I do to replace the old loc?
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49238872
type: Question
has comment: http://stackoverflow.com/comment/85492560

http://stackoverflow.com/comment/85293609
comment on: http://stackoverflow.com/a/49143680
has text: So you mean to say that list and matrix[0] are different variables and they occupy different addresses in memory?
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49161652
has title: How to get around in place operation error if index leaf variable for gradient update?
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/60593633
upvote count: 12
tagged with: gradient-descent
score: 12
tagged with: neural-network
tagged with: python
possible better answer: http://stackoverflow.com/a/49253755
has body: I am encountering In place operation error when I am trying to index a leaf variable to update gradients with customized Shrink function. I cannot work around it. Any help is highly appreciated! import torch.nn as nn import torch import numpy as np from torch.autograd import Variable, Function # hyper parameters batch_size = 100 # batch size of images ld = 0.2 # sparse penalty lr = 0.1 # learning rate x = Variable(torch.from_numpy(np.random.normal(0,1,(batch_size,10,10))), requires_grad=False) # original # depends on size of the dictionary, number of atoms. D = Variable(torch.from_numpy(np.random.normal(0,1,(500,10,10))), requires_grad=True) # hx sparse representation ht = Variable(torch.from_numpy(np.random.normal(0,1,(batch_size,500,1,1))), requires_grad=True) # Dictionary loss function loss = nn.MSELoss() # customized shrink function to update gradient shrink_ht = lambda x: torch.stack([torch.sign(i)*torch.max(torch.abs(i)-lr*ld,0)[0] for i in x]) ### sparse reprsentation optimizer_ht single image. optimizer_ht = torch.optim.SGD([ht], lr=lr, momentum=0.9) # optimizer for sparse representation ## update for the batch for idx in range(len(x)): optimizer_ht.zero_grad() # clear up gradients loss_ht = 0.5*torch.norm((x[idx]-(D*ht[idx]).sum(dim=0)),p=2)**2 loss_ht.backward() # back propogation and calculate gradients optimizer_ht.step() # update parameters with gradients ht[idx] = shrink_ht(ht[idx]) # customized shrink function. RuntimeError Traceback (most recent call last) in () 15 loss_ht.backward() # back propogation and calculate gradients 16 optimizer_ht.step() # update parameters with gradients —&gt; 17 ht[idx] = shrink_ht(ht[idx]) # customized shrink function. 18 19 /home/miniconda3/lib/python3.6/site-packages/torch/autograd/variable.py in setitem(self, key, value) 85 return MaskedFill.apply(self, key, value, True) 86 else: —&gt; 87 return SetItem.apply(self, key, value) 88 89 def deepcopy(self, memo): RuntimeError: a leaf Variable that requires grad has been u…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49253755
accepted answer: http://stackoverflow.com/a/49316176
tagged with: deep-learning
answer count: 3
tagged with: pytorch
has answer: http://stackoverflow.com/a/49316176
downvote count: 0

http://stackoverflow.com/comment/85484659
type: QuestionComment
has text: #!/usr/local/bin/python3 import MySQLdb Doesn't work either...
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49220899

http://stackoverflow.com/comment/85392870
type: AnswerComment
comment on: http://stackoverflow.com/a/49192396
score: 0
type: Comment
has text: . But this is optional - See Section 3.6.1 of [https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6]. If the website chooses not to send the length by the OPTIONAL chunked parameters... then you cant use this method

http://stackoverflow.com/a/49192088
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85389520
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85390858
has body: Use DataFrame contructor with pivot, rename_axis and reset_index: arr = [('06/03/2018 17.35.18.211', 'param_a', 1), ('06/03/2018 17.35.19.211', 'param_b', 1), ('06/03/2018 17.35.20.211', 'param_c', 1), ('06/03/2018 17.35.21.211', 'param_a', 2), ('06/03/2018 17.35.22.211', 'param_b', 2), ('06/03/2018 17.35.23.211', 'param_c', 2)] df = pd.DataFrame(arr, columns=['timestamp','b','c']) df = df.pivot('timestamp','b','c').rename_axis(None, axis=1).reset_index() print (df) timestamp param_a param_b param_c 0 06/03/2018 17.35.18.211 1.0 NaN NaN 1 06/03/2018 17.35.19.211 NaN 1.0 NaN 2 06/03/2018 17.35.20.211 NaN NaN 1.0 3 06/03/2018 17.35.21.211 2.0 NaN NaN 4 06/03/2018 17.35.22.211 NaN 2.0 NaN 5 06/03/2018 17.35.23.211 NaN NaN 2.0 But if duplicates in first and second values, is necessary aggregation.
has comment: http://stackoverflow.com/comment/85390568
has comment: http://stackoverflow.com/comment/85390880
accepted answer of: http://stackoverflow.com/q/49192027
type: Answer
answers question: http://stackoverflow.com/q/49192027
score: 1

http://stackoverflow.com/comment/85401677
type: Comment
comment on: http://stackoverflow.com/q/49197801
has text: up to date! Just installed it on a new machine last week! 0.6.0
score: 0
type: QuestionComment

http://stackoverflow.com/a/49130670
accepted answer of: http://stackoverflow.com/q/49130183
has comment: http://stackoverflow.com/comment/85267636
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/49130183
type: AcceptedAnswer
downvote count: 0
has body: You don't really need extra modules for this, you just need to use the datetime object, not a string. from datetime import datetime import os import re line_regex = re.compile(r'A0-20-A6-0A-F2-AB') prev_dsa = None with open("info.log", "r") as in_file: for line in in_file: if (line_regex.search(line)): asd = line[6:26] dsa = datetime.strptime(asd, '%m-%d-%Y, %H:%M:%S') if (prev_dsa != None): if abs((dsa - prev_dsa).seconds) &gt;= 2: print dsa prev_dsa = dsa
has comment: http://stackoverflow.com/comment/85269646
type: Answer

http://stackoverflow.com/comment/85535883
type: QuestionComment
has text: Sorry, it's the second left-most column that is `df.index` I believe. In any case the index is what's ordering the data points. You might try `viz_df.reset_index()` after you sort.
score: 0
comment on: http://stackoverflow.com/q/49264518
type: Comment

http://stackoverflow.com/comment/85559881
score: 1
type: Comment
type: QuestionComment
has text: to overlay plots on the same curve, create the ax first in matplotlib (e.g. `fig, ax = plt.sublots()`, and then plot specifically to that ax `sb.lmplot(y=..,x=..,data=..,ax=ax)`. with this method, you can plot first the data, and then the fitted curve, as you like. This works for whole dataframes, too, e.g. `df.plot(ax=ax)`. Since seaborn is built on top of matplotlib, it's kinda hard to navigate until you have mastered the matplotlib basics.
comment on: http://stackoverflow.com/q/49277182

http://stackoverflow.com/q/49167224
downvote count: 0
answer count: 1
favorite count: 0
type: Question
has body: I want to conditional format each row of my exported output data-frame(Output format: excel file)based on a single column(max_probabilities column in my data-frame). If probability in the max_probabilities is greater than 0.75 I want that particular entire row to be colored Green else it has to be colored Red. How do i do it.(Note: I want to color my exported excel rows not the dataframe) Dataframe format Code: df=pd.DataFrame({'Details':x_test,'Amount':test_data.xn_Amount,'Category':Classified_Category,'Probability':max_probabilities}) This is how my exported dataframe looks like as of now. Thanks
tagged with: scikit-learn
tagged with: dataframe
tagged with: python
has title: Coloring the excel output in Sklearn
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: colors
has answer: http://stackoverflow.com/a/49167478
accepted answer: http://stackoverflow.com/a/49167478
tagged with: pandas

http://stackoverflow.com/q/49205343
has title: Sending Terminal commands from a running script on remote back to my local?
type: UnansweredQuestion
tagged with: remote-access
has body: I'm developing on a remote server which I login using ssh and develop using vi. I however need to send Terminal notification commands osascript -e "display notification {} {} {}" and such commands back to my local terminal so I can get sound/mac notifications on my system. How do I achieve this? I know I can use import os; os.sytem('command') for the script on server to send terminal commands on the machine its running in i.e., the server itself, but is there a similar command to send commands back to my local ? Ideally, I need this to be done from the scripts itself- because I have multiple triggers for notifications to be done.
tagged with: ssh
tagged with: python
has comment: http://stackoverflow.com/comment/85416142
has comment: http://stackoverflow.com/comment/85416102
score: 0
has answer: http://stackoverflow.com/a/49206042
has comment: http://stackoverflow.com/comment/85416069
has comment: http://stackoverflow.com/comment/85416303
has comment: http://stackoverflow.com/comment/85416354
answer count: 1
has comment: http://stackoverflow.com/comment/85416397
tagged with: openssh
type: Question
tagged with: python-os

http://stackoverflow.com/comment/85435071
has text: I appreciate your answer but can you use non capturing group(?:) or [^ ] and also use '*' instead of '+' in the answer
type: AnswerComment
comment on: http://stackoverflow.com/a/49215437
score: 0
type: Comment

http://stackoverflow.com/q/49226391
type: AnsweredQuestion
upvote count: 0
downvote count: 2
answer count: 3
has title: print a given number of characters or items per line to a textfile
has body: i would like to print a huge list of numbers to a textfile and each line should have 5 numbers in it. each number is 20 digits long. below is the list of number (this huge list of numbers is called a1) 3.1948343452787551598e-08 8.2713170790435268456e-08 9.2997407466072783263e-08 2.2201974063356576525e-08 4.7184351703512537954e-08 6.4869237006439418830e-08 5.6105657006093290136e-08 2.5869788723656166592e-08 3.2336150408719792489e-08 1.3711755095387755690e-08 0.8466139114156927980e-08 8.6552265489125695952e-08 1.6410391288046437544e-08 6.4151550079023113112e-08 9.9077814220256712144e-08 4.8228459783414887112e-08 1.6503915571969716123e-08 5.0759765831642425139e-08 1.4163943549368568877e-08 0.9171874262950143401e-08 2.2924892903408382299e-08 8.0910403085272639979e-08 0.1150909967310807486e-08 1.7800414806457459589e-08 9.9156327409347916878e-08 0.7474308272820071357e-08 4.8164050539957729897e-08 7.2570119501482690351e-08 5.5760621634989852061e-08 3.3409017307778332564e-08 4.7565190913441753115e-08 5.1557086343029653458e-08 6.3693801211606923532e-08 7.8897108738118126312e-08 9.4510334836961360301e-08 7.4880836459074272283e-08 4.9268327788150989424e-08 1.8466453757372403026e-08 6.2011855819003971679e-08 2.0783930984602632852e-08 0.9917554541229221025e-08 7.5224425124573985562e-08 2.6181377446191134266e-08 8.9009270149441469026e-08 7.7175189573912221707e-08 2.2170581996655944683e-08 3.2639560946849215485e-08 7.0901354279344938844e-08 5.5997044308008179085e-08 9.8907609461314007943e-08 3.1948343452787551598e-08 8.2713170790435268456e-08 9.2997407466072783263e-08 2.2201974063356576525e-08 4.7184351703512537954e-08 6.4869237006439418830e-08 5.6105657006093290136e-08 2.5869788723656166592e-08 3.2336150408719792489e-08 1.3711755095387755690e-08 0.8466139114156927980e-08 8.6552265489125695952e-08 this is what i have so far. with open('testfile5.txt','w') as testfile5: testfile5.write(a1) testfile5.close()
favorite count: 0
has answer: http://stackoverflow.com/a/49226491
tagged with: text-files
type: Question
has answer: http://stackoverflow.com/a/49226694
tagged with: python
possible better answer: http://stackoverflow.com/a/49226491
score: -2
accepted answer: http://stackoverflow.com/a/76558865
has answer: http://stackoverflow.com/a/76558865
tagged with: printing

http://stackoverflow.com/comment/85471466
score: 2
type: Comment
comment on: http://stackoverflow.com/q/49234219
type: QuestionComment
has text: you need `logging` library

http://stackoverflow.com/q/49235082
tagged with: flask
has comment: http://stackoverflow.com/comment/85473382
has body: first of all pls excuse my bad english skills ^^ My problem looks very simple to solve but I cant get flask_wtf running on my Raspberry Pi 3. I want to create a form with Flask-WTF but i am not able to import it. I first installed it with sudo pip install Flask-WTF When I import the module from flask_wtf import FlaskForm and run the program I get this: ImportError: No module named 'flask_wtf' If I try to install it again, I get: Requirement already satisfied: Flask-WTF in /usr/local/lib/python2.7/dist-packages Thanks in advance!
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85473714
tagged with: flask-wtforms
score: 1
accepted answer: http://stackoverflow.com/a/49235966
answer count: 1
downvote count: 0
upvote count: 1
tagged with: raspberry-pi3
has answer: http://stackoverflow.com/a/49235966
has title: ImportError with flask_wtf on Raspberry PI 3
tagged with: import
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/48654611
tagged with: python

http://stackoverflow.com/a/49252477
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85508915
answers question: http://stackoverflow.com/q/49252247
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/85509135
has body: yes, of course the size increases; you can check that with: from sys import getsizeof from decimal import Decimal, getcontext getcontext().prec = 6 d = Decimal(1)/Decimal(3) print(getsizeof(d)) # 104 getcontext().prec = 256 d = Decimal(1)/Decimal(3) print(getsizeof(d)) # 216 ymmv... the exact values may be implementation/platform specific.
has comment: http://stackoverflow.com/comment/85509976

restore
tag name: restore
tags question: http://stackoverflow.com/q/49191509
type: Tag

http://stackoverflow.com/comment/85263348
score: 0
comment on: http://stackoverflow.com/q/49129300
has text: https://www.python.org/dev/peps/pep-0328/#guido-s-decision
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49205354
tagged with: loops
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85416093
has comment: http://stackoverflow.com/comment/85416340
has comment: http://stackoverflow.com/comment/85416043
tagged with: python
has body: I'm working on some project and came up with the messy situation across where I've to split the data frame based on the first column of a data frame, So the situation is here the data frame I've with me is coming from SQL queries and I'm doing so much manipulation on that. So that is why not posting the code here. Target: The data frame I've with me is like the below screenshot, and its available as an xlsx file. Output: I'm looking for output like the attached file here: The thing is I'm not able to put any logic here that how do I get this done on dataframe itself as I'm newbie in Python.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49205595
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/49205595
answer count: 2
has answer: http://stackoverflow.com/a/49205473
possible better answer: http://stackoverflow.com/a/49205473
tagged with: pandas
upvote count: 1
has title: DataFrame Split On Rows and apply on header one column using Python Pandas
tagged with: xlsxwriter

http://stackoverflow.com/a/49251754
has comment: http://stackoverflow.com/comment/85508112
has comment: http://stackoverflow.com/comment/85507327
has comment: http://stackoverflow.com/comment/85507496
answers question: http://stackoverflow.com/q/49251560
has comment: http://stackoverflow.com/comment/85508334
type: Answer
has comment: http://stackoverflow.com/comment/85510532
score: 0
has comment: http://stackoverflow.com/comment/85507797
has comment: http://stackoverflow.com/comment/85507638
has body: have you tried like this, try with subprocess.Popen : import os import signal import time import subprocess process = subprocess.Popen("ssh root@192.168.180.11 'echo 'rootpass' | sudo -Sv &amp;&amp; bash -s' &lt; ../attaques/Ping_flood.sh &amp;", shell=True) time.sleep(5) os.killpg(process.pid, signal.SIGTERM)
has comment: http://stackoverflow.com/comment/85507750
has comment: http://stackoverflow.com/comment/85508522
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85509646
has comment: http://stackoverflow.com/comment/85508625
accepted answer of: http://stackoverflow.com/q/49251560

regex
tags question: http://stackoverflow.com/q/49228915
tags question: http://stackoverflow.com/q/49135476
tags question: http://stackoverflow.com/q/49197821
tags question: http://stackoverflow.com/q/49215041
tags question: http://stackoverflow.com/q/49267157
tags question: http://stackoverflow.com/q/49231405
tags question: http://stackoverflow.com/q/49216593
tags question: http://stackoverflow.com/q/49214894
tags question: http://stackoverflow.com/q/49279403
tags question: http://stackoverflow.com/q/49272973
tags question: http://stackoverflow.com/q/49191546
tags question: http://stackoverflow.com/q/49133716
tags question: http://stackoverflow.com/q/49192351
tags question: http://stackoverflow.com/q/49212623
tags question: http://stackoverflow.com/q/49156698
tags question: http://stackoverflow.com/q/49238027
tags question: http://stackoverflow.com/q/49272206
tags question: http://stackoverflow.com/q/49278714
tags question: http://stackoverflow.com/q/49142738
tags question: http://stackoverflow.com/q/49196515
tags question: http://stackoverflow.com/q/49137057
tags question: http://stackoverflow.com/q/49132092
tags question: http://stackoverflow.com/q/49252176
tags question: http://stackoverflow.com/q/49176643
tags question: http://stackoverflow.com/q/49201556
tag name: regex
tags question: http://stackoverflow.com/q/49247258
tags question: http://stackoverflow.com/q/49191577
tags question: http://stackoverflow.com/q/49215406
tags question: http://stackoverflow.com/q/49254224
tags question: http://stackoverflow.com/q/49258642
tags question: http://stackoverflow.com/q/49226885
tags question: http://stackoverflow.com/q/49129065
tags question: http://stackoverflow.com/q/49247168
tags question: http://stackoverflow.com/q/49234374
tags question: http://stackoverflow.com/q/49251946
tags question: http://stackoverflow.com/q/49166524
tags question: http://stackoverflow.com/q/49267293
tags question: http://stackoverflow.com/q/49184752
tags question: http://stackoverflow.com/q/49216652
tags question: http://stackoverflow.com/q/49233067
tags question: http://stackoverflow.com/q/49170237
tags question: http://stackoverflow.com/q/49131708
tags question: http://stackoverflow.com/q/49214466
tags question: http://stackoverflow.com/q/49214585
tags question: http://stackoverflow.com/q/49186639
tags question: http://stackoverflow.com/q/49272584
tags question: http://stackoverflow.com/q/49161183
tags question: http://stackoverflow.com/q/49171653
tags question: http://stackoverflow.com/q/49198225
tags question: http://stackoverflow.com/q/49251629
tags question: http://stackoverflow.com/q/49215525
tags question: http://stackoverflow.com/q/49142366
tags question: http://stackoverflow.com/q/49199283
tags question: http://stackoverflow.com/q/49269593
tags question: http://stackoverflow.com/q/49273039
tags question: http://stackoverflow.com/q/49204225
tags question: http://stackoverflow.com/q/49206003
tags question: http://stackoverflow.com/q/49183568
tags question: http://stackoverflow.com/q/49251322
tags question: http://stackoverflow.com/q/49269581
tags question: http://stackoverflow.com/q/49154240
tags question: http://stackoverflow.com/q/49254242
tags question: http://stackoverflow.com/q/49163663
tags question: http://stackoverflow.com/q/49278005
tags question: http://stackoverflow.com/q/49147276
tags question: http://stackoverflow.com/q/49265699
tags question: http://stackoverflow.com/q/49277003
tags question: http://stackoverflow.com/q/49140120
tags question: http://stackoverflow.com/q/49135250
tags question: http://stackoverflow.com/q/49242166
tags question: http://stackoverflow.com/q/49123277
tags question: http://stackoverflow.com/q/49262574
tags question: http://stackoverflow.com/q/49169725
tags question: http://stackoverflow.com/q/49178852
tags question: http://stackoverflow.com/q/49190411
tags question: http://stackoverflow.com/q/49219142
tags question: http://stackoverflow.com/q/49175624
tags question: http://stackoverflow.com/q/49217248
tags question: http://stackoverflow.com/q/49245954

http://stackoverflow.com/a/49210090
score: 0
has body: To achieve it you can define __enter__ and __exit__ inside your class and create your instance using with statement: import threading import multiprocessing class MyClass: def __init__(self): self.queue = None self.thread = None def __enter__(self): return self def __exit__(self, type, value, traceback): self.stop() def start(self): self.queue = multiprocessing.Queue() self.thread = threading.Thread(target=self.queued_writer, daemon=True) self.thread.start() def queued_writer(self): while 1: msg = self.queue.get() print("Message:", str(msg)) if msg is None: break def put(self, msg): self.queue.put(msg) def stop(self): self.queue.put(None) self.thread.join() with MyClass() as instance: instance.start() print('Thread stopped: ' + str(instance.thread._is_stopped)) instance.put('abc') print('Thread stopped: ' + str(instance.thread._is_stopped)) Above code gives as an output: Thread stopped: False Message: abc Message: None Thread stopped: True
answers question: http://stackoverflow.com/q/49209385
has comment: http://stackoverflow.com/comment/85424692
type: Answer

http://stackoverflow.com/q/49255283
downvote count: 1
linked to: http://stackoverflow.com/q/7670303
has answer: http://stackoverflow.com/a/49255390
accepted answer: http://stackoverflow.com/a/49255390
favorite count: 0
score: 9
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85513586
upvote count: 10
has comment: http://stackoverflow.com/comment/85513566
tagged with: python
has body: How can you run Flask app which uses a specific version of python? On my env "python" = python2.7 and "python3" = python3.6. I have installed Flask using pip3. I start the app with FLASK_APP=app.py flask run. It uses python2.7 to execute, I would like it to use python3.6. Also tried adding #!flask/bin/python3 to app.py, but it did not have an effect.
has answer: http://stackoverflow.com/a/61596986
possible better answer: http://stackoverflow.com/a/61596986
tagged with: flask
type: AnsweredQuestion
answer count: 2
has comment: http://stackoverflow.com/comment/85513569
has title: Run Flask using python3 not python

http://stackoverflow.com/a/49153875
type: Answer
answers question: http://stackoverflow.com/q/49150748
score: 0
has body: Another, possibly slower, solution: output_loops = (weights * pseudo_input[...,np.newaxis]).sum(axis=(0, 1, 2))

http://stackoverflow.com/a/49196427
score: 4
upvote count: 4
type: AcceptedAnswer
has body: So you have some data (I'm going to change the values because you have repeated X values with different Y): import numpy as np x1 = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]) y1 = np.array([1, 3, 4, 6, 7, 4, 6, 5, 2]) You can find different polynomial fits with np.polyfit: fit1 = np.polyfit(x1, y1, 1) # linear fit2 = np.polyfit(x1, y1, 2) # quadratic fit3 = np.polyfit(x1, y1, 3) # cubic You can check how good each of these is by evaluating the resulting polynomials with np.polyval: v1 = np.polyval(fit1, x1) v2 = np.polyval(fit2, x1) v3 = np.polyval(fit3, x1) These look like this: You can check numerically how well each of these fit for example calculating the mean squared error: mse1 = np.mean(np.square(y1 - v1)) # 3.240 mse2 = np.mean(np.square(y1 - v2)) # 0.734 mse3 = np.mean(np.square(y1 - v3)) # 0.727 Now, besides this, you can look at correlation. There are actually several kinds of correlation coefficients. NumPy implements the Pearson correlation coefficient in np.corrcoef: np.corrcoef(x1, y1) # [[ 1. , 0.27578314], # [ 0.27578314, 1. ]] This coefficient measures linear correlation, so it will not work well with non-linear relationships. However, non-linear correlation is in general a much more complicated topic (and still under research). You can look into some of the other correlation coefficients or investigate other techniques, but note that this will only tell you if there exists some correlation, it will not tell you whether you will be able to construct a model exploiting the correlation.
accepted answer of: http://stackoverflow.com/q/49179463
downvote count: 0
answers question: http://stackoverflow.com/q/49179463
has comment: http://stackoverflow.com/comment/85423967
type: Answer
has comment: http://stackoverflow.com/comment/85425188

http://stackoverflow.com/a/49227175
score: 0
answers question: http://stackoverflow.com/q/49227092
has body: Your code didn't work because you're using statements in the wrong way, such as hungry != True or False, here's a working version of your code: hungry = None while hungry not in (True, False): # Check if hungry is not True or False hungry = input('Hey, are you hungry?') if hungry in ('yes', 'ye', 'y', 'yeah'): print ('oh you hungry huh') hungry = True elif hungry in ('no', 'n', 'nah', 'nope'): print ('no food for you then') hungry = False else: print ('its a simple yes or no question pls')
type: Answer

http://stackoverflow.com/comment/85510939
has text: Your code does not seem Java to me. Why do you use that tag?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49253819

http://stackoverflow.com/q/49135355
has title: Overwritten TreeCtrl.OnCompareItems() not called in Python 3 - wxPython 4
upvote count: 5
downvote count: 0
tagged with: wxpython
tagged with: sorting
has comment: http://stackoverflow.com/comment/85369094
has comment: http://stackoverflow.com/comment/85369167
type: AnsweredQuestion
tagged with: python-2.7
has body: I have a wx.TreeCtrl structure where the user can sort the items by different criteria (date, name, id, descending, ascending, ...). This worked fine in Python 2, but Python 3 (with wxPython 4) refuses sorting. The method CTreeCtrl.OnCompareItems() is called in Python 2, but never in Python 3. In the functools.cmp_to_key documentation (https://docs.python.org/3/library/functools.html) I found a hint: Python 3 does not support comparison functions. Confusing: in the description of wx.TreeCtrl (wxPython 4) there is a comparison method OnCompareItems() (https://docs.wxpython.org/wx.TreeCtrl.html#wx.TreeCtrl.OnCompareItems). The description says, that together with this method I must use the RTTI macros DECLARE_DYNAMIC_CLASS and IMPLEMENT_DYNAMIC_CLASS since the baseclass does not know that I overwrote OnCompareItems(). I found only descriptions of how to use this macros in C++, but nothing for python. I have no idea how I could make my program calling my OnCompareItems() method in Python3/wxPython 4. Can anybody help? Regards, Humbalan Below there is a small sample programm which reflects the problem. It runs with Python 2 and Python 3 as well. The print( 'in CTreeCtrl.OnCompareItems()' ) shows, that this method is called (in py2) or not called (in py3): import sys import wx class CTreeCtrl( wx.TreeCtrl ): def __init__( self, parent ): super( CTreeCtrl, self ).__init__( parent=parent, style=wx.TR_HIDE_ROOT ) def OnCompareItems( self, item1, item2 ): print( 'in CTreeCtrl.OnCompareItems()' ) if sys.version_info.major &lt; 3: d1 = self.GetItemData( item1 ).Data d2 = self.GetItemData( item2 ).Data else: d1 = self.GetItemData( item1 ) d2 = self.GetItemData( item2 ) if d1 &lt; d2: return -1 elif d1 &gt; d2: return 1 else : return 0 class CSettingsTree( wx.Dialog ): def __init__( self, parent, settings ) : size = wx.Size(200,150) wx.Dialog.__init__( self, parent, title='all settings', size=size ) bSizer_main = wx.BoxSizer( wx.VERTICAL ) self.m_treeCtrl = CTreeCtrl( self ) bSi…
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/60622928
has answer: http://stackoverflow.com/a/60622928
favorite count: 0
type: Question
tagged with: python-3.x
score: 5
has comment: http://stackoverflow.com/comment/85276682

http://stackoverflow.com/comment/85256712
score: 1
has text: you got to change the request type. the logic you have written needs to be in POST method, change them, and also the form method in the html page to POST instead of GET
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49125925

http://stackoverflow.com/a/49175709
answers question: http://stackoverflow.com/q/49174476
score: 3
accepted answer of: http://stackoverflow.com/q/49174476
type: Answer
has comment: http://stackoverflow.com/comment/85387227
upvote count: 3
has comment: http://stackoverflow.com/comment/85393507
type: AcceptedAnswer
downvote count: 0
has body: There are a few ways to do this, but I'm not sure that any of them are as quick/simple as you're imagining. A lot of this also depends on what blogging platform you use. For example, the second example you posted looks more like raw code that has been copy/pasted and then formatted by their blogging platform Here's a few things you can try, but none of them offer direct "export cell" functionality. They also assume you only want a static notebook for display: Export to HTML Go to File &gt; Download as &gt; HTML This will give you a HTML page with all of your cells nicely rendered. Its not that trivial to extract specific cells to post on a blog, but if you just want to display your entire notebook you have everything as a HTML that you can upload to wherever your blog is. It will look exactly like your full notebook: Export basic HTML template You can use nbconvert to give you a basic HTML rendering of your notebook. Open a terminal, go to the directory where your notebook is located and type: jupyter nbconvert name_of_notebook.ipynb --template basic That will give you a html page without all of the flashy styling. This makes it much easier for you just copy/paste the specific cell you want (as HTML) into your blog. Your blog would then need some styling/syntax highlighting to make it look pretty This will look like a simple rendering of your notebook: As an aside, the first option (exporting the full HTML page) also uses nbconvert behind the scenes, just without the --template basic argument Export to markdown Go to File &gt; Download as &gt; Markdown If your blogging platform supports markdown, you can export your notebook as a markdown file without all of the styling and copy/paste the cell you want into your blog post. Again, you'd need a way to style it on your blog This will give you basic markdown code you can copy/paste anywhere: ```python a = 2 b = 5 print(a+b) ``` 7 Upload to nbviewer http://nbviewer.jupyter.org/ If you have your notebook uploaded as a git…

http://stackoverflow.com/comment/85401201
comment on: http://stackoverflow.com/a/49198132
type: AnswerComment
score: 1
has text: @AnonX Use `sort_values`: `df.groupby('code').note.agg(['count', 'first']).sort_values('count', ascending=False)`
type: Comment

http://stackoverflow.com/q/49251884
type: UnansweredQuestion
tagged with: pythonpath
tagged with: python
score: 0
answer count: 1
type: Question
has answer: http://stackoverflow.com/a/49252111
has title: Python script path
has body: Lets assume following directories tree: / home/ user/ X/ scripy.py Y/ a.c b.c I have a python script, with many commands using relative path, doing sth like this: def f1(relative_path_to_a, relative_path_to_c): abs_path = PATH_TO_PLACE_FROM_SCRIPT_WAS_CALLED c_abs_path = abs_path + relative_path_to_c file_a = open(relative_path_to_a) file_a.write(c_abs_path) close() As it found out, I need to use it on another machine, with different directories tree. There should also be a possibility to call script from other location, than the one where it is placed. Changing all paths to absolute will take some time, but is not impossible. On the other hand, I come up with an idea to change path on the beginning of the script, to /home/user/X (I did it by adding one more python file to X directory and calling inside of it abs_path = os.path.abspath("."), then in script.py I do os.chdir(second_script.abs_path). What are disadvantages of second solution? Are there any situations, where it can crash? To be precise, in the second solution, i'm doing sth line this: / home/ user/ X/ scripy.py second_scripy.py Y/ a.c b.c user@user:~$ pwd /home/ user@user:~$ python user/X/script.py

http://stackoverflow.com/a/49198865
has comment: http://stackoverflow.com/comment/85404303
answers question: http://stackoverflow.com/q/49198633
has body: You seem to be reinventing the GridSearchCV ;-) Try this approach: from sklearn.model_selection import GridSearchCV X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25) param_grid = dict(model__alpha=[0, 0.2, 0.4, 0.6, 0.8, 1]) model = Lasso() # put here algorithm, that you want to use folds = 3 # alternatively you can prepare folds yourself #folds = KFold(n_splits=folds, shuffle=False, random_state=1986) grid_search = GridSearchCV(model, param_grid=param_grid, cv=folds, n_jobs=-1, verbose=2) grid_search.fit(X_train, y_train) y_pred = grid_search.best_estimator_.predict(X_test)
upvote count: 2
has comment: http://stackoverflow.com/comment/85405885
has comment: http://stackoverflow.com/comment/85408095
score: 2
has comment: http://stackoverflow.com/comment/85404380
downvote count: 0
has comment: http://stackoverflow.com/comment/85408237
type: Answer

http://stackoverflow.com/q/49261197
type: Question
has answer: http://stackoverflow.com/a/49261841
accepted answer: http://stackoverflow.com/a/49261313
possible better answer: http://stackoverflow.com/a/49261841
has body: I have a list with the following structure: A1, B2, C3, 66 A1, B2, C3, 00 A2, B2, C3, 77 A3, B3, C4, 44 A4, B4, C5, 11 A4, B4, C5, 12 A4, B4, C5, 13 And I need to enumerate the unique 1-3 column elements to get the output like this: A1, B2, C3, 66, 1 A1, B2, C3, 00, 2 A2, B2, C3, 77, 1 A3, B3, C4, 44, 1 A4, B4, C5, 11, 1 A4, B4, C5, 12, 2 A4, B4, C5, 13, 3 As you understand, I want the ordinal number in the fourth column to order on unique value at 1-3 columns. After reading the instructions, I came to the conclusion that I need to use the collections module. Is this the right decision? I try this: new = ['A1,B2,C3,66','A1,B2,C3,00','A2, B2, C3, 77','A3, B3, C4, 44','A4, B4, C5, 11','A4, B4, C5, 12','A4, B4, C5, 13'] test=[] i = 0 for a in new: i+=1 test.append('{},{}'.format(i, a)) print(test) if a[i]!=a[i-1]: continue
tagged with: python
has title: Numbering coincidence in list
score: 2
upvote count: 2
type: AnsweredQuestion
tagged with: list
tagged with: for-loop
answer count: 3
has answer: http://stackoverflow.com/a/49261313
has answer: http://stackoverflow.com/a/49262033
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/85415148
type: Comment
has text: Sorry about that. The x-values are years, so from 2000 to 2016.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49204861

http://stackoverflow.com/comment/85550224
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49194871
has text: You could try adding locks and see if it solves your problem. Another check to add would be to put `print (id(X), id(b))` to your worker as first and last lines to ensure your global variables remain the same and they are not given local incarnations of the same name. Sorry I can't be of more assistance.

http://stackoverflow.com/a/49240292
upvote count: 5
type: Answer
score: 4
answers question: http://stackoverflow.com/q/49235994
has body: When you define your pool, you must specify a pool start task. This start task will be run on each node as it is created and joins the pool (or when it is rebooted, re-imaged). You can do it in the console under your pool. Or if you used Python, do it like this (this is an example, adjust as required!). Look at how the task_commands variable is defined (the curl is requried): def create_pool(batch_service_client, pool_id, resource_files, publisher, offer, sku): &quot;&quot;&quot; Creates a pool of compute nodes with the specified OS settings. :param batch_service_client: A Batch service client. :type batch_service_client: `azure.batch.BatchServiceClient` :param str pool_id: An ID for the new pool. :param list resource_files: A collection of resource files for the pool's start task. :param str publisher: Marketplace image publisher :param str offer: Marketplace image offer :param str sku: Marketplace image sku &quot;&quot;&quot; print('Creating pool [{}]...'.format(pool_id)) # Create a new pool of Linux compute nodes using an Azure Virtual Machines # Marketplace image. For more information about creating pools of Linux # nodes, see: # https://azure.microsoft.com/documentation/articles/batch-linux-nodes/ # Specify the commands for the pool's start task. The start task is run # on each node as it joins the pool, and when it's rebooted or re-imaged. # We use the start task to prep the node for running our task script. task_commands = [ 'cp -p {} $AZ_BATCH_NODE_SHARED_DIR'.format('YOUR-PYTHON-SCRIPT.py'), # Install pip 'curl -fSsL https://bootstrap.pypa.io/get-pip.py | python', # Install the azure-storage module so that the task script can access # Azure Blob storage, pre-cryptography version 'pip install azure-storage==0.32.0'] # Get the node agent SKU and image reference for the virtual machine # configuration. # For more information about the virtual machine configuration, see: # https://azure.microsoft.com/documentation/articles/batch-linux-nodes/ sku_to_use, image_r…
has comment: http://stackoverflow.com/comment/85556788
downvote count: 1
has comment: http://stackoverflow.com/comment/116623784

http://stackoverflow.com/comment/85492599
score: 0
type: AnswerComment
has text: See Martijn Pieter's answer for the details of the over-allocation algorithm. The naive approach is to just double the list every time it needs to be resized, but that tends to over allocate memory. (In a very hand wavy sense, each append makes the next append less likely--it has to stop growing *sometime*--, so later appends are more likely to allocate memory that won't be used. Python makes more smaller allocations to reduce wasted memory.
type: Comment
comment on: http://stackoverflow.com/a/49244140

http://stackoverflow.com/comment/85263515
has text: For that you need to buy dyno.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49128783

http://stackoverflow.com/comment/85473740
type: QuestionComment
has text: Your data structure is unclear, you have multiple lists and they are syntactically incorrect.
comment on: http://stackoverflow.com/q/49235268
score: 0
type: Comment

http://stackoverflow.com/q/49228252
has comment: http://stackoverflow.com/comment/85474022
downvote count: 0
has answer: http://stackoverflow.com/a/49229061
has comment: http://stackoverflow.com/comment/85460644
tagged with: python
accepted answer: http://stackoverflow.com/a/49229061
tagged with: data-science
has comment: http://stackoverflow.com/comment/85460337
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85460040
tagged with: pandas
score: 1
answer count: 1
tagged with: jupyter
upvote count: 1
tagged with: jupyter-notebook
favorite count: 0
type: Question
has body: This is a input and output from a jupyter notebook. I need help with identifying the reason why I am unable to accurately select and set the data in the 'went_out' column. Both the red underline cells are supposed to be displaying data from the datetime column of its own row but only one is accurately displaying it. It turns out that many of the rows that matched my condition did not get selected and set. This is a sample of the code I used: # your answer here df.loc[(df['reading_type'] == 'motion') &amp; (df['value'] == 255), 'event'] = 'motion on' df.loc[(df['reading_type'] == 'motion') &amp; (df['value'] == 0), 'event'] = 'motion off' df2 = df.loc[(df['reading_type'] == 'door') | (df['event'] == 'motion on')].copy() df2.loc[(df['event'] == 'door close') &amp; (df['event'].shift(-1) == 'door open'), 'went_out'] = df2['datetime'] df2 Here are the links for the jupyter notebook file and csv file: Jupyter Notebook: https://drive.google.com/file/d/15f6NQrM4UoAZlzRhK35TOKyhPJnmWWdU/view?usp=sharing CSV file: https://drive.google.com/file/d/1hZudSVbT91ESj2qkzrJ--CbVdrzVCmce/view?usp=sharing
has comment: http://stackoverflow.com/comment/85460115
has title: Python Pandas condition fails to identify rows accurately

http://stackoverflow.com/q/49182242
has answer: http://stackoverflow.com/a/49182305
has body: I have a list A= [1,2,3,3,4,4,5,6,4,7] I want to only keep one 3 and 4 if they are next to another identical one. Thus A should become A= [1,2,3,4,5,6,4,7] I tried to use set set[A] {1, 2, 3, 4, 5, 6, 7} But it removed the last 4 that I want to keep. It seems I should loop through the list and compare i and i+1. Wondering any faster and smarter way exists?
type: Question
has title: Python remove one of two duplicates (next to each other) in a list
duplicate of: http://stackoverflow.com/q/5738901
possible better answer: http://stackoverflow.com/a/49182346
tagged with: duplicates
has answer: http://stackoverflow.com/a/49182346
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: list
answer count: 2
linked to: http://stackoverflow.com/q/3460161
tagged with: set
accepted answer: http://stackoverflow.com/a/49182305
linked to: http://stackoverflow.com/q/5738901

http://stackoverflow.com/comment/85285863
type: Comment
type: QuestionComment
has text: No need to add them since their code is not really important
comment on: http://stackoverflow.com/q/49139855
score: 0

http://stackoverflow.com/q/49140099
type: Question
accepted answer: http://stackoverflow.com/a/49141391
has title: New Line Added in file write when inserting text
has answer: http://stackoverflow.com/a/49141391
tagged with: python
has body: I've tried several ways to append a string to a line being written to a file when reading from another file (as well as in place using fileinput). I'm definitely missing something but trying different approaches for a few hours has not fixed the problem. The latest approach is below, which still results in the imagelist being on a new line after the datarow where the goal is to output them to a single line. for datarow in oldfile: rowcols = datarow.split('|') imagelist = [] image_seed = rowcols[headers.index('Group ID')]+'_'+rowcols[headers.index('Case ID')]+'_'+rowcols[headers.index('Contact ID')] if isfirstrow: newfile.write(headerrow) isfirstrow = False else: for imagename in imagefiles: if image_seed in imagename: imagelist.append(os.path.basename(imagename)) if len(imagelist) &gt; 0: imagelist.insert(0, datarow) newfile.write('|'.join(imagelist)+'\n') else: newfile.write(datarow) Thanks in advance for you input!
type: AnsweredQuestion
tagged with: python-2.7
score: 1
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/85460963
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49228744
has text: Or, have you also installed `attrs`?

http://stackoverflow.com/comment/86308260
has text: I know, this is unsupported documentation but you can find LACP in Pyvmomi - https://github.com/vmware/pyvmomi/blob/master/docs/vim/dvs/VmwareDistributedVirtualSwitch/LacpGroupConfig.rst
comment on: http://stackoverflow.com/q/49221299
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85375980
has text: Welcome to SO! please read up on [how to ask a question](https://stackoverflow.com/help/asking) and provide a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve) that reproduces your problem.
type: Comment
comment on: http://stackoverflow.com/q/49185074
score: 1
type: QuestionComment

http://stackoverflow.com/comment/85551652
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49273932
type: Comment
has text: [When to open file in binary mode (b)?](https://stackoverflow.com/questions/31483253/when-to-open-file-in-binary-mode-b) answers that, with longer explanations of "text" mode than in the answers here.

http://stackoverflow.com/a/49151321
upvote count: 3
has body: This is one way. I'm not sure it can be vectorised. import pandas as pd df = pd.DataFrame({'A': [1, None, 'hello', True, 'world', 'mystr', 34.11]}) df['stringy'] = [isinstance(x, str) for x in df.A] # A stringy # 0 1 False # 1 None False # 2 hello True # 3 True False # 4 world True # 5 mystr True # 6 34.11 False
answers question: http://stackoverflow.com/q/49151010
downvote count: 0
type: Answer
score: 3

http://stackoverflow.com/comment/85505305
type: QuestionComment
has text: Perhaps you tried this in the interactive interpreter? In the interactive shell, any expression that you execute that doesn't produce `None` is *echoed*. But that only happens in the interactive interpreter, because for real production scripts, you don't want everything to be echoed all the time. You need to explicitly write out stuff you want to appear on the screen instead.
type: Comment
comment on: http://stackoverflow.com/q/49250833
score: 0

http://stackoverflow.com/q/49145666
downvote count: 0
has title: Connection aborted., error(104, 'Connection reset by peer') in Django
tagged with: python-requests
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49147005
type: UnansweredQuestion
has body: I have created an API in Django and inside that calling a third party API which accepts XML data. With 30 rows of XML it is working fine, for more rows throwing the error "Connection aborted.', error(104, 'Connection reset by peer')". The third party also provided a UI so I can test that up to 5000 rows they are accepting and returning proper result. The connection is not getting closed from either of the APIs. What issue can it be? Expected Result The post request should work properly for more data in the request as it is working fine for fewer data. Actual Result ConnectionError at /v1/send-sms/ ('Connection aborted.', error(104, 'Connection reset by peer')) Request Method: POST Request URL: http://example.com/v1/send-sms/ Django Version: 1.11 Exception Type: ConnectionError Exception Value: ('Connection aborted.', error(104, 'Connection reset by peer')) Exception Location: /home/user-135/sandbox/venv/local/lib/python2.7/site-packages/requests/adapters.py in send, line 490 Python Executable: /home/user-135/sandbox/venv/bin/python Python Version: 2.7.12 Python Path: ['/home/user-135/public_html/MyProject', '/home/user-135/sandbox/venv/lib/python2.7', '/home/user-135/sandbox/venv/lib/python2.7/plat-x86_64-linux-gnu', '/home/user-135/sandbox/venv/lib/python2.7/lib-tk', '/home/user-135/sandbox/venv/lib/python2.7/lib-old', '/home/user-135/sandbox/venv/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/user-135/sandbox/venv/local/lib/python2.7/site-packages', '/home/user-135/public_html/MyProject', '/home/user-135/public_html/MyProject'] Server time: Wed, 7 Mar 2018 10:55:19 +0530 Reproduction Steps import requests recievers = '' url = 'https://example.com/sms/' for x in xrange(0, len(users)): y = x + 1 body_content = body phone = mobile_no recievers = recievers + " ....... " xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n \n \n<USER USERNAME=\""+username+"\" PASSWORD=\""+password+"\…
tagged with: django
has answer: http://stackoverflow.com/a/66935148
tagged with: python
score: 2
tagged with: python-2.7
answer count: 2
upvote count: 2

http://stackoverflow.com/comment/85555702
comment on: http://stackoverflow.com/q/49276477
type: Comment
has text: @AxeonThra, nothing really changes.
type: QuestionComment
score: 0

http://stackoverflow.com/a/49137619
accepted answer of: http://stackoverflow.com/q/49136319
answers question: http://stackoverflow.com/q/49136319
type: AcceptedAnswer
score: 0
has body: I think one of the biggest improvements you could make is to use a dictionary. Instead of looping through all of the artist_tuples for each filename in files, you can just do a single lookup in a dictionary for each of the filenames in files. This should speed up your code quite a bit. I wasn't sure if you have to have the output back into tuples so the first example does that but the other one outputs the results in a dictionary (basically a sub-dictionary of by_filename filtered by files). In[2]: artist_tuples = [ ...: ('House Manhufe','102257.jpg'), ...: ('Bernett Newman','75232.jpg'), ...: ('House Manhufe','32145.jpg'), ...: ('Kiri nichol','20304.jpg'), ...: ('Wolfgang', '48876.jpg'), ...: ('Arabesque','63861.jpg'), ...: ('Francis','99442.jpg') ...: ] In[3]: files = ['102257.jpg','75232.jpg','32145.jpg','20304.jpg'] In[4]: by_filename = {filename: artist for artist, filename in artist_tuples} In[5]: final_artist_filenames = [] ...: for filename in files: ...: try: ...: artist = by_filename[filename] ...: except KeyError: ...: pass ...: else: ...: final_artist_filenames.append((artist, filename)) ...: In[6]: final_artist_filenames Out[6]: [('House Manhufe', '102257.jpg'), ('Bernett Newman', '75232.jpg'), ('House Manhufe', '32145.jpg'), ('Kiri nichol', '20304.jpg')] In[7]: by_filename_only_from_files = {} ...: for filename in files: ...: try: ...: artist = by_filename[filename] ...: except KeyError: ...: pass ...: else: ...: by_filename_only_from_files[filename] = artist ...: In[8]: by_filename_only_from_files Out[8]: {'102257.jpg': 'House Manhufe', '20304.jpg': 'Kiri nichol', '32145.jpg': 'House Manhufe', '75232.jpg': 'Bernett Newman'}
type: Answer

http://stackoverflow.com/a/74639392
type: Answer
answers question: http://stackoverflow.com/q/49224022
score: 0
has body: mark and then find the first one that didn't find nums = [ 6, 4, 3, -5, 0, 2, -7, 1 ] def check_min(nums): marks = [-1] * len(nums) for idx, num in enumerate(nums): if num &gt;= 0: marks[num] = idx for idx, mark in enumerate(marks): if mark == -1: return idx return idx + 1

http://stackoverflow.com/comment/85422988
type: AnswerComment
has text: @TarunK Keyur Potdar Answer has nice explanation, go through that and you will understand it. Mainly the first line will clear your doubt.
comment on: http://stackoverflow.com/a/49209177
type: Comment
score: 0

http://stackoverflow.com/comment/85370515
comment on: http://stackoverflow.com/q/49182123
has text: A = randomSet (5, 100), but in the latter function I am trying to iterate over the list, and add the contents to a new set.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49227242
downvote count: 0
has title: How does await give back control to the event loop during coroutine chaining?
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85458575
has answer: http://stackoverflow.com/a/49227296
accepted answer: http://stackoverflow.com/a/49227296
tagged with: python-asyncio
score: 10
upvote count: 10
tagged with: async-await
tagged with: python
has body: I'm trying my hand at asyncio in Python 3.6 and having a hard time figuring out why this piece of code is behaving the way it is. Example code: import asyncio async def compute_sum(x, y): print("Compute %s + %s ..." % (x, y)) await asyncio.sleep(5) print("Returning sum") return x + y async def compute_product(x, y): print("Compute %s x %s ..." % (x, y)) print("Returning product") return x * y async def print_computation(x, y): result_sum = await compute_sum(x, y) result_product = await compute_product(x, y) print("%s + %s = %s" % (x, y, result_sum)) print("%s * %s = %s" % (x, y, result_product)) loop = asyncio.get_event_loop() loop.run_until_complete(print_computation(1, 2)) Output: Compute 1 + 2 ... Returning sum Compute 1 x 2 ... Returning product 1 + 2 = 3 1 * 2 = 2 Expected Output: Compute 1 + 2 ... Compute 1 x 2 ... Returning product Returning sum 1 + 2 = 3 1 * 2 = 2 My reasoning for expected output: While the compute_sum coroutine is correctly called before the compute_product coroutine, my understanding was that once we hit await asyncio.sleep(5), the control would be passed back to the event loop which would start the execution of the compute_product coroutine. Why is "Returning sum" being executed before we hit the print statement in the compute_product coroutine?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58611539
possible better answer: http://stackoverflow.com/a/58611539
answer count: 2

http://stackoverflow.com/a/49266855
type: Answer
has body: Something along these lines should work: new_index = list(df.index) new_index[-1] = 'string' df.index=new_index For example: df=pd.DataFrame(np.random.random(5)) &gt;&gt;&gt; df 0 0 0.665922 1 0.591298 2 0.274722 3 0.561243 4 0.382927 new_index = list(df.index) new_index[-1] = 'string' df.index=new_index returns a re-indexed df: &gt;&gt;&gt; df 0 0 0.665922 1 0.591298 2 0.274722 3 0.561243 string 0.382927
has comment: http://stackoverflow.com/comment/85735860
answers question: http://stackoverflow.com/q/49266798
score: 0

http://stackoverflow.com/comment/85291389
has text: @Evert Ah I see. Thank you for that clarification. I removed that and it posts to the DB and I no longer get the error.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49142635
type: QuestionComment

http://stackoverflow.com/comment/85312552
comment on: http://stackoverflow.com/q/49153792
has text: Which OS are you on and which project are you referring to. Could you share a link?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49226554
accepted answer of: http://stackoverflow.com/q/49226531
has comment: http://stackoverflow.com/comment/85457082
score: 0
answers question: http://stackoverflow.com/q/49226531
has comment: http://stackoverflow.com/comment/85456944
has body: You've created a circular dependency. app wants to import app.api.controllers, but that wants to import from app. What you should do to fix it, is to create a new module containing main_dict and import that in both app and app.api.controllers: # app/__init__.py from .main_dict import main_dict from .api.controllers import api # app/main_dict.py main_dict = {'a': 'A'} # app/api/__init__.py # app/api/controllers.py from flask import current_app as app from ..main_dict import main_dict if you need access to the app outside of app/__init__.py, the recommended way to get at it is to use from flask import current_app
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85457019
type: Answer

http://stackoverflow.com/a/49247599
type: Answer
upvote count: 16
has body: Without duplicates If your objects are hashable and your lists have no duplicates, you can create an inverted index of the first list and then traverse the second list. This traverses each list only once and thus is O(n). def find_matching_index(list1, list2): inverse_index = { element: index for index, element in enumerate(list1) } return [(index, inverse_index[element]) for index, element in enumerate(list2) if element in inverse_index] find_matching_index([1,2,3], [3,2,1]) # [(0, 2), (1, 1), (2, 0)] With duplicates You can extend the previous solution to account for duplicates. You can keep track of multiple indices with a set. def find_matching_index(list1, list2): # Create an inverse index which keys are now sets inverse_index = {} for index, element in enumerate(list1): if element not in inverse_index: inverse_index[element] = {index} else: inverse_index[element].add(index) # Traverse the second list matching_index = [] for index, element in enumerate(list2): # We have to create one pair by element in the set of the inverse index if element in inverse_index: matching_index.extend([(x, index) for x in inverse_index[element]]) return matching_index find_matching_index([1, 1, 2], [2, 2, 1]) # [(2, 0), (2, 1), (0, 2), (1, 2)] Unfortunately, this is no longer O(n). Consider the case where you input [1, 1] and [1, 1], the output is [(0, 0), (0, 1), (1, 0), (1, 1)]. Thus by the size of the output, the worst case cannot be better than O(n^2). Although, this solution is still O(n) if there are no duplicates. Non-hashable objects Now comes the case where your objects are not hashable, but comparable. The idea here will be to sort your lists in a way that preserves the origin index of each element. Then we can group sequences of elements that are equal to get matching indices. Since we make heavy use of groupby and product in the following code, I made find_matching_index return a generator for memory efficiency on long lists. from itertools import groupby, product def f…
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49247506
downvote count: 0
score: 16
has comment: http://stackoverflow.com/comment/85499087
accepted answer of: http://stackoverflow.com/q/49247506
has comment: http://stackoverflow.com/comment/85498986

http://stackoverflow.com/comment/85297409
has text: @juanpa.arrivillaga was trying to find out if its possible without iterating a loop.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49146274

http://stackoverflow.com/comment/85316696
has text: @jpp, done. Thanks.
score: 0
comment on: http://stackoverflow.com/q/49154375
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85334669
comment on: http://stackoverflow.com/a/49162908
type: Comment
score: 0
type: AnswerComment
has text: @Dark, I wasn't sure if the OP wants company as a column or index. You are right, it could be a bit easier if he wants column.

http://stackoverflow.com/a/49159595
has comment: http://stackoverflow.com/comment/85358486
answers question: http://stackoverflow.com/q/49159523
score: 0
has comment: http://stackoverflow.com/comment/85335965
has body: Use a loop, enumerate to get the index, and use integer division to calculate the 2nd number. for i, s in enumerate(myList): print(i, s, i // 2 + 1)
type: Answer

http://stackoverflow.com/a/49194357
answers question: http://stackoverflow.com/q/49194107
has comment: http://stackoverflow.com/comment/85393540
type: Answer
has body: Whatever you do, please don't look up the presence of a dictionary key from the list returned by d.keys(). Much more efficient is to query the dictionary directly. (Disclaimer: apparantly this only applies to Python 2, as the view returned in Python 3 also enables efficient membership tests...) Then you can just fetch the index of the first item that has the key, e.g., like this: idx = next((i for i,d in enumerate(listofpeople) if "Jack" in d), None) For reference: https://docs.python.org/3/library/functions.html#next https://docs.python.org/3/library/functions.html#enumerate https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
has comment: http://stackoverflow.com/comment/85393841
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85393417
score: 1

http://stackoverflow.com/comment/85285880
has text: If you want `--components` to apply to computers in general *and* a specific type of computer, then each computer would have to be a subcommand as well. `argparse` isn't the way to parse this kind of query language.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49140017
score: 0

http://stackoverflow.com/comment/85401721
comment on: http://stackoverflow.com/a/49198281
type: Comment
type: AnswerComment
has text: @rsc05 Not experienced with ST plugins, but you can google "how to add python plugins to sublime text". A quick search gives me http://sublimetext.info/docs/en/extensibility/plugins.html
score: 1

http://stackoverflow.com/comment/96745313
score: 0
type: AnswerComment
has text: Does not work. Just puts the whole dataset into the first cell of the Excel file instead of rendering it as a table(s)
comment on: http://stackoverflow.com/a/49209740
type: Comment

http://stackoverflow.com/q/49278341
has comment: http://stackoverflow.com/comment/85559737
tagged with: python
has answer: http://stackoverflow.com/a/49278467
has body: Basically, I want to modify a base class attribute in one of its child classes, and afterwards keep the new value, so the rest of child classes inheriting from the parent class will have the new value: class Parent(object): x = False class Child1(Parent): x = True Now if I have another child class and call its x attribute, I want it to be 'True' rather than 'False'. How do I do this?
tagged with: python-2.7
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85559856
has title: Python: how to change an attribute of a parent class via child class?
type: Question
has comment: http://stackoverflow.com/comment/85559151
type: UnansweredQuestion

http://stackoverflow.com/a/49204007
has body: For this task, as stated, try / except is a solution which should deal with all cases. pd.DataFrame.applymap applies a function to each element in the dataframe. def CheckInt(s): try: int(s) return True except ValueError: return False res = df[df.applymap(CheckInt).all(axis=1)].astype(int) # 0 1 2 3 4 5 6 7 # 0 1 2017 0 321 3 20 42 18 # 3 4 1811 0 822 8 13 65 18
answers question: http://stackoverflow.com/q/49203951
has comment: http://stackoverflow.com/comment/85413732
has comment: http://stackoverflow.com/comment/85413834
upvote count: 5
has comment: http://stackoverflow.com/comment/85413773
type: Answer
score: 5
downvote count: 0

http://stackoverflow.com/comment/85353295
has text: do you need to implement the derivative function yourself (e.g. as part of an assignment), or could you use existing libraries? Because there's theano (http://deeplearning.net/software/theano/tutorial/gradients.html) and autograd (https://github.com/HIPS/autograd/blob/master/docs/tutorial.md), for instance.
comment on: http://stackoverflow.com/q/49170908
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49258872
tagged with: function
has comment: http://stackoverflow.com/comment/85521366
answer count: 1
has answer: http://stackoverflow.com/a/49259103
has body: I have the following code to give Signals (1 or 0) The issue is I have a List of stocks close price ['SPY','TLT',.... etc] What I am doing now is changing the stock = df[] manually for each stock. Can you advise how to create a function for this please? Also df['Signal'] should be unique for each.. for example df['SPY'] will produce df['SPYsignal'] I am too new to python and have tried with errors, hopefully you can guide me thanks. # I am doing this for all my tickers, this is inefficient # Only wanted to do it for selected columns so I should begin with List = 'SPY','TLT' yes? stock = df['SPY'] df['avg'] = stock.shift(1).rolling(window=5).mean() df['LongEntry'] = stock &gt; df.avg df['LongExit'] = stock &lt; df.avg df['PositionLong'] = np.nan df.loc[df.LongEntry,'PositionLong'] = 1 df.loc[df.LongExit, 'PositionLong'] = 0 df['SPYSignal'] = df.PositionLong df['SPYSignal'].fillna(method='ffill') df['SPYSignal'].fillna(0, inplace = True) print (df['SPYSignal']) stock = df['TLT'] df['avg'] = stock.shift(1).rolling(window=5).mean() df['LongEntry'] = stock &gt; df.avg df['LongExit'] = stock &lt; df.avg df['PositionLong'] = np.nan df.loc[df.LongEntry,'PositionLong'] = 1 df.loc[df.LongExit, 'PositionLong'] = 0 df['TLTSignal'] = df.PositionLong df['TLTSignal'].fillna(method='ffill') df['TLTSignal'].fillna(0, inplace = True) print (df['TLTSignal']) Dataframe Sample SPY TLT 100 200 102 202 105 208 106 205 108 210 Desired Output SPY TLT SPYSignal TLTSignal 100 200 0 1 102 202 1 0 105 208 0 0 106 205 1 0 108 210 0 1
type: AnsweredQuestion
score: 0
tagged with: pandas
tagged with: dataframe
tagged with: python
accepted answer: http://stackoverflow.com/a/49259103
type: Question
has comment: http://stackoverflow.com/comment/85520896
has title: Repeat a Calculation for Each item in a Dataframe list and name it uniquely

pandas-groupby
tags question: http://stackoverflow.com/q/49208499
tags question: http://stackoverflow.com/q/49132761
type: Tag
tags question: http://stackoverflow.com/q/49262865
tags question: http://stackoverflow.com/q/49197937
tags question: http://stackoverflow.com/q/49269856
tags question: http://stackoverflow.com/q/49232243
tags question: http://stackoverflow.com/q/49162051
tags question: http://stackoverflow.com/q/49156883
tags question: http://stackoverflow.com/q/49161202
tags question: http://stackoverflow.com/q/49157048
tags question: http://stackoverflow.com/q/49222772
tags question: http://stackoverflow.com/q/49216357
tags question: http://stackoverflow.com/q/49177741
tags question: http://stackoverflow.com/q/49183759
tags question: http://stackoverflow.com/q/49157164
tags question: http://stackoverflow.com/q/49268619
tags question: http://stackoverflow.com/q/49223373
tags question: http://stackoverflow.com/q/49235545
tags question: http://stackoverflow.com/q/49239652
tags question: http://stackoverflow.com/q/49139665
tags question: http://stackoverflow.com/q/49169705
tags question: http://stackoverflow.com/q/49180567
tag name: pandas-groupby
tags question: http://stackoverflow.com/q/49249404
tags question: http://stackoverflow.com/q/49220479
tags question: http://stackoverflow.com/q/49264510
tags question: http://stackoverflow.com/q/49216865
tags question: http://stackoverflow.com/q/49263066
tags question: http://stackoverflow.com/q/49261388
tags question: http://stackoverflow.com/q/49135821
tags question: http://stackoverflow.com/q/49245918
tags question: http://stackoverflow.com/q/49215714
tags question: http://stackoverflow.com/q/49173597
tags question: http://stackoverflow.com/q/49264407
tags question: http://stackoverflow.com/q/49151170

http://stackoverflow.com/a/49138608
score: 1
type: Answer
has body: What is happening is location and field both become part of **kwargs or, in this case **user_info. kwargs stands for keyword arguments and thus Python recognizes that the user can enter a number of keyword parameters, and will happily accept them. What is happening at a deeper level is a dictionary is passed to build profile that looks something like this: user_info = {'location':'princeton', 'field':'physics'} This means that it is possible to pass a dictionary to any **kwargs argument. In the case of supplying keywords instead, Python will, in essence, build the dictionary automatically.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49138545
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49138545

http://stackoverflow.com/a/49129997
answers question: http://stackoverflow.com/q/49129349
has body: Adding rows with loc is quite inefficient (every time you add a row the columns' underlying arrays are recreated). Instead, prepare all the data and create the whole dataframe at once: lines = [] for ind1 in itemList: item1user = itemuser_dict[ind1] for ind2 in itemList: if ind1 == ind2: continue item2user = itemuser_dict[ind2] commonUsers = len(item1user.intersection(item2user)) affinity_score = commonUsers / len(item1user) lines.append({'item1': ind1, 'item2': ind2, 'score': affinity_score}) itemAffinity = pd.DataFrame(data=lines, columns=('item1', 'item2', 'score')) Keep in mind that columns is not necessary, but it makes sure the columns will be in the order you expect them. Also keep in mind that you have an O(n^2) algorithm (nested for loops on the same list) and it is not clear if (item1user, item2user) is the same as (item2user, item1user). If so, you can greatly decrease the number of iterations by using itertools.combinations: import itertools combinations = itertools.combinations(itemList, r=2) lines = [] for ind1, ind2 in combinations: item1user = itemuser_dict[ind1] item2user = itemuser_dict[ind2] commonUsers = len(item1user.intersection(item2user)) affinity_score = commonUsers / len(item1user) lines.append({'item1': ind1, 'item2': ind2, 'score': affinity_score}) itemAffinity = pd.DataFrame(data=lines, columns=('item1', 'item2', 'score'))
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/85265563

http://stackoverflow.com/comment/85489590
type: Comment
type: QuestionComment
has text: Are you using [`.read_csv`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html)?
comment on: http://stackoverflow.com/q/49242884
score: 0

http://stackoverflow.com/comment/85496815
score: 2
has text: Your last example is what [the documentation suggests](https://sqlalchemy-utils.readthedocs.io/en/latest/data_types.html#sqlalchemy_utils.types.password.PasswordType). Does that not work properly for you?
type: Comment
comment on: http://stackoverflow.com/q/49246527
type: QuestionComment

airflow
tags question: http://stackoverflow.com/q/49139821
tags question: http://stackoverflow.com/q/49177246
tags question: http://stackoverflow.com/q/49184502
tag name: airflow
type: Tag

http://stackoverflow.com/comment/98349116
has text: @Vj there is a typo in line 3 `df = df.rename(columns={'Date of the document': 'ds','Quantity sold': 'y', 'Article bar code': 'article'})` should be: `df2 = df.rename(columns={'Date of the document': 'ds','Quantity sold': 'y', 'Article bar code': 'article'})` no?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49241361

http://stackoverflow.com/q/49163449
answer count: 4
has answer: http://stackoverflow.com/a/49177470
has answer: http://stackoverflow.com/a/49163623
type: Question
has title: How to store first N strings from a txt file in Python?
accepted answer: http://stackoverflow.com/a/49163957
upvote count: 2
score: 2
has answer: http://stackoverflow.com/a/49163957
has comment: http://stackoverflow.com/comment/85332814
downvote count: 0
has answer: http://stackoverflow.com/a/49163662
possible better answer: http://stackoverflow.com/a/49163623
has comment: http://stackoverflow.com/comment/85333255
favorite count: 0
type: AnsweredQuestion
has body: I'm trying to figure out how to get the first N strings from a txt file, and store them into an array. Right now, I have code that gets every string from a txt file, separated by a space delimiter, and stores it into an array. However, I want to be able to only grab the first N number of strings from it, not every single string. Here is my code (and I'm doing it from a command prompt): import sys f = open(sys.argv[1], "r") contents = f.read().split(' ') f.close() I'm sure that the only line I need to fix is: contents = f.read().split(' ') I'm just not sure how to limit it here to N number of strings.
has comment: http://stackoverflow.com/comment/85332935
tagged with: python
has comment: http://stackoverflow.com/comment/85332611

http://stackoverflow.com/comment/85547345
comment on: http://stackoverflow.com/q/49271785
type: QuestionComment
score: 0
has text: Thanks. I'll make the edit! However, even when I add that it is the same issue.
type: Comment

http://stackoverflow.com/q/49180678
favorite count: 0
tagged with: pattern-matching
type: Question
has answer: http://stackoverflow.com/a/49180776
has body: I'm using re.findall to parse the year and month from a string, however it is only outputting patterns from half the string. Why is this? date_string = '2011-1-1_2012-1-3,2015-3-1_2015-3-3' find_year_and_month = re.findall('[1-2][0-9][0-9][0-9]-[1-12]', date_string) print(find_year_and_month) and my output is this: ['2011-1', '2012-1'] This is the current output for those dates but why am I only getting pattern matching for half the string?
upvote count: 0
possible better answer: http://stackoverflow.com/a/49180774
linked to: http://stackoverflow.com/q/3148240
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49180776
has title: re.findall only finding half the patterns
type: AnsweredQuestion
answer count: 2
duplicate of: http://stackoverflow.com/q/3148240
linked to: http://stackoverflow.com/q/7105146
has comment: http://stackoverflow.com/comment/85366989
tagged with: string-parsing
has answer: http://stackoverflow.com/a/49180774
downvote count: 1

http://stackoverflow.com/comment/85488729
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49211055
has text: @Venguiat Object references and callbacks can be read about Python as well. They're not specific to tkinter. You may want to read about callbacks for tkinter [here](https://stackoverflow.com/q/6920302/7032856) perhaps.

http://stackoverflow.com/comment/85542096
score: 0
comment on: http://stackoverflow.com/q/49269134
has text: @Adam Smith --- It's also a dictionary. It works quite well in my jumble solver program. https://stackoverflow.com/questions/35757407/how-to-add-dictionary-to-pyenchant
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49177369
type: Question
has answer: http://stackoverflow.com/a/49178126
accepted answer: http://stackoverflow.com/a/49178126
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85361210
has comment: http://stackoverflow.com/comment/85361605
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85361061
has title: Sentences in columns SQLite
has comment: http://stackoverflow.com/comment/85361330
tagged with: sqlite
answer count: 1
has body: I'm programming a little directory, with SQLite, python and tkinter. I have a problem when I insert more than one word in one column of the database, when I insert a name with more than two words it appears in {} (as it is shown in the picture) and not as it is in the other columns, how can I solve this? Backend: import sqlite3 def connect(): """Set up a connection with the database.""" conn_obj = sqlite3.connect("Database.db") cur_obj = conn_obj.cursor() cur_obj.execute("CREATE TABLE IF NOT EXISTS " "book (id integer PRIMARY KEY, " "title text, " "name text, " "email text, " "address text, " "telephone integer, " "cellphone integer, " "description text, " "company text, " "addresscompany text, " "telephonecompany integer, " "cellphonecompany integer, " "company text)") conn_obj.commit() conn_obj.close() def insert(title, name, email, address, telephone, cellphone, description, company, addresscompany, telephonecompany, cellphonecompany, comment): """Insert entry into database.""" conn_obj = sqlite3.connect("Database.db") cur_obj = conn_obj.cursor() cur_obj.execute("INSERT INTO book " "VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (title, name, email, address, telephone, cellphone, description, company, addresscompany, telephonecompany, cellphonecompany, comment)) conn_obj.commit() conn_obj.close() connect() def view(): """View all database entries.""" conn_obj = sqlite3.connect("Database.db") cur_obj = conn_obj.cursor() cur_obj.execute("SELECT * FROM book") rows = cur_obj.fetchall() conn_obj.close() return rows Frontend: from tkinter import * import backend def add_command(): """Insert entry via button.""" backend.insert(title_text.get(), name_text.get(), email_text.get(), address_text.get(), telephone_text.get(), cellphone_text.get(), description_text.get(), company_text.get(), addresscompany_text.get(), telephonecompany_text.get(), cellphonecompany_text.get(), comment_text.get()) listing.delete(0, END) listing.insert(END, (title_text.get(), name_text.get(),…

http://stackoverflow.com/q/49227249
answer count: 3
has title: Python 3, list.append not working
possible better answer: http://stackoverflow.com/a/49227279
tagged with: python
score: -1
accepted answer: http://stackoverflow.com/a/49227403
has answer: http://stackoverflow.com/a/49227279
tagged with: append
has answer: http://stackoverflow.com/a/49227403
type: Question
has body: New here and have been hunting around for the answer to this question. Working on a Project Euler question and attempting to add values of a function to a list using list.append, however nothing is being added to the list and I'm unsure why. Any help appreciated. import math import logging %config Application.log_level="INFO" input = 600851475143 factlist = [] def factors(i): for i in range(1, int(math.sqrt(input)) + 1): if(input%i == 0): factlist.append() print(i) Have tried defining the list inside and outside of the loop but to no avail.
downvote count: 2
has comment: http://stackoverflow.com/comment/85458341
has comment: http://stackoverflow.com/comment/85458490
has comment: http://stackoverflow.com/comment/85458418
upvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85458329
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/49227314

http://stackoverflow.com/a/49174442
type: Answer
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49174315
has body: You should prefer to use the unittest assertions so for example self.assertEqual(1, 2) Also you can use the teamcity-messages module to emit test messages the TeamCity will handle appropriately. Then you could change your main (if you have one) to something like the following import teamcity from teamcity.unittestpy import TeamcityTestRunner if __name__ == '__main__': if teamcity.is_running_under_teamcity(): runner = TeamcityTestRunner() else: runner = unittest.TextTestRunner() unittest.main(testRunner=runner)
has comment: http://stackoverflow.com/comment/85354775

http://stackoverflow.com/a/72885500
has body: I faced the same error installing TF 1.7 on Linux with Python 3.6 via conda install tensorflow-gpu==1.7 -c free -y. For some reason, during one of the runs I got not only the error message F tensorflow/core/kernels/conv_ops.cc:712] Check failed: stream-&gt;parent()-&gt;GetConvolveAlgorithms( conv_parameters.ShouldIncludeWinogradNonfusedAlgo&lt;T&gt;(), &amp;algorithms) but also E tensorflow/stream_executor/cuda/cuda_dnn.cc:396] Loaded runtime CuDNN library: 7103 (compatibility version 7100) but source was compiled with 7005 (compatibility version 7000). If using a binary install, upgrade your CuDNN library to match. If building from sources, make sure the library loaded at runtime matches a compatible version specified during compile configuration. right before it. So, based on the answer here, I ran conda install cudnn==7.0.5 to change the version of cudnn installed automatically along with tensorflow-gpu==1.7, and now it works. However, it still takes a lot of time before the training starts.
answers question: http://stackoverflow.com/q/49132736
type: Answer
score: 0

kibana
tags question: http://stackoverflow.com/q/49146039
tag name: kibana
type: Tag

http://stackoverflow.com/q/49150036
upvote count: 5
has comment: http://stackoverflow.com/comment/85347735
has title: Unable to run python script in virtualenv using bash script
has comment: http://stackoverflow.com/comment/85305510
has comment: http://stackoverflow.com/comment/85322568
favorite count: 0
has answer: http://stackoverflow.com/a/54195231
has body: I want to run a python script in in-built anaconda environment tensorflow_p36. To check if it is in virtual environment or not, I am using command pip -V. My first attempt at bash script: #!/bin/bash source activate tensorflow_p36 python /home/ec2-user/abc/temp.py pip -V Note: tensorflow_p36 being an in-built environment, does not require to be called from specific /env/bin directory. It can be activated from any directory. I think it's a feature of Amazon Deep Learning AMIs. My second attempt at bash script: #!/bin/bash pythonEnv="/home/ec2-user/anaconda3/envs/tensorflow_p36/" source ${pythonEnv}bin/activate ${pythonEnv}bin/python /home/ec2-user/abc/temp.py pip -V Note: When I try to run source /home/ec2-user/anaconda3/envs/tensorflow_p36/bin/activate command in terminal, the environment isn't being activated. Each time, I am getting the same result: pip 9.0.1 from /home/ec2-user/anaconda3/lib/python3.6/site-packages (python 3.6) Whereas, I should be getting: pip 9.0.1 from /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages (python 3.6) Can someone please explain how do I activate virtual environment and run a python script from that environment? I need to use this particular environment because of the dependencies installed in it. Extra info: Not sure if it matters, but the tensorflow_p36 is a conda environment, not a virtualenv.
has comment: http://stackoverflow.com/comment/85304817
has comment: http://stackoverflow.com/comment/85304757
has comment: http://stackoverflow.com/comment/85306764
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/85305811
tagged with: python
has comment: http://stackoverflow.com/comment/85347862
tagged with: virtualenv
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85306643
has comment: http://stackoverflow.com/comment/85305190
answer count: 1
tagged with: conda
has comment: http://stackoverflow.com/comment/85347101
has comment: http://stackoverflow.com/comment/85306030
tagged with: bash
has comment: http://stackoverflow.com/comment/85304686
has comment: http://stackoverflow.com/comment/85305016
type: Question
has comment: http://stackoverflow.com/comment/85308440
has comment: http://stackoverflow.com/comment/85305368
has comment: http://stackoverflow.com/comment/85306995

encoding
tags question: http://stackoverflow.com/q/49174304
tag name: encoding
type: Tag
tags question: http://stackoverflow.com/q/49160878
tags question: http://stackoverflow.com/q/49166171
tags question: http://stackoverflow.com/q/49150550
tags question: http://stackoverflow.com/q/49158184
tags question: http://stackoverflow.com/q/49197793
tags question: http://stackoverflow.com/q/49179132
tags question: http://stackoverflow.com/q/49232180
tags question: http://stackoverflow.com/q/49123937
tags question: http://stackoverflow.com/q/49176277
tags question: http://stackoverflow.com/q/49162044
tags question: http://stackoverflow.com/q/49150948
tags question: http://stackoverflow.com/q/49129888
tags question: http://stackoverflow.com/q/49153905
tags question: http://stackoverflow.com/q/49175185

http://stackoverflow.com/q/49138692
has answer: http://stackoverflow.com/a/49146456
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85282518
has body: Similar question: What&#39;s the advantage of a trailing underscore in Python naming?. This addresses advantages/disadvantages, whereas this addresses the reasoning behind doing it, both broadly and specifically to sklearn. I am looking through the sklearn documentation, and I noticed that the sklearn.model_selection.GridSearchCV attributes all end in underscore. For example: cv_results_ best_params_ best_score_ Why is this? What does the underscore do? Please be as broad as possible in your answer (i.e. don't just refer to sklearn's GridSearchCV. I'm assuming this isn't just an sklearn thing, and I have no idea what the appropriate tag is for this so I'm tagging sklearn. Please correct the tags (or me!).
downvote count: 2
linked to: http://stackoverflow.com/q/21075208
has comment: http://stackoverflow.com/comment/85311270
tagged with: scikit-learn
tagged with: python
has comment: http://stackoverflow.com/comment/85300929
linked to: http://stackoverflow.com/q/8714440
accepted answer: http://stackoverflow.com/a/49146456
score: 12
has comment: http://stackoverflow.com/comment/85295115
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85283226
upvote count: 14
has title: What does it mean for an attribute name to end in an underscore?
has comment: http://stackoverflow.com/comment/85299861
answer count: 1
has comment: http://stackoverflow.com/comment/85294003
has comment: http://stackoverflow.com/comment/85297604

http://stackoverflow.com/comment/85290081
type: Comment
type: QuestionComment
score: 0
has text: I have added the below lines of code. url = session.get(request_url) zipfile.ZipFile.extractall(url) I am getting the bellow error. Authentication sucessful !! Traceback (most recent call last): File "C:\Users\x0cw\Downloads\login.py", line 21, in <module> zipfile.ZipFile.extractall(url) File "C:\Program Files\Python\Python36\lib\zipfile.py", line 1493, in extractall members = self.namelist() AttributeError: 'Response' object has no attribute 'namelist'
comment on: http://stackoverflow.com/q/49141787

http://stackoverflow.com/comment/85250724
type: QuestionComment
has text: I think https://github.com/python/cpython is preferred nowadays
type: Comment
comment on: http://stackoverflow.com/q/49122128
score: 1

http://stackoverflow.com/q/49223511
has body: I have a dataframe as follows: version count region listing 2 v2 2 CAN [7, 8] 2 v3 3 CAN [7, 8, 9] I want to extract listing list for each row and get the length. So I did the following: group_v2_list = group[group['version'] == 'v2']['listing'].values and I get output as [list([7, 8])]. Here the type of listing column is numpy.ndarray which I get after using type(group_v2_list). Now I want to get the number of elements in this group_v2_list but I am unable to get it. I tried len(group_v2_list) and group_v2_list.size but both are giving me 1. I want to get the number of elements which should be 2 as 7, 8. How can I get that?
has comment: http://stackoverflow.com/comment/85450616
has comment: http://stackoverflow.com/comment/85450596
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85450722
has answer: http://stackoverflow.com/a/49224614
tagged with: numpy
downvote count: 0
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/85450578
type: UnansweredQuestion
score: 1
answer count: 1
has title: Can't get the size of numpy.ndarray
favorite count: 0
type: Question

http://stackoverflow.com/comment/105543299
comment on: http://stackoverflow.com/a/49160588
type: AnswerComment
has text: It is strange, but with np array this does not work!!! should convert to list first!
score: 1
type: Comment

http://stackoverflow.com/comment/85553794
type: QuestionComment
score: 0
has text: Try using small `s`. Also what's the issue you're facing?
type: Comment
comment on: http://stackoverflow.com/q/49275656

http://stackoverflow.com/a/49263609
has comment: http://stackoverflow.com/comment/85530755
answers question: http://stackoverflow.com/q/49263464
score: 0
has body: I would use a nested list comprehension for your task. old = [["abc","cdf","efgh","x","hijk","y","z"],["xyz","qwerty","uiop","x","asdf","y","z"]] droplist = ["x", "y", "z"] new = [[item for item in sublist if item not in droplist] for sublist in old] print(new) Note the creation of the new list. The outer list comprehnsion considers each of the sublists. The inner list comprehension considers individual strings. The filter occurs when if item not in droplist is executed. The if item not in droplist can be replaced by any criteria you can code. For example: new = [[item for item in sublist if len(item) &gt;= 3] for sublist in old] Or even: def do_I_like_it(s): # Arbitrary code to decide if `s` is worth keeping return True new = [[item for item in sublist if do_I_like_it(item)] for sublist in old] If you want to remove items by their location in the sublists, use slicing: # Remove last 2 elements of each sublist new = [sublist[:-2] for sublist in old] assert new == [['abc', 'cdf', 'efgh', 'x', 'hijk'], ['xyz', 'qwerty', 'uiop', 'x', 'asdf']]
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/49263464
has comment: http://stackoverflow.com/comment/85530734

http://stackoverflow.com/comment/85553795
comment on: http://stackoverflow.com/a/49194871
has text: Also, think what is the difference with definitions of X and b if X works and b does not. Are they defined in the same part of the code? Are they objects of the same kind? Etc.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85260239
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49126593
has text: I cannot see an indentation error in your post, but you post is incomplete. What's coming after the ``fetchall():`` and how is it indented? Are you sure the indention in the else block is in the code the same as you pasted it here? For the rest I think @jpp's link will help you.
type: Comment

http://stackoverflow.com/q/49182288
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49182387
upvote count: 1
favorite count: 0
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49182387
tagged with: pandas
score: 1
tagged with: python
tagged with: merge
possible better answer: http://stackoverflow.com/a/49182348
has body: Say I have the following dataframes; one with data on 1 minute intervals, and the another with daily data intervals. &gt;&gt;&gt; df_1 = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9]}, index=pd.to_datetime(['2017-01-01 00:01:00', '2017-01-01 00:02:00', '2017-01-02 00:01:00'])) &gt;&gt;&gt; df_1 A B C 2017-01-01 00:01:00 1 4 7 2017-01-01 00:02:00 2 5 8 2017-01-02 00:01:00 3 6 9 &gt;&gt;&gt; df_2 = pd.DataFrame({'D':['ON','OFF']}, index=pd.to_datetime(['2017-01-01', '2017-01-02'])) &gt;&gt;&gt; df_2 D 2017-01-01 ON 2017-01-02 OFF And I want to merge them so that the data from df_2 gets pulled into df_1 by the date only, as below. &gt;&gt;&gt; df_merge = pd.merge(df_1, df_2) &gt;&gt;&gt; df_merge A B C D 2017-01-01 00:01:00 1 4 7 ON 2017-01-01 00:02:00 2 5 8 ON 2017-01-02 00:01:00 3 6 9 OFF Is there any way to merge based on date only that will pull the daily data into the minutely data?
type: Question
has title: Combine Dataframes with Minute and Date Indexes
has answer: http://stackoverflow.com/a/49182348

http://stackoverflow.com/a/49268145
has body: You can use split inbuilt function to split the sentences and use the size inbuilt function to count the length of the array as df.withColumn("word_count", F.size(F.split(df['reviewText'], ' '))).show(truncate=False) This way you won't need the expensive udf function As an example, lets say you have following one sentence dataframe +-----------------------------+ |reviewText | +-----------------------------+ |this is text testing spliting| +-----------------------------+ After applying above size and split function you should be getting +-----------------------------+----------+ |reviewText |word_count| +-----------------------------+----------+ |this is text testing spliting|5 | +-----------------------------+----------+ If you have multiple sentences in one row as below +----------------------------------------------------------------------------------+ |reviewText | +----------------------------------------------------------------------------------+ |this is text testing spliting. this is second sentence. And this is the third one.| +----------------------------------------------------------------------------------+ Then you will have to write a udf function as below from pyspark.sql import functions as F def countWordsInEachSentences(array): return [len(x.split()) for x in array] countWordsSentences = F.udf(lambda x: countWordsInEachSentences(x.split('. '))) df.withColumn("word_count", countWordsSentences(df['reviewText'])).show(truncate=False) which should give you +----------------------------------------------------------------------------------+----------+ |reviewText |word_count| +----------------------------------------------------------------------------------+----------+ |this is text testing spliting. this is second sentence. And this is the third one.|[5, 4, 6] | +----------------------------------------------------------------------------------+----------+ I hope the answer is helpful
accepted answer of: http://stackoverflow.com/q/49267331
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49267331
upvote count: 5
score: 5
type: Answer

dll
tags question: http://stackoverflow.com/q/49126195
tags question: http://stackoverflow.com/q/49187150
tag name: dll
type: Tag
tags question: http://stackoverflow.com/q/49153792
tags question: http://stackoverflow.com/q/49158400
tags question: http://stackoverflow.com/q/49266538
tags question: http://stackoverflow.com/q/49132604

http://stackoverflow.com/comment/85403108
comment on: http://stackoverflow.com/q/49198207
score: 0
has text: @Walucas Yes, I did. I have a feeling I might have to start again, remove the migrations and start the process again but I'm just not sure if that would even help.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49127314
tagged with: python
has title: Sklearn Decision Tree Classifier showing float error Python [not a duplicate]
linked to: http://stackoverflow.com/q/16743889
tagged with: sklearn-pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85259466
score: 1
has comment: http://stackoverflow.com/comment/85259601
answer count: 1
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85259824
accepted answer: http://stackoverflow.com/a/49127586
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49127586
has body: I want to make a program for prediction using sklearn DecisionTreeClassifier. Im comparing two lists, ListOnePar that has float values, and timelist that has only strings. I always get the same error. I searched the web and I didnt find anything that can help me. All I saw that comparison can be done between two lists (one with floats and other with strings.) This is not a duplicate of the other question, in the other question the error is totally different, and the whole program is different. This is the error : Pred1=tree.DecisionTreeClassifier() AttributeError: 'float' object has no attribute 'DecisionTreeClassifier' This is the code : from sklearn import tree ListOnePar=[] for child in tree1.get_children(id1): ListTwoPar=[] one=round(float(tree1.item(child,"values")[1]),2) two=round(float(tree1.item(child,"values")[2]),2) tree=round(float(tree1.item(child,"values")[3]),2) four=round(float(tree1.item(child,"values")[5]),1) five=round(float(tree1.item(child,"values")[6]),1) ListTwoPar.append(one) ListTwoPar.append(two) ListTwoPar.append(tree) ListTwoPar.append(four) ListTwoPar.append(five) ListOnePar.append(ListTwoPar) timelist=[] for child in tree1.get_children(id1): time=tree1.item(child,"values")[7] timelist.append(time) Pred1=tree.DecisionTreeClassifier() Pred1=Pred1.fit(ListOnePar,time) size=float(PredSizeEntry.get()) time=float(PredTimeEntry.get()) cost=float(PredCostEntry.get()) level=float(PredLevelEntry.get()) subcontractors=float(PredSubcontractorsEntry.get()) ListForPrediction1=[] ListForPrediction2=[] ListForPrediction2.insert(0,size) ListForPrediction2.insert(1,time) ListForPrediction2.insert(2,cost) ListForPrediction2.insert(3,level) ListForPrediction2.insert(4,subcontractors) ListForPrediction1.append(ListForPrediction2) prediction1=Pred1.predict(ListForPrediction1) print(prediction1[0])
has comment: http://stackoverflow.com/comment/85259646

http://stackoverflow.com/comment/85307696
has text: @JonasAdler added data example.
type: QuestionComment
comment on: http://stackoverflow.com/q/49151096
type: Comment
score: 0

http://stackoverflow.com/a/49159552
downvote count: 1
upvote count: 17
type: Answer
answers question: http://stackoverflow.com/q/49159245
has body: Warnings aren't errors - they won't hinder your program from running. In case of deprecated warnings: you use a feature that will be removed in future versions so the devs lable it deprecated. It may work now, but next version it may no longer as this feature was removed - then you will get an error. You can fix it like this: wb.sheetnames # all names sheet = wb["UseThisSheet"] # select a certain sheet by name for sheet2 in wb: # or go over all sheets print(sheet2.title) sh = wb.active # normally sheet at index 0 if you create an empy one Source: https://openpyxl.readthedocs.io/en/stable/tutorial.html Here is a short example on how to create a workbook (my answer to some other xlsx question): https://stackoverflow.com/a/48782382/7505395
score: 16

http://stackoverflow.com/comment/85252054
type: QuestionComment
has text: You have quite a few conditions, and you have an object array as well. Why not use a pandas dataframe?
comment on: http://stackoverflow.com/q/49123406
score: 1
type: Comment

http://stackoverflow.com/a/49202913
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49202426
downvote count: 0
answers question: http://stackoverflow.com/q/49202426
has body: You can apply groupby to sum value by key first for each element then using pandas to convert to dataframe. Note that you have to sort by key first before summing. import pandas as pd from itertools import groupby data = [ [(0, 61), (1, 30), (5, 198), (4, 61), (0, 30), (5, 200)], [(1, 72), (2, 19), (3, 31), (4, 192), (6, 72), (5, 75)], [(0, 71), (1, 40), (5, 98), (4, 21), (0, 10), (5, 21200)], [(1, 702), (2, 190), (3, 310), (4, 1092), (6, 702), (5, 705)], ] # copying example from @PatrickArtnerz solution def group_sum(data): """given list, return dictionary of summation based on initial key""" data_dict = {k: sum(v_[1] for v_ in v) for k, v in groupby(sorted(data, key=lambda x: x[0]), lambda x: x[0])} return data_dict df = pd.DataFrame(list(map(group_sum, data))).fillna(0)
type: Answer
score: 2

http://stackoverflow.com/comment/85324017
type: Comment
has text: @Dunes Transitivity is already broken (`OrderedDict([(1,2), (3,4)]) == {1:2, 3:4} == OrderedDict([(3,4), (1,2)])`), so who cares?
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/49159268

xpath
tags question: http://stackoverflow.com/q/49171370
tags question: http://stackoverflow.com/q/49146623
tags question: http://stackoverflow.com/q/49239935
tags question: http://stackoverflow.com/q/49221014
tags question: http://stackoverflow.com/q/49267695
tags question: http://stackoverflow.com/q/49126355
tag name: xpath
tags question: http://stackoverflow.com/q/49275438
tags question: http://stackoverflow.com/q/49128161
type: Tag
tags question: http://stackoverflow.com/q/49145635
tags question: http://stackoverflow.com/q/49247602
tags question: http://stackoverflow.com/q/49178621
tags question: http://stackoverflow.com/q/49143689
tags question: http://stackoverflow.com/q/49266162
tags question: http://stackoverflow.com/q/49270953
tags question: http://stackoverflow.com/q/49141584

http://stackoverflow.com/a/49194902
downvote count: 1
upvote count: 4
has body: You can get the posterior samples of Log-Likelihood by doing: logp = fit.extract()['lp__']
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/112817288
answers question: http://stackoverflow.com/q/49147905
accepted answer of: http://stackoverflow.com/q/49147905
score: 3
has comment: http://stackoverflow.com/comment/103888495
type: Answer

http://stackoverflow.com/q/49242820
has comment: http://stackoverflow.com/comment/85494198
tagged with: python
has comment: http://stackoverflow.com/comment/85490876
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85489732
tagged with: mod-wsgi
score: 1
has comment: http://stackoverflow.com/comment/85490804
has comment: http://stackoverflow.com/comment/85494456
tagged with: apache
linked to: http://stackoverflow.com/q/38132755
answer count: 1
downvote count: 0
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85490613
accepted answer: http://stackoverflow.com/a/49247800
has body: I am encountering a "No module named 'encodings'" error. It appears to me that Python virtual env was not correctly loaded. However I also included wsgi file just in case. 0> Error I got: [Mon Mar 12 16:49:44.919934 2018] [:info] [pid 6546] mod_wsgi (pid=6546): Starting process 'abcd_server' with uid=501, gid=501 and threads=5. [Mon Mar 12 16:49:44.920494 2018] [:info] [pid 6546] mod_wsgi (pid=6546): Python home /var/www/m.abcd.com/venv. [Mon Mar 12 16:49:44.920556 2018] [:info] [pid 6546] mod_wsgi (pid=6546): Initializing Python. Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' 1> Installation: Amazon EC2 linux instance (CentOS); installed Python 3.6: sudo yum install python36 installed wsgi: sudo yum install mod24_wsgi-python36.x86_64 2> Verify: httpd: Apache/2.4.27 (Amazon) python3: Python 3.6.2 httpd uses modules/wsgi.so ldd wsgi.so: linux-vdso.so.1 => (0x00007ffe71de8000) libpython3.6m.so.1.0 => /usr/lib64/libpython3.6m.so.1.0 (0x00007f49a0ecf000) libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f49a0cb3000) libdl.so.2 => /lib64/libdl.so.2 (0x00007f49a0aaf000) libutil.so.1 => /lib64/libutil.so.1 (0x00007f49a08ac000) libm.so.6 => /lib64/libm.so.6 (0x00007f49a05aa000) libc.so.6 => /lib64/libc.so.6 (0x00007f49a01e6000) /lib64/ld-linux-x86-64.so.2 (0x00007f49a1616000) 3> Web site setup: Create a new user "python_user:python_user" (uid=501); Create a directory /var/www/m.abcd.com and owned by python_user:python_user. Also subdirectories are also owned by python_user:python_user Under /var/www/m.abcd.com, create python-src, venv, html, logs, applogs etc. python-src contains setup.py and application source files venv is setup by running python3 -m venv venv (Edit: not python2) (setup virtual env) inside python-src, pip install -e . to add app dependencies to virtual env. 4> httpd config: ...... WSGIDaemonProcess abcd_server user=python_user group=python_user threads=5 python-home="/var/www/m.abcd.co…
has answer: http://stackoverflow.com/a/49247800
has title: Receiving "No module named encodings error" in Apache in WSGI mode
has comment: http://stackoverflow.com/comment/85493236

http://stackoverflow.com/comment/85489253
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49224871
has text: Doesn't work like that. Edit your question so that it is focused on the issue and all necessary information is contained. In order to understand the issue, it shouldn't be necessary to read the comments.
type: Comment

http://stackoverflow.com/q/49213695
answer count: 1
has comment: http://stackoverflow.com/comment/85432337
has comment: http://stackoverflow.com/comment/85431977
downvote count: 1
has comment: http://stackoverflow.com/comment/85432662
favorite count: 0
type: Question
has title: Is open() writing to my file?
has answer: http://stackoverflow.com/a/49214239
has comment: http://stackoverflow.com/comment/85432012
tagged with: pickle
tagged with: python
score: -1
has body: I really don't have much to say here except my terminal output matthew@archey [03:13:31 PM] [~/code] -&gt; % python3 Python 3.6.4 (default, Jan 5 2018, 02:35:40) [GCC 7.2.1 20171224] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import pickle &gt;&gt;&gt; f=open("pokemon.pkl", "wb") &gt;&gt;&gt; pickle.dump({}, f) &gt;&gt;&gt; f.close() &gt;&gt;&gt; exit() matthew@archey [03:15:23 PM] [~/code] -&gt; % cat pokemon.pkl �}q.% matthew@archey [03:15:27 PM] [~/code] -&gt; % python3 pokedex.py Traceback (most recent call last): File "pokedex.py", line 8, in &lt;module&gt; pokemon = pickle.load(f_read, "rb") EOFError: Ran out of input matthew@archey [03:15:37 PM] [~/code] -&gt; % vim pokedex.py matthew@archey [03:15:52 PM] [~/code] -&gt; % cat pokemon.pkl matthew@archey [03:16:02 PM] [~/code] -&gt; % All of the code: Just a note - this adds pokemon to the pokemon.pkl file import pickle # pokedex pokemon appender f_read = open("pokemon.pkl", "rb") f_write = open("pokemon.pkl", "wb") pokemon = pickle.load(f_read) f_read.close() try: while True: p_name = input("Name: ") p_type = input("Type: ") p_height = input("Height: ") p_weight = input("Weight: ") pokemon[p_name] = [p_type, p_height, p_weight] except KeyboardInterrupt: pickle.dump(pokemon, f_write) print("Exiting...") So this is what I did: Created the pickle file Viewed my pickle file Ran my code. It errored out and said the file 'ran out of input' Viewed the pickle file again. There was nothing there! Please help!
has comment: http://stackoverflow.com/comment/85431825
upvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/85284974
has text: It does look like your guessing worked well in this case.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49133301

http://stackoverflow.com/a/49136997
accepted answer of: http://stackoverflow.com/q/49136890
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85279184
answers question: http://stackoverflow.com/q/49136890
has comment: http://stackoverflow.com/comment/85278991
type: Answer
has body: You can use pd.merge: df1.merge(df2, on=['B','C'],suffixes=('','_y')).drop('A_y',axis=1) A B C 0 15:00:00 2002-01-13 9 1 15:30:00 2002-01-13 9 2 16:00:00 2002-01-13 9 3 15:00:00 2002-01-15 38 4 15:30:00 2002-01-15 38 5 16:00:00 2002-01-15 38 Another option is use boolean index: df1[df1.B.isin(df2.B) &amp; df1.C.isin(df2.C)] A B C 1 15:00:00 2002-01-13 9 3 15:30:00 2002-01-13 9 5 16:00:00 2002-01-13 9 10 15:00:00 2002-01-15 38 12 15:30:00 2002-01-15 38 14 16:00:00 2002-01-15 38
score: 2
upvote count: 2

http://stackoverflow.com/comment/85550624
score: 0
type: AnswerComment
has text: The problem is that I don't have much control of the local scripts, it could be written by someone else. What I want to do is simply terminate the python scripts without waiting remotely via paramiko.
type: Comment
comment on: http://stackoverflow.com/a/49273330

http://stackoverflow.com/a/49255673
type: Answer
accepted answer of: http://stackoverflow.com/q/49255529
score: 1
type: AcceptedAnswer
has body: boto3 has an awesome feature called Service Resource. The Instance type sub-resource has the attribute block_device_mappings. Make use of it: ec2 = boto3.resource('ec2') instance = ec2.Instance(instance_id) for device in instance.block_device_mappings: volume = device.get('Ebs') print(volume.get('VolumeId'))
answers question: http://stackoverflow.com/q/49255529
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85515899

http://stackoverflow.com/q/49204378
upvote count: 1
has comment: http://stackoverflow.com/comment/85415415
favorite count: 0
type: Question
has title: Python/BeautifulSoup: Scrape Select Class
tagged with: beautifulsoup
has body: I am trying to scrape the option values with the following HTML; SIZE XS S M L XL I have tried following code with no success: soup=BeautifulSoup(response.text, "html.parser") product = soup.find('select',{'class':'PI__select PI__input js-select js-select-SIZE js-select-SIZE-static'}) print (product) The output I get is: None
has answer: http://stackoverflow.com/a/49204400
linked to: http://stackoverflow.com/q/30147223
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49204447
tagged with: python
has comment: http://stackoverflow.com/comment/85414107
answer count: 2
score: 1
downvote count: 0

http://stackoverflow.com/comment/85485304
score: 1
comment on: http://stackoverflow.com/q/49240801
type: QuestionComment
type: Comment
has text: Also, your line breaks are messed up.

http://stackoverflow.com/a/49208957
answers question: http://stackoverflow.com/q/49181526
score: 0
type: Answer
has body: the yum command in old version of red hat(6 and older) work with python 2.6 are you test yum command with unlink /usr/bin/python and add new link from /bin/python to /usr/bin/python2.6 ? if the result is like same error try to recompile python6 OR update your yum pkgs on server

http://stackoverflow.com/comment/85554055
type: AnswerComment
has text: @Glostas the question mentiones a 'on a known key_length'; without `itertools.product` this is indeed difficult to do. i think that is what the question is about.
comment on: http://stackoverflow.com/a/49275663
type: Comment
score: 0

http://stackoverflow.com/q/49157772
answer count: 2
has answer: http://stackoverflow.com/a/49157837
accepted answer: http://stackoverflow.com/a/49157837
downvote count: 1
has title: create an array of the smallest magnitude values from two equal sized numpy arrays
favorite count: 0
type: Question
tagged with: numpy
tagged with: python-3.x
tagged with: arrays
has body: I have two numpy arrays: import numpy as np a=np.array([1,-2,3]) b=np.array([-2,-1,4]) I know how to create an array of the minimum of each pair of entries: np.minimum(a,b) array([-2, -2, 3]) And how to get an array of the absolute value of the smallest magnitude vales np.minimum(abs(a),abs(b)) array([1, 1, 3]) But what I would like is an array of the smallest magnitude values but retaining the sign of the values, in other words to get array([1,-1,3]) as my output... I can't think of a python-esque way of doing this in one line, only resorting to long-winded loops and if-thens...
has answer: http://stackoverflow.com/a/49170371
possible better answer: http://stackoverflow.com/a/49170371
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 3

http://stackoverflow.com/a/49196395
score: 0
answers question: http://stackoverflow.com/q/49195394
has body: I know why.... I put 'wb' for i in range(261): with open('result_20140213/task_%i.pkl' %i , 'rb') as handle: pickle.load(handle) So it will firstly create empty files..... Thanks everyone.
type: Answer

http://stackoverflow.com/comment/98223491
has text: This has nothing to do with what he asked
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49280195

http://stackoverflow.com/q/49184344
tagged with: python-3.x
answer count: 2
upvote count: 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
has title: Python code runs without problems in Py2.7 but doesn't in 3.6.4
has answer: http://stackoverflow.com/a/49184798
tagged with: python-2.7
score: 1
has answer: http://stackoverflow.com/a/49184621
has body: I am trying to run the following code: Headers=requests.get('https://coinmarketcap.com').headers CookieDough=Headers['Set-Cookie'] Headers="""\"{ ":authority":"coinmarketcap.com", ":method":"POST", ":path":"/login", ":scheme":"https", "accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "accept-encoding":"gzip, deflate, br", "accept-language":"en-US,en;q=0.9", "cache-control":"max-age=0", "content-length":"743", "content-type":"application/x-www-form-urlencoded", "cookie":\""""+CookieDough+"""\", "origin":"https://coinmarketcap.com", "referer":"https://coinmarketcap.com", "upgrade-insecure-requests":"1", "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36" }\"""" print(json.loads(Headers, strict=False)) On a past thread somebody has run this code on python 2.7 and it runs successfully, however when I run it on my end, python 3.6.4, it doesn't run. It gives me the following error: json.decoder.JSONDecodeError: Extra data: line 2 column 2 (char 4) I am running Python 3.6.4 on the Sublime Text 3 Builder. Thank you
tagged with: sublimetext3
favorite count: 0
type: Question

http://stackoverflow.com/a/76655700
type: Answer
has comment: http://stackoverflow.com/comment/135171893
score: 0
answers question: http://stackoverflow.com/q/49207179
has body: def result(request) emails = [] module_dir = os.path.dirname(__file__) file_path = os.path.join(module_dir, 'disposable.txt') disposable_mails = open(file_path, 'r+') for disposable_mail in disposable_mails: emails.append(disposable_mail.rstrip())

http://stackoverflow.com/comment/85514733
type: QuestionComment
comment on: http://stackoverflow.com/q/49254161
score: 0
has text: as in a model function? (`def is_youtube(self)`...) yeah that would definitely be better I think.
type: Comment

http://stackoverflow.com/comment/85409410
comment on: http://stackoverflow.com/a/49201967
type: Comment
score: 0
type: AnswerComment
has text: Thanks @abarnet ! I appreciate it man! I am trying to grasp both python and discrete structures at the same time and its hard for me to see the connection sometimes!

http://stackoverflow.com/comment/85496914
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49246587
has text: The `else` part needs to be removed, and the `return True` is to go outside the loop.
score: 3

http://stackoverflow.com/q/49178611
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85363813
tagged with: python
has comment: http://stackoverflow.com/comment/85372435
tagged with: git
score: 0
answer count: 0
upvote count: 1
downvote count: 1
has body: I want to execute a Python script that closes all the tickets of JIRA once my branch is merged with master. Can any one please help me how to solve the problem? from __future__ import with_statement from jira import JIRA, JIRAError from requests.exceptions import ConnectionError import cProfile import logging import sys import os import shutil import logging.handlers jiraEnabled = True dashes = "---------------------------------------------------------------------" import contextlib import subprocess import re import collections import getpass import traceback import pprint import pdb import stat import cookielib import subprocess import urllib2 import ConfigParser import string def main(): global username, password, loglevel, jiraCheckEnabled, url, allowed_states, check_assignee, check_state, disabled_on_branches configure_logging(loglevel) config_file = get_config_file("config.ini") error_code = handle_pre_receive() if error_code != 0: logging.error(“Hook failed please try later\n”) return error_code # Performs the git "pre-receive" hook def handle_pre_receive(): line = sys.stdin.read() try: (old_commit_id, new_commit_id, ref) = line.strip().split() except ValueError: logging.error("\n%s", dashes) return -1 if new_commit_id == "0000000000000000000000000000000000000000": logging.debug("Branch was deleted, going to skip commit") return 0 if disabled_on_branch(git_get_branchname_from_ref(ref)): return 0 commit_id_array = git_get_array_of_commit_ids(old_commit_id, new_commit_id) if commit_id_array == None or len(commit_id_array)==0: if old_commit_id == "0000000000000000000000000000000000000000": logging.debug("Branch was created, going to skip commit processing") return 0 logging.error("No new commits found!") return -1 if jiraEnabled: try: jira = JIRA(url,basic_auth=(username,password)) except ConnectionError, e: logging.error("Failed to connect to JIRA") return 0 except JIRAError, e: logging.error("JIRA has rejected connection” ) return 0; else: jira = None def get_…
has title: Change JIRA status on code merge python code
favorite count: 0
tagged with: jira
type: Question

http://stackoverflow.com/comment/85253032
score: 1
type: Comment
has text: @PrashantPuri Your coding style like someone from Javascript world trying to write a python code with camelCase as variable name, and '//' as comment...
comment on: http://stackoverflow.com/a/49123830
type: AnswerComment

http://stackoverflow.com/comment/85435545
score: 0
comment on: http://stackoverflow.com/a/49210532
type: Comment
type: AnswerComment
has text: john.. modifying your code... i have traceback "KeyError: 1" from tkinter import * def dofunc(): bag_o_widgets[1].config(text='ok') root=Tk() bag_o_widgets = {} for i in range(1,4): v = StringVar() bag_o_widgets[str(i)] = Label(root, width=10,text=str(i), textvariable=v) bag_o_widgets[str(i)].pack() print(bag_o_widgets) root.after(100,dofunc) root.mainloop

http://stackoverflow.com/a/49142862
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49130327
answers question: http://stackoverflow.com/q/49130327
has body: The FFT algorithm computes the DFT, which has the origin (both spatial and in frequency domain) on the first sample. You need to shift your signal (after applying the Hanning window) so that t=0 is the leftmost sample, and after computing the FFT you have to do the inverse shift. MATLAB has ifftshift and fftshift, which implement those two shifts. NumPy must have similar functions. Another issue with your code is that you compute the DFT, and plot it at the locations given by the w that you computed, but is unrelated to the actual frequencies at which the DFT is computed. Here is your code, translated to MATLAB, and fixed to properly compute F2 and w *. I hope this is useful. One thing to note is that your F does not match F2, I am confident that this is not due to an error in F2, but an error in your computation of F. The shapes are similar, but F is scaled differently and mirrored. N = 1e3; t = linspace(-100,100,N); % time Fs = 1/(t(2)-t(1)); w = Fs * (-floor(N/2):floor((N-1)/2)) / N; % NOTE proper frequencies b = 0.1; a = 1; H = @(x)1*(x&gt;0); % Heaviside function % function in time f = -1j*H(t).*exp(-(1j*a+b)*t); % function in frequency (analytical work) F = (w-a-1j*b)./((w-a).^2+b.^2); % hanning window hann = 0.5*(1-cos(2*pi*linspace(0,1,N))); % function in frequency (numerical work) F2 = fftshift(fft(ifftshift(hann.*f))); % NOTE shifting of origin figure subplot(2,1,1), hold on plot(w,real(F),'b-') plot(w,real(F2),'r-') xlabel('\omega') ylabel('Re(F(\omega))') legend({'analytical','fft'},'Location','best') subplot(2,1,2), hold on plot(w,imag(F),'b-') plot(w,imag(F2),'r-') xlabel('\omega') ylabel('Im(F(\omega))') legend({'analytical','fft'},'Location','best') Footnote: * I also changed the colors, MATLAB's green is too light.
type: Answer
has comment: http://stackoverflow.com/comment/85333449
upvote count: 2
has comment: http://stackoverflow.com/comment/85299437
score: 2
downvote count: 0

http://stackoverflow.com/q/49272209
favorite count: 0
tagged with: apache-spark-sql
has comment: http://stackoverflow.com/comment/85556043
type: Question
upvote count: 2
tagged with: bigdata
tagged with: pyspark
accepted answer: http://stackoverflow.com/a/49277642
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/49277642
has body: I have below DataFrame's and achieved the desired output in python. But I wanted to convert the same into pyspark. d = {'user': ['A', 'A', 'B','B','C', 'D', 'C', 'E', 'D', 'E', 'F', 'F'], 'songs' : [11,22,99,11,11,44,66,66,33,55,11,77]} data = pd.DataFrame(data = d) e = {'user': ['A', 'B','C', 'D', 'E', 'F','A'], 'cluster': [1,2,3,1,2,3,2]} clus = pd.DataFrame(data= e) Desired output: I wanted to achieve all the songs which were not listened by the user of a particular cluster. A belongs to cluster 1, and cluster 1 has songs [11,22,33,44] so A hasnt listened to [33,44] so I achieved that using the below python code. user A [33, 44] B [55, 66] C [77] D [11, 22] E [11, 99] F [66] PYTHON CODE: df = pd.merge(data, clus, on='user', how='left').drop_duplicates(['user','movie']) df1 = (df.groupby(['cluster']).apply(lambda x: x.pivot('user','movie','cluster').isnull()) .fillna(False) .reset_index(level=0, drop=True) .sort_index()) s = np.where(df1, ['{}'.format(x) for x in df1.columns], '') #remove empty values s1 = pd.Series([''.join(x).strip(', ') for x in s], index=df1.index) print (s1) Hot to achieve the same in pyspark distributed coding ?
has title: python to pyspark, converting the pivot in pyspark
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85608692

http://stackoverflow.com/comment/85382959
score: 0
comment on: http://stackoverflow.com/q/49188607
type: Comment
type: QuestionComment
has text: @kiffu, you're welcome. you can accept any answer which is working at your end.

http://stackoverflow.com/a/49267230
score: 3
type: Answer
answers question: http://stackoverflow.com/q/49266458
has body: The smallest change is to use submit once for each element, instead of once for the whole list: futures = [] for file in FileList: future = pool.submit(subprocess.call, file, shell=1) future.blah blah futures.append(future) The futures list is only necessary if you want to do something with the futures—wait for them to finish, check their return values, etc. Meanwhile, you're explicitly creating the pool with max_workers=1. Not surprisingly, this means you'll only get 1 worker child process, so it'll end up waiting for one subprocess to finish before grabbing the next one. If you want to actually run them concurrently, remove that max_workers and let it default to one per core (or pass max_workers=8 or some other number that's not 1, if you have a good reason to override the default). While we're at it, there are a lot of ways to simplify what you're doing: Do you really need multiprocessing here? If you need to communicate with each subprocess, that can be painful to do in a single thread—but threads, or maybe asyncio, will work just as well as processes here. More to the point, it doesn't look like you actually do need anything but launch the process and wait for it to finish, and that can be done in simple, synchronous code. Why are you building a string and using shell=1 instead of just passing a list and not using the shell? Using the shell unnecessarily creates overhead, safety problems, and debugging annoyances. You really don't need the jid on each future—it's just the list of all of your invocation strings, which can't be useful. What might be more useful is some kind of identifier, or the subprocess return code, or… probably lots of other things, but they're all things that could be done by reading the return value of subprocess.call or a simple wrapper. You really don't need the callback either. If you just gather all the futures in a list and as_completed it, you can print the results as they show up more simply. If you do both of the above, you've got n…
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49266458
has comment: http://stackoverflow.com/comment/138822282

duplicates
tags question: http://stackoverflow.com/q/49182242
tags question: http://stackoverflow.com/q/49218181
tags question: http://stackoverflow.com/q/49186684
tags question: http://stackoverflow.com/q/49266143
tags question: http://stackoverflow.com/q/49263997
tags question: http://stackoverflow.com/q/49202126
tags question: http://stackoverflow.com/q/49195912
tags question: http://stackoverflow.com/q/49254850
type: Tag
tags question: http://stackoverflow.com/q/49194081
tags question: http://stackoverflow.com/q/49243151
tag name: duplicates

http://stackoverflow.com/comment/85493372
type: QuestionComment
has text: Thanks, I am wondering if this is an issue specific to my installation. I am running on MacOSX 10.13.3, Anaconda distribution, Python 3.6.4
comment on: http://stackoverflow.com/q/49242870
score: 0
type: Comment

http://stackoverflow.com/comment/112445784
comment on: http://stackoverflow.com/a/50215635
type: Comment
score: 0
type: AnswerComment
has text: I'd suggest that this use case is dangerous. Build a new `kwargs` for any subsequent class intialization with the expected parameters. You should not modify the parent `kwargs` for onward use. That has a code smell.

http://stackoverflow.com/comment/85289995
type: Comment
score: 0
type: QuestionComment
has text: Your best bet is to search `uninstall miniconda` in Google. The original Python installer you had from a few months ago *may* have an uninstall option if you run it again. Otherwise, you'll have to search how to uninstall it as well.
comment on: http://stackoverflow.com/q/49141525

http://stackoverflow.com/a/49244325
type: Answer
score: 2
downvote count: 0
has body: Lets break down the filtration into a few steps. First, create the conditions to be filtered conditions = "(x['discharge'].isin(x['admit'])) &amp; (x['Num1'] &gt;= 5) &amp; (x['Num1'] &lt;= 12)" I Chose to store the conditions as string because it looks cleaner for formatting the next step. However, the filter command will be used to check, by key in the dataframe, if there are any discharge times equal to admit times. And will also check if Num1 at the dischargetime is between 5 and 12. Now we run the groupby operation and evaluate conditions filter = df.groupby('Key').apply(lambda x: pd.eval(conditions)) filter.index = filter.index.droplevel(0) filter will output this 0 True 1 False 2 False 3 False 4 False 5 False 6 False 7 True dtype: bool filter provides some Boolean flags were the conditions hold true. The last step is to add the flags for admit times equlivant to dischagre times which can be done by merging the initial dataframe with the filtered locations which is used to extract the indices of admit flags. dex = df.merge(df[filter.values],left_on=['Key','admit'],right_on=['Key','discharge'],how='left').dropna().index Finally set the flags where either condition is True df['flag'] = (filter | df.index.isin(dex)).astype(int) Full code: conditions = "(x['discharge'].isin(x['admit'])) &amp; (x['Num1'] &gt;= 5) &amp; (x['Num1'] &lt;= 12)" filter = df.groupby('Key').apply(lambda x: pd.eval(conditions)) filter.index = filter.index.droplevel(0) dex = df.merge(df[filter.values],left_on=['Key','admit'],right_on=['Key','discharge'],how='left').dropna().index df['flag'] = (filter | df.index.isin(dex)).astype(int) Output: Key Num1 Num2 admit discharge flag 0 10003 12 121 2012-05-06 2012-05-08 1 1 10003 13 122 2012-05-08 2012-05-10 1 2 10003 13 122 2012-10-10 2012-10-12 0 3 10003 13 124 2012-10-10 2012-10-16 0 4 10003 12 125 2012-10-10 2012-10-23 0 5 10003 13 126 2012-11-10 2012-11-11 0 6 10034 15 127 2012-05-20 2012-05-20 1 7 10034 12 128 2012-05-20 2012-05-20 1
answers question: http://stackoverflow.com/q/49164935
upvote count: 2

http://stackoverflow.com/a/49231214
answers question: http://stackoverflow.com/q/49231190
score: 3
upvote count: 3
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85466121
type: Answer
accepted answer of: http://stackoverflow.com/q/49231190
has body: Use setting with enlargement: df.loc[('bar', ''), ['col_1', 'col_2', 'col_3']] = np.nan Or use tuple in name: s = pd.Series( [np.nan, np.nan, np.nan], index=['col_1', 'col_2', 'col_3'], name=('bar', np.nan) ) print (df.append(s)) col_1 col_2 col_3 idx_1 idx_2 foo r_1 1.0 2.0 3.0 r_2 4.0 5.0 6.0 r_3 7.0 8.0 9.0 bar NaN NaN NaN NaN s = pd.Series( [np.nan, np.nan, np.nan], index=['col_1', 'col_2', 'col_3'], name=('bar', '') ) print (df.append(s)) col_1 col_2 col_3 idx_1 idx_2 foo r_1 1.0 2.0 3.0 r_2 4.0 5.0 6.0 r_3 7.0 8.0 9.0 bar NaN NaN NaN
has comment: http://stackoverflow.com/comment/123118211

http://stackoverflow.com/a/49262386
type: Answer
answers question: http://stackoverflow.com/q/49262089
has comment: http://stackoverflow.com/comment/85528648
has body: if not a big dataframe you can do something simple like: portion = [] for ix, row in df.iterrows(): if df.loc[ix - 1, 'Labelid']==0 and row['Labelid']==0: portion.append(row) else: # do stuff on the portion portion = []
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85528450
score: 1

http://stackoverflow.com/q/49244460
has title: how to get difference of consecutive rows by shifting between columns
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85492999
has body: I have a dataframe like the one below A B 0 a b 1 c d 2 e f 3 g h How do I find the difference like below using python A B diff 0 a b Nan 1 c d (b-c) 2 e f (d-e) 3 g h (f-g)
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 5
has answer: http://stackoverflow.com/a/49244656
tagged with: python
score: -5

http://stackoverflow.com/q/49158268
tagged with: pandas
downvote count: 0
has body: I want to backfill each column based on time (1 day ,2 day) with different label. here is the code: from datetime import datetime, timedelta import pandas as pd import numpy as np import random np.random.seed(11) date_today = datetime.now() ndays = 15 df = pd.DataFrame({'date': [date_today + timedelta(days=x) for x in range(ndays)], 'test': pd.Series(np.random.randn(ndays)), 'test2':pd.Series(np.random.randn(ndays))}) df = df.set_index('date') df = df.mask(np.random.random(df.shape) &lt; .7) print(df) # this will be the dataset that I generate for this question # my orginal data set have labels that is why I convert it to str df['test']=df['test'].astype(str) df['test2']=df['test2'].astype(str) df.replace('nan', np.nan, inplace = True) for I in df.dropna().index.values: end=I start=end-np.timedelta64(24,'h') start2=end-np.timedelta64(48,'h') df[(df.index &gt;= start) &amp; (df.index &lt;= end)]=df[(df.index &gt;= start) &amp; (df.index &lt;= end)].bfill() my initial dataset will look like this: test test2 date 2018-03-07 11:28:23.028856 NaN NaN 2018-03-08 11:28:23.028856 NaN NaN 2018-03-09 11:28:23.028856 -0.484565 1.574634 2018-03-10 11:28:23.028856 -2.653319 NaN 2018-03-11 11:28:23.028856 NaN NaN 2018-03-12 11:28:23.028856 NaN NaN 2018-03-13 11:28:23.028856 -0.536629 NaN 2018-03-14 11:28:23.028856 NaN 0.725752 2018-03-15 11:28:23.028856 NaN 1.549072 2018-03-16 11:28:23.028856 -1.065603 0.630080 2018-03-17 11:28:23.028856 NaN NaN 2018-03-18 11:28:23.028856 -0.475733 0.732271 2018-03-19 11:28:23.028856 NaN -0.642575 2018-03-20 11:28:23.028856 NaN -0.178093 2018-03-21 11:28:23.028856 NaN -0.573955 What I want to get is like this: I tried different things but I couldn't find a way to this with bfill, bfill don't get any parameters for value and fillna only get method or value. test test2 date 2018-03-07 11:28:23.028856 -0.484565_2D 1.574634_2D 2018-03-08 11:28:23.028856 -0.484565_D 1.574634_D 2018-03-09 11:28:23.028856 -0.484565 1.574634 2018-03-10 11:28:23.028856 -2.…
has answer: http://stackoverflow.com/a/49162072
answer count: 1
has comment: http://stackoverflow.com/comment/85325358
favorite count: 0
has comment: http://stackoverflow.com/comment/85327887
type: Question
has title: back fill missing data with a label for a window of a time
type: UnansweredQuestion
tagged with: missing-data
has comment: http://stackoverflow.com/comment/85327593
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85325000
score: 2
upvote count: 2
tagged with: categorical-data

http://stackoverflow.com/comment/85328937
score: 1
comment on: http://stackoverflow.com/a/49161057
has text: Turns out I had to just fix a line elsewhere in my code! With that and your help, the function returns the various indices now :) thank you!
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85547544
has text: Unfortunately, this answer doesn't have any "blank" columns as are required by the OP.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49272409

http://stackoverflow.com/a/49156900
has comment: http://stackoverflow.com/comment/85326011
has comment: http://stackoverflow.com/comment/85324918
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85324267
upvote count: 1
answers question: http://stackoverflow.com/q/49156225
has comment: http://stackoverflow.com/comment/85326328
has comment: http://stackoverflow.com/comment/85323781
score: 1
accepted answer of: http://stackoverflow.com/q/49156225
type: Answer
has body: The simplest way to do this would be to write your own item pipeline, and do the cleanup per item in process_item(), instead of doing it all at once using pandas. class YourPipeline(object): def process_item(self, item, spider): if 'gerald' not in item['performance']: raise DropItem # do your cleanup return item Sidenote: lstrip and rstrip don't do what you think, they just happen to produce the correct result in this case. EDIT: The error you get is caused by the same item being yielded multiple times from parse_ticketinv. This causes the already-modified item (item['performance'] being replaced by a datetime object) to pass through the pipeline again, causing a TypeError. The simplest way to solve the problem is creating a new item each loop, or yielding item copies: def parse_ticketinv(self, response): # for whatever: # do stuff yield item.copy()

http://stackoverflow.com/q/49122420
type: Question
tagged with: python-3.x
tagged with: python-xarray
has comment: http://stackoverflow.com/comment/86362752
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/102385345
tagged with: python
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/49675691
downvote count: 0
tagged with: pandas
answer count: 1
linked to: http://stackoverflow.com/q/7883646
has body: I want to structure my data (similarly to pandas) to allow easy data exploration. I tried using xarray.DataArray for this task (the recommended way to represent n-dimensional data in pandas http://pandas.pydata.org/pandas-docs/stable/dsintro.html#panel4d-and-panelnd-deprecated) but it appears inefficient given that my data is sparse. Is there a better way to structure my data under xarray.DataArray or under another Python data structure to allow easy data exploration? Description of data My data consists of prescriptions given to patients. Each entry consists of: Date (datetime64) Patient Id (int) Drug name (string) Drug type (string) Drug class (string) Scheduled dosage (real value) Dosage as needed (real value) There might be several prescriptions on a date for different patients. A patient might also be prescribed several drugs (e.g., 2-3 drugs) at the same time with 'mandatory' dosage and 'optional/as needed' dosage. My dataset currently consists of 397 different patients, 1520 different dates and 161 different drugs. I only have 21790 non-null entries out of the 397*1520*161*2 entries (i.e., 0.01%). Initial code My data is currently organized as the following xarray.DataArray: drugs = xarray.DataArray(dosages, coords={'patient': patients, 'time': dates, 'drug': drug_names, 'timing': timings, 'drug_type': ('drug', drug_types), 'drug_class': ('drug', drug_classes)}, dims=['patient', 'time', 'drug', 'timing']) where dosages.shape = (len(patients), len(dates), len(drug_names), 2). The timing axis corresponds to 'scheduled' vs. 'as needed' dosage. All the missing/zero entries are set to numpy.nan.
has title: Best data structure for sparse data with multiple dimensions
favorite count: 0

http://stackoverflow.com/comment/85492472
type: Comment
type: AnswerComment
has text: Not much to understand, it was my mistake :) I corrected the answer, but I suppose you figured it out in the mean time.
comment on: http://stackoverflow.com/a/49238728
score: 1

http://stackoverflow.com/comment/85442563
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49219443
has text: Might be a slight issue where the original text contains duplicated words - you'll only get one occurrence - try `'ooo ooo ooo'` as your input. (Also - the order of the words won't be preserved - whether that's important or not is another issue)

http://stackoverflow.com/q/49148342
tagged with: reduce
has title: why 'functools.reduce' and 'itertools.chain.from_itertools' had different computation time when nested list merged
upvote count: 3
answer count: 1
accepted answer: http://stackoverflow.com/a/49148409
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49148409
tagged with: python-3.x
tagged with: functools
tagged with: python-itertools
has body: sometimes you should have nested merge to merged list(it is similar to np.flatten() ). when the list of list is given like below, and you should flatten it a = [[j for j in range(0, 10)] for i in range(0, 10000)] you have two kinds of solution to solve it. itertools.chain.from_iterable and functools.reduce. %timeit list(itertools.chain.from_iterable(a)) %timeit reduce(lambda x, y: x+y, a) do you think which one is faster and how much faster than other thing? itertools.chain.from_iterable is 1000 times faster or more(when the length of the list is bigger). If somebody knows why this thing happen, please let me know. always thx for you support and help.
tagged with: python
has comment: http://stackoverflow.com/comment/85303406
type: AnsweredQuestion
score: 2

http://stackoverflow.com/comment/85411007
has text: Hi! Sorry about that, I've adjusted the solution to have the desired output
type: AnswerComment
comment on: http://stackoverflow.com/a/49201117
score: 1
type: Comment

http://stackoverflow.com/comment/85285606
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49139855
has text: One of the sprites must have a problem, try to comment all the `all_sprites.add(...)` statements except for one, and change this one, to find which sprites create a problem and which don't
type: Comment

http://stackoverflow.com/a/49297076
has body: Providing more insight on the answer I already gave at the pcl users forum. Have a look at equation 1 and 2 of the Model Based Training, Detection and Pose Estimation of Texture-Less 3D Objects in Heavily Cluttered Scenes from Hinsterstoisser et al. commonly known as LineMOD. This is a common used method for pose estimation problem with rigid objects. Equation 1 is for non-symetric objects and 2 for symmetric ones. I can't type the expressions because Stack Overflow doens't support mathjax but the general idea is: The norm of the difference between the location where your point is estimated to be and where it actually is, summed over all points, normalized by the number of points The difference for the first one is that you no longer enforce you point correspondences. Each point from the source cloud, picks the closest point on the target cloud. Then perform the sum and averaging like before. This is not exactly a stack overflow question, it's a math exchange one.
upvote count: 1
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49216605
has comment: http://stackoverflow.com/comment/85596101
answers question: http://stackoverflow.com/q/49216605
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/85431825
score: 5
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49213695
has text: What is the content of `pokedex.py`?

http://stackoverflow.com/q/49266587
downvote count: 0
tagged with: argparse
tagged with: python
has title: Appending multiple items to a default parameter with argparse
has comment: http://stackoverflow.com/comment/85538898
has comment: http://stackoverflow.com/comment/85537037
favorite count: 0
type: Question
upvote count: 2
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85538439
linked to: http://stackoverflow.com/q/41152799
has body: I'm using argparse with Python 2.7.x and am having some trouble appending to a default parameter list. The pertinent code is shown below: parser = ArgumentParser(...) parser.add_argument('--project-list', action='append', dest='project_list', nargs='*', default=['AAA', 'BBB']) # ... args = parser.parse_args() print args.project_list Which prints the following when called: $ python program.py --project-list CCC # --&gt; project_list=['AAA', 'BBB', ['CCC']] $ python program.py --project-list CCC DDD # --&gt; project_list=['AAA', 'BBB', ['CCC', 'DDD']] However, what I would like the program to do is illustrated below: $ python program.py --project-list CCC # --&gt; project_list=['AAA', 'BBB', 'CCC'] $ python program.py --project-list CCC DDD # --&gt; project_list=['AAA', 'BBB', 'CCC', 'DDD'] From what I've found so far it seems the nargs parameter forces a list to be made, which is then appended (not sure why?). A few other solutions such as passing type=str, or type=construct_project_list (which is a function that returns a 'valid' list) haven't worked either... Thanks in advance for any help you can provide!
duplicate of: http://stackoverflow.com/q/41152799
score: 2
has comment: http://stackoverflow.com/comment/85536979

http://stackoverflow.com/a/49147901
has comment: http://stackoverflow.com/comment/85306984
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85306168
downvote count: 0
has comment: http://stackoverflow.com/comment/85306783
accepted answer of: http://stackoverflow.com/q/49147403
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85306322
has body: Try this def filter_dict(d): for key, value in d.items(): if key.startswith('@'): key = key[1:] del d["@"+key] if isinstance(value, dict): d[key] = filter_dict(value) elif isinstance(value, list): d[key] = [filter_dict(l) for l in value] else: d[key]=value return d Pass your dictionary to this function and it will produce the desired output, irrespective of the hierarchy.If abc is your dictionary then filter_dict(abc) will update abc with desired format. Note that abc will be updated automatically since dictionary is mutable. Sample code from pprint import pprint abc = { "stationlist": { "tunein": { "@base-m3u": "/sbin/tunein-station.m3u", "@base": "/sbin/tunein-station.pls", "@base-xspf": "/sbin/tunein-station.xspf" }, "station": [ { "@lc": "34753", "@br": "128", "@mt": "audio/mpeg", "@name": "Dance Wave Retro!", "@id": "1057402", "@genre": "Urban Contemporary" }, { "@lc": "12847", "@br": "64", "@logo": "http://i.radionomy.com/document/radios/a/a265/a2654f5f-669e-4b9e-ac13-962971886ad2.jpg", "@mt": "audio/aacp", "@name": "COOLfahrenheit 93 - (7)", "@id": "1735956", "@ct": "25 Hours - #11D8'1 (Soft Version)", "@genre": "Easy Listening", "@genre2": "Pop" }, ] } } def filter_dict(d): for key, value in d.items(): if key.startswith('@'): key = key[1:] del d["@"+key] if isinstance(value, dict): d[key] = filter_dict(value) elif isinstance(value, list): d[key] = [filter_dict(l) for l in value] else: d[key]=value return d print "before" pprint(abc) filter_dict(abc) print "after" pprint(abc) Output before {'stationlist': {'station': [{'@br': '128', '@genre': 'Urban Contemporary', '@id': '1057402', '@lc': '34753', '@mt': 'audio/mpeg', '@name': 'Dance Wave Retro!'}, {'@br': '64', '@ct': "25 Hours - #11D8'1 (Soft Version)", '@genre': 'Easy Listening', '@genre2': 'Pop', '@id': '1735956', '@lc': '12847', '@logo': 'http://i.radionomy.com/document/radios/a/a265/a2654f5f-669e-4b9e-ac13-962971886ad2.jpg', '@mt': 'audio/aacp', '@name': 'COOLfahrenheit 93 - (7)'}], 'tunein': {'@base': …
has comment: http://stackoverflow.com/comment/85306207
answers question: http://stackoverflow.com/q/49147403
has comment: http://stackoverflow.com/comment/85307050
has comment: http://stackoverflow.com/comment/85302459
has comment: http://stackoverflow.com/comment/85300568
has comment: http://stackoverflow.com/comment/85307108
has comment: http://stackoverflow.com/comment/85305709
type: Answer

http://stackoverflow.com/q/49128976
tagged with: ldap
tagged with: python
has title: Logging in with e-mail as ldapUser in Django
score: 0
has comment: http://stackoverflow.com/comment/85264572
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85264709
answer count: 1
tagged with: authentication
linked to: http://stackoverflow.com/q/21458071
tagged with: django
has comment: http://stackoverflow.com/comment/85263967
has answer: http://stackoverflow.com/a/49130508
has body: I am currently working on my webapp. As of now, I can login with the username (sAMAccountName) but I want to login with the e-mail-adress. I looked up some backends, but none of them could help me. Here are my setting.py AUTH_LDAP_SERVER_URI = "ldap://192.168.4.123" AUTH_LDAP_BIND_DN = "username" AUTH_LDAP_BIND_PASSWORD = "password" AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_DEBUG_LEVEL: 1, ldap.OPT_REFERRALS: 0 } AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") AUTH_LDAP_GROUP_SEARCH = LDAPSearch("DC=domain,DC=com", ldap.SCOPE_SUBTREE, "(objectClass=group)") AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail", "dn": "distinguishedName", } AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_active": "CN=users,cn=users,DC=domain,DC=com", "is_staff": "CN=users,cn=users,DC=domain,DC=com", "is_superuser": "CN=users,cn=users,DC=domain,DC=com" } AUTH_LDAP_ALWAYS_UPDATE_USER = True LDAP_AUTH_OBJECT_CLASS = "inetOrgPerson" AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, 'stream_to_console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler' }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'django_auth_ldap': { 'handlers': ['stream_to_console'], 'level': 'DEBUG', 'propagate': True, }, } } Maybe you have a good backend or I am missing something. I also tried: AUTH_LDAP_USER_SEARCH = LDAPSearch("DC=sbvg,DC=ch", ldap.SCOPE_SUBTREE, "(mail=%(user)s)") but then it creates a user with the username user@domain.com, which is also wrong.
type: Question

http://stackoverflow.com/comment/85315015
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49154677
type: Comment
has text: are you sure its the import that is the problem? It sounds like your connection times out which is unrelated to importing

http://stackoverflow.com/q/49262607
score: 0
tagged with: django
tagged with: python
has body: I have an update or create method in my form valid function and im getting the error, when I submit the form. Im not sure as to why? super(type, obj): obj must be an instance or subtype of type Full trace: File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.6/site-packages/django/contrib/auth/decorators.py" in _wrapped_view 23. return view_func(request, *args, **kwargs) File "/itapp/itapp/config/views.py" in device_details 151. form = DeviceSubnetForm(request.POST) File "/itapp/itapp/config/forms.py" in __init__ 135. super(DeviceSubnet, self).__init__(*args, **kwargs) Exception Type: TypeError at /config/device_details/2/7 Exception Value: super(type, obj): obj must be an instance or subtype of type This is the function within the view if request.method == 'GET': form = DeviceSubnetForm() else: # A POST request: Handle Form Upload form = DeviceSubnetForm(request.POST) # If data is valid, proceeds to create a new post and redirect the user if form.is_valid(): subnet_data = form.save(commit=False) obj, record = DeviceSubnet.objects.update_or_create( defaults={ 'subnet' : subnet_data.subnet, 'subnet_mask' : subnet_data.subnet_mask, 'subnet_type' : SubnetTypes.objects.get(subnet_data.subnet_type) }, subnet=subnet_data.subnet, subnet_mask=subnet_data.subnet_mask, subnet_type=SubnetTypes.objects.get(subnet_data.subnet_type) ) print(obj.id) return 'Valid' forms.py class DeviceSubnetForm(forms.ModelForm): class M…
answer count: 1
has title: Django - update or create obj must be an instance or subtype of type
type: Question
accepted answer: http://stackoverflow.com/a/49262695
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49262695

http://stackoverflow.com/a/49215926
downvote count: 0
has body: Edit:- This solution does not use groupby but uses .loc I believe that what you want is to set flag as '1' when both admit and discharge day are same and also when the Num1 is between 5 and 12 (inclusive) Here is the code that works for the logic. df.loc[(df['admit'] == df['discharge'] ) &amp; (df['Num1'].isin(num1_range)), 'flag'] = 1 df.loc[~((df['admit'] == df['discharge'] ) &amp; (df['Num1'].isin(num1_range))), 'flag'] = 0 print(df) The output is: Key Num1 Num2 admit discharge flag 0 10003 12 121 2012-05-06 2012-05-08 0.0 1 10003 13 122 2012-05-08 2012-05-10 0.0 2 10003 13 122 2012-10-10 2012-10-12 0.0 3 10003 13 124 2012-10-10 2012-10-16 0.0 4 10003 12 125 2012-10-10 2012-10-23 0.0 5 10003 13 126 2012-11-10 2012-11-11 0.0 6 10034 15 127 2012-05-20 2012-05-20 0.0 7 10034 12 128 2012-05-20 2012-05-20 1.0 You can see that only the last row satisfies the condition and has flag set as '1'. Hope this helps.
score: 1
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/49164935

scrapy
tags question: http://stackoverflow.com/q/49188298
tags question: http://stackoverflow.com/q/49186440
tags question: http://stackoverflow.com/q/49221269
tags question: http://stackoverflow.com/q/49156225
tags question: http://stackoverflow.com/q/49223145
tags question: http://stackoverflow.com/q/49223081
tags question: http://stackoverflow.com/q/49185065
tag name: scrapy
tags question: http://stackoverflow.com/q/49266391
tags question: http://stackoverflow.com/q/49136804
tags question: http://stackoverflow.com/q/49177153
tags question: http://stackoverflow.com/q/49201456
tags question: http://stackoverflow.com/q/49221014
tags question: http://stackoverflow.com/q/49145354
tags question: http://stackoverflow.com/q/49208779
tags question: http://stackoverflow.com/q/49276401
tags question: http://stackoverflow.com/q/49187766
tags question: http://stackoverflow.com/q/49274242
tags question: http://stackoverflow.com/q/49193757
tags question: http://stackoverflow.com/q/49244871
tags question: http://stackoverflow.com/q/49209771
tags question: http://stackoverflow.com/q/49141584
tags question: http://stackoverflow.com/q/49147353
tags question: http://stackoverflow.com/q/49224133
type: Tag
tags question: http://stackoverflow.com/q/49273719
tags question: http://stackoverflow.com/q/49201915
tags question: http://stackoverflow.com/q/49171414
tags question: http://stackoverflow.com/q/49213861
tags question: http://stackoverflow.com/q/49156079
tags question: http://stackoverflow.com/q/49145774
tags question: http://stackoverflow.com/q/49188016
tags question: http://stackoverflow.com/q/49157923
tags question: http://stackoverflow.com/q/49209595
tags question: http://stackoverflow.com/q/49242940

http://stackoverflow.com/comment/85406453
has text: How about `5.0 == 5`?
comment on: http://stackoverflow.com/q/49200609
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49240801
accepted answer: http://stackoverflow.com/a/49240909
has title: code is ignoring def start?
downvote count: 6
type: AnsweredQuestion
has body: from tkinter import * import os creds = 'tempfile.txt' def start(): global rootE rootE = Tk() rootE.title('welcome') greeting = Label(rootE, text='What yould you like to do?' ) sign = Button(rootE, text='register', command=Signup) login = Button(rootE, text='log in', command=Login) sign.grid(row=1,column=0, stick=W) login.grid(row=2,column=0, stick=W) rootE.geometry('200x200') rootE.mainloop() def Signup(): # This is the signup definition, global pwordE global nameE global roots roots = Tk() # This creates the window, just a blank one. roots.title('Signup') # This renames the title of said window to 'signup' intruction = Label(roots, text='Please Enter new Credidentials\n') # This puts a label, so just a piece of text saying 'please enter blah' intruction.grid(row=0, column=0, sticky=E) # This just puts it in the window, on row 0, col 0. If you want to learn more look up a tkinter tutorial :) nameL = Label(roots, text='New Username: ') # This just does the same as above, instead with the text new username. pwordL = Label(roots, text='New Password: ') # ^^ nameL.grid(row=1, column=0, sticky=W) # Same thing as the instruction var just on different rows. :) Tkinter is like that. pwordL.grid(row=2, column=0, sticky=W) # ^^ nameE = Entry(roots) # This now puts a text box waiting for input. pwordE = Entry(roots, show='*') # Same as above, yet 'show="*"' What this does is replace the text with *, like a password box :D nameE.grid(row=1, column=1, sticky=W) pwordE.grid(row=2, column=1, sticky=W) signupButton = Button(roots, text='Signup', command=FSSignup) # This creates the button with the text 'signup', when you click it, the command 'fssignup' will run. which is the def signupButton.grid(columnspan=2, sticky=W) roots.mainloop() # This just makes the window keep open, we will destroy it soon def FSSignup(): with open(creds, 'w') as f: # Creates a document using the variable we made at the top. f.write(nameE.get()) # nameE is the variable we were storing the input to. Tkin…
has comment: http://stackoverflow.com/comment/85485254
has comment: http://stackoverflow.com/comment/85485252
has answer: http://stackoverflow.com/a/49240870
possible better answer: http://stackoverflow.com/a/49240870
has comment: http://stackoverflow.com/comment/85485304
score: -6
linked to: http://stackoverflow.com/q/419163
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85485537
has comment: http://stackoverflow.com/comment/85485257
answer count: 2
tagged with: function
upvote count: 0
has comment: http://stackoverflow.com/comment/85485238
tagged with: python
has answer: http://stackoverflow.com/a/49240909
has comment: http://stackoverflow.com/comment/85485300

http://stackoverflow.com/comment/85412274
type: QuestionComment
has text: Thanks I figured ed out what was cause the issue it's the way I'm calling Powershell script incorrectly. I'm working on the resolution.
score: 0
comment on: http://stackoverflow.com/q/49183315
type: Comment

http://stackoverflow.com/a/76778927
score: 0
answers question: http://stackoverflow.com/q/49218936
type: Answer
has body: In case this helps others, I had the exact same issue, but in my case the subnet prefix length was the problem, not the firewall. The Ethernet interface on my PC was configured as /16, when for my device it needed to be /24. Even with the wrong subnet prefix length Wireshark was still able to see the packets, but Python was not. Changing the Ethernet interface to /24 fixed the issue. I changed it on Windows 10 by going to Ethernet settings, then selecting the interface my device is connected to, and under IP settings, clicking Edit, then updating the Subnet prefix length.

http://stackoverflow.com/q/49255406
score: 0
has title: Dump (append) text of web page to file
linked to: http://stackoverflow.com/q/8220669
type: UnansweredQuestion
tagged with: wget
answer count: 1
tagged with: logging
type: Question
has body: I need to dump the contents (text only) of a webpage every 1 minute to a text file (append it all to one text file) The webpage is a web log which is updated on the fly automatically. Could I use a short python script to accomplish this simple copy/paste automation?Or do you know of any ready made program that does the same? I have checked the answers to this: Python: saving large web page to file and this: Dumping a dynamic web page to file? But I am new to python so I cannot build my script on the info provided It seems that this may be a solution: https://www.seleniumhq.org/projects/webdriver/ But could you give me a small working example
tagged with: dump
linked to: http://stackoverflow.com/q/7627901
tagged with: scripting
tagged with: python
has answer: http://stackoverflow.com/a/49327518

http://stackoverflow.com/a/49201457
score: 0
answers question: http://stackoverflow.com/q/49199934
type: Answer
has body: You need to convert the frequencies to the sample rate. See https://stackoverflow.com/a/27191172/7919597 or the doc of rfftfreq: signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float) fourier = np.fft.rfft(signal) n = signal.size sample_rate = 100 freq = np.fft.fftfreq(n, d=1./sample_rate) print(freq) freq = np.fft.rfftfreq(n, d=1./sample_rate) print(freq)

http://stackoverflow.com/comment/85294086
type: Comment
score: 0
type: AnswerComment
has text: True. Thanks I added that
comment on: http://stackoverflow.com/a/49144442

http://stackoverflow.com/a/49175502
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49160354
score: 0
answers question: http://stackoverflow.com/q/49160354
has body: UPDATE I found the issue.I probably had a sort of conflict with the several packages that I've installed previously. I unistalled all tensorflow packages from my enviroment with pip and pip3 and I installed ONLY tensorflow-gpu with pip install tensorflow-gpu. Now working well: from tensorflow.python.client import device_lib device_lib.list_local_devices() [name: "/device:CPU:0" device_type: "CPU" memory_limit: 268435456 locality { } incarnation: 9774489396791002051, name: "/device:GPU:0" device_type: "GPU" memory_limit: 9234234737 locality { bus_id: 1 } incarnation: 10911103484745736471 physical_device_desc: "device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1"]

http://stackoverflow.com/comment/85305177
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49150115
type: QuestionComment
has text: https://stackoverflow.com/a/33398553/1319284 sys.get_referrers gets all the references to an object according to this answer

http://stackoverflow.com/q/49279425
has comment: http://stackoverflow.com/comment/85593515
tagged with: audio
has title: extract human vocals from song
has comment: http://stackoverflow.com/comment/85561862
downvote count: 0
tagged with: voice
has comment: http://stackoverflow.com/comment/88579801
upvote count: 15
tagged with: signal-processing
favorite count: 0
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/85609666
tagged with: algorithm
has comment: http://stackoverflow.com/comment/85609847
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/88562104
has answer: http://stackoverflow.com/a/61013758
has body: my question is about how to proceed in extracting human voice in music using the language python i have gone through this code but it extracts background music from pydub import AudioSegment from pydub.playback import play # read in audio file and get the two mono tracks sound_stereo = AudioSegment.from_file(myAudioFile, format="mp3") sound_monoL = sound_stereo.split_to_mono()[0] sound_monoR = sound_stereo.split_to_mono()[1] # Invert phase of the Right audio file sound_monoR_inv = sound_monoR.invert_phase() # Merge two L and R_inv files, this cancels out the centers sound_CentersOut = sound_monoL.overlay(sound_monoR_inv) # Export merged audio file fh = sound_CentersOut.export(myAudioFile_CentersOut, format="mp3") i need to extract human voice in song if not this then how to subtract one audio file from another audio file
has answer: http://stackoverflow.com/a/52223865
tagged with: python
linked to: http://stackoverflow.com/q/48730097
score: 15

http://stackoverflow.com/a/49133101
accepted answer of: http://stackoverflow.com/q/49132360
answers question: http://stackoverflow.com/q/49132360
has body: Ok I resolved the issue. I deleted the first line of the bash file, so I just have the command python3 /path/to/script.py. I added the quotes "" around the path of the script, and I deleted an invisible blank space at the end of the line that I didn't see. And it is working. Thank you all for your help, because it guided me in finding the solution!
type: AcceptedAnswer
type: Answer
score: 0

http://stackoverflow.com/comment/85375414
comment on: http://stackoverflow.com/q/49184761
score: 0
type: Comment
has text: I can't use sum
type: QuestionComment

http://stackoverflow.com/comment/85403311
type: Comment
has text: Try with a * glob?
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49190076

http://stackoverflow.com/comment/85523750
type: QuestionComment
has text: Can you provide the full code of the function. This while loop will return regardless of your python version (but you should use // in Python3).
comment on: http://stackoverflow.com/q/49260086
score: 0
type: Comment

http://stackoverflow.com/q/49142767
has body: I'm trying to enter a date value into a date field of our AS400/DB2 via JayDeBe. When I try with a literal SQL value everything works fine curs.execute(''' UPDATE mytable SET city = ?, mydate = date(to_date('1999-05-03', 'YYYY-MM-DD')) WHERE id = ?''', ('Somewhere', 5)) When I put the date value into a parameter curs.execute(''' UPDATE mytable SET city = ?, mydate = date(to_date(?, 'YYYY-MM-DD')) WHERE id = ?''', ('Somewhere', '1999-05-03', 5)) I get the error: [..] File "/usr/local/lib/python3.6/dist-packages/py4j/protocol.py", line 320, in get_return_value format(target_id, ".", name), value) py4j.protocol.Py4JJavaError: An error occurred while calling o1.prepareStatement. : java.sql.SQLException: [SQL0171] Argument 01 der Funktion TO_DATE ungültig. [..] which means 'argument 01 of function TO_DATE is invalid'. When I use a datetime.date value as Parameter curs.execute(''' UPDATE mytable SET city = ?, mydate = ? WHERE id = ?''', ('Somewhere', datetime.date.today(), 5)) I get the error File "/usr/local/lib/python3.6/dist-packages/py4j/protocol.py", line 290, in get_command_part command_part = REFERENCE_TYPE + parameter._get_object_id() AttributeError: 'datetime.date' object has no attribute '_get_object_id' Has anyone succeeded in storing dates into an AS400? Or any suggestions what I could try to do? Regards Volker
has comment: http://stackoverflow.com/comment/85301175
score: 1
has comment: http://stackoverflow.com/comment/85303577
has comment: http://stackoverflow.com/comment/85299949
has comment: http://stackoverflow.com/comment/85300964
tagged with: db2
tagged with: python
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/85299892
upvote count: 1
tagged with: sql
has comment: http://stackoverflow.com/comment/85302739
tagged with: jt400
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49153046
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49153046
has comment: http://stackoverflow.com/comment/85298604
has comment: http://stackoverflow.com/comment/85300432
has title: JayDeBe: Store a date into an AS400/DB2 (jt400 driver)

http://stackoverflow.com/q/49247628
tagged with: cpython
has body: Is there a way to pass a python2.7 string with a null character in the middle (such as foo\0bar) to c++ code in swig bindings? The python C bindings provide two functions: PyString_AsString and PyString_AsStringAndSize, but both functions return null terminated strings.
answer count: 1
favorite count: 0
type: Question
tagged with: swig
accepted answer: http://stackoverflow.com/a/49248060
score: 1
tagged with: python
tagged with: python-2.x
tagged with: c++
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49248060
downvote count: 0
has title: Passing a python2.7 string with internal null characters to c++
upvote count: 1

http://stackoverflow.com/q/49157989
has title: Not able to import cv2 in python3
type: Question
has comment: http://stackoverflow.com/comment/85320926
tagged with: opencv
has comment: http://stackoverflow.com/comment/85321019
tagged with: python
has comment: http://stackoverflow.com/comment/85320865
has comment: http://stackoverflow.com/comment/85366696
has comment: http://stackoverflow.com/comment/85324107
has body: When I do import cv2 I get Traceback (most recent call last): File "", line 1, in ImportError: libz-a147dcb0.so.1.2.3: cannot open shared object file: No such file or directory How should I avoid this problem? What should I do?
has comment: http://stackoverflow.com/comment/85321262
accepted answer: http://stackoverflow.com/a/49180603
type: AnsweredQuestion
tagged with: python-3.x
score: 0
has answer: http://stackoverflow.com/a/49180603
answer count: 1

http://stackoverflow.com/comment/85442094
type: QuestionComment
has text: Thanks did that! still getting the error.
score: 0
comment on: http://stackoverflow.com/q/49219139
type: Comment

http://stackoverflow.com/comment/135899802
has text: How can I add `arabic_reshaper` and `bidi` to it?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49467247
type: Comment

http://stackoverflow.com/q/49162648
accepted answer: http://stackoverflow.com/a/49237142
favorite count: 0
has body: I'm trying to format a column of numbers in Google Sheets using the API (Sheets API v.4 and Python 3.6.1, specifically). A portion of my non-functional code is below. I know it's executing, as the background color of the column gets set, but the numbers still show as text, not numbers. Put another way, I'm trying to get the equivalent of clicking on a column header (A, B, C, or whatever) then choosing the Format -> Number -> Number menu item in the GUI. def sheets_batch_update(SHEET_ID,data): print ( ("Sheets: Batch update")) service.spreadsheets().batchUpdate(spreadsheetId=SHEET_ID,body=data).execute() #,valueInputOption='RAW' data={ "requests": [ { "repeatCell": { "range": { "sheetId": all_sheets['Users'], "startColumnIndex": 19, "endColumnIndex": 20 }, "cell": { "userEnteredFormat": { "numberFormat": { "type": "NUMBER", "pattern": "#,##0", }, "backgroundColor": { "red": 0.0, "green": 0.4, "blue": 0.4 }, } }, "fields": "userEnteredFormat(numberFormat,backgroundColor)" } }, ] } sheets_batch_update(SHEET_ID, data)
tagged with: google-sheets-api
has title: Setting column in Google Sheets API (with Python) to be number-formatted
has comment: http://stackoverflow.com/comment/85363097
has comment: http://stackoverflow.com/comment/85379130
type: Question
has comment: http://stackoverflow.com/comment/85372217
tagged with: python
has answer: http://stackoverflow.com/a/49237142
has comment: http://stackoverflow.com/comment/85398005
possible better answer: http://stackoverflow.com/a/49245583
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49245583
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/85376535
score: 1
upvote count: 1

http://stackoverflow.com/a/49202045
upvote count: 1
has body: In your first function you do: vec = vec.tocsr() if sparse.issparse(vec): I don't think the issparse test does anything for you. If the input argument is a sparse matrix, it has a tocsr method, and the result is sparse matrix. If vec is a ndarray is does not have a tocsr method, and the first line will throw an error. In the rest of that function, a sparse matrix has a multiply method, and a sum method. The result of sum is dense, so np.sqrt works fine on it. Actually np.sqrt(M) also works on sparse matrix because M.sqrt exists. In the second function you work with the data attribute, which is a 1d ndarray. np.sum(np.abs(vec.data)) That's fine. But notice that M.__abs__ for a sparse matrix is self._with_data(abs(self._deduped_data())) In a slightly more round about way, funtions/methods like abs, sqrt work with the .data attribute as well. Only they return a new sparse matrix. As for the testing look at np.array_equal return bool(asarray(a1 == a2).all()) If I try to use it on output1 (I won't try your gensim solution In [106]: np.array_equal(output1, output1) /usr/local/lib/python3.5/dist-packages/scipy/sparse/compressed.py:226: SparseEfficiencyWarning: Comparing sparse matrices using == is inefficient, try using != instead. " != instead.", SparseEfficiencyWarning) Out[106]: False It doesn't like taking == on sparse matrices. Usually these are large with many 0s. That means the result will be True for all those, and hence no longer sparse. Your output1 is a sparse matrix, but, at least for these inputs, not sparse: In [107]: output1.A Out[107]: array([[0.05923489, 0.11846977, 0.17770466], [0.23693955, 0.29617444, 0.35540932], [0.4146442 , 0.4738791 , 0.53311396]], dtype=float32) But even if you get around the sparsity bit, np.array_equal(output1.A, output2.A) could fail due to a comparison of floats allclose on the dense versions is probably the simplest test: In [113]: np.allclose(output1.A, output1.A) Out[113]: True You could also compare the data (assuming the sp…
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49201063
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49201063
downvote count: 0

http://stackoverflow.com/q/49161623
duplicate of: http://stackoverflow.com/q/19796123
answer count: 0
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85329355
upvote count: 1
has comment: http://stackoverflow.com/comment/85329160
has comment: http://stackoverflow.com/comment/85329261
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85329670
has body: I'm loading a JSON and I'm printing string formatting. fmt = (u"{id:&lt;4} {title:&lt;28} {timestamp:&lt;23} {description:&lt;23}" u" {link}") and to print: for item in items print(fmt.format(**item)) This works fine. But the problem here is that I'm printing a unix timestamp. Now I've written a function (convert_unix_timestamp)which converts the unix timestamp to a readable timestamp. But how can I use this function and also use my string formatting? I was thinking about something as below but I don't know how to make this work fmt = (u"{id:&lt;4} {title:&lt;28} {self.convert_unix_timestamp(timestamp):&lt;23} {description:&lt;23}" u" {link}") Can someone tell me how I can use a function inside this above?
has comment: http://stackoverflow.com/comment/85329312
has comment: http://stackoverflow.com/comment/85329188
has comment: http://stackoverflow.com/comment/85329278
type: UnansweredQuestion
tagged with: string-formatting
has title: How to use a function in string formatting in Python
tagged with: python

http://stackoverflow.com/a/49140747
answers question: http://stackoverflow.com/q/49137519
score: 0
has comment: http://stackoverflow.com/comment/100371988
has body: After extensive searching, I found the solution. Calling setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) from my GLViewWidget fixed this issue.
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49137519

http://stackoverflow.com/comment/85269918
score: 0
type: Comment
has text: @sytech haha I tried and I still have the same problem. I guess your problem is that your previous package does not match the tensorflow dependencies, like numpy, etc. But mine, ..., I still do not know how to solve it T T
type: QuestionComment
comment on: http://stackoverflow.com/q/49122044

http://stackoverflow.com/q/49267706
has comment: http://stackoverflow.com/comment/85538926
type: UnansweredQuestion
has body: I have a slot machine with the three columns. Three fruits will spin together and then the first will stop, then the second and finally the third. I have used tkinter and this function is in a class. def animate(self): chosen_random_fruits = [] x_positions = [0.24, 0.43, 0.62] for no_of_fruits_spinning in range(3, 0, -1): for _ in range(100): random_fruits = [random.choice(self.weighted_fruits) for _ in range(no_of_fruits_spinning)] for random_fruit, x_pos in zip(random_fruits, x_positions): Label(image=self.fruits[random_fruit].image, bg="white").place(relx=x_pos, y=100) time.sleep(0.01) self.root.update() chosen_random_fruits.append(random_fruits[0]) x_positions = x_positions[1:] return chosen_random_fruits The dictionary self.fruits assigns a namedtuple (including an image) for each of the fruits. x_positions is simply to place the fruits in the correct place. Is there a more efficient or simpler way to do this than the way I have implemented?
tagged with: animation
tagged with: python
answer count: 0
downvote count: 0
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85539073
tagged with: user-interface
has comment: http://stackoverflow.com/comment/85538978
has title: Most efficient way to make a slot machine animation where each item stops spinning at a certain time
favorite count: 0
has comment: http://stackoverflow.com/comment/85539024
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/85378175
comment on: http://stackoverflow.com/q/49186198
type: Comment
has text: can you print data?i think the problem is in data after re.findall,
type: QuestionComment
score: 0

http://stackoverflow.com/q/49240034
has body: I want to install packages on a computer which does not have internet (connect via ssh) from a computer which does. My idea is that instead of uploading the individual pip packages for each project + python version (same reasons why you'd want to use a virtual environment), I'd like to install the target package in an empty virtual environment on the machine with internet access and then scp all dependencies from my_env/lib/python3.6/site-packages to the remote machine. Then I'd pip install from there. Ideal scenario: Machine with internet $ python -m venv my_env $ source ./my_env/bin/activate (my_env) $ pip install lime Then send my_env/lib/python3.6/site-packages to the remote machine (let's name itsource_packages/) Machine without internet $ sudo pip install lime --find-everything-in ./source_packages I have tried pip install lime --no-index --find-links path/to/my_env/lib/python3.6/site-packages/ But this raises an error: Collecting lime Could not find a version that satisfies the requirement lime (from >versions: ) No matching distribution found for lime EDIT The proposed solutions (see comments) are close to working except I have platform compatibility issues. Internet machine is a Mac, remote server is CentOS. I'm therefore afraid that unzipping site-packages/ in the server's lib/python3.6/ directory would fail in some cases. Regarding the pip download solution, it is also partial as default behavior is to download according to current platform but the --platform flag only works with binaries. A package as lime can't therefore be downloaded specifying the platform. A workaround would be to be able to run something in the likes of pip download --only-binary=:all: --platform=linux_x86_64 lime but with a fallback to download the source if the binary asked for is not available
linked to: http://stackoverflow.com/q/11091623
has comment: http://stackoverflow.com/comment/85484229
type: Question
has comment: http://stackoverflow.com/comment/85483883
has comment: http://stackoverflow.com/comment/85508642
has comment: http://stackoverflow.com/comment/85484126
linked to: http://stackoverflow.com/q/34704163
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85484321
has comment: http://stackoverflow.com/comment/85485993
tagged with: pip
tagged with: python
tagged with: virtualenv
has comment: http://stackoverflow.com/comment/85485977
has comment: http://stackoverflow.com/comment/85494776
has comment: http://stackoverflow.com/comment/85497253
has comment: http://stackoverflow.com/comment/85484331
score: 0
linked to: http://stackoverflow.com/q/48925659
has title: pip install packages from files in virtual env
has comment: http://stackoverflow.com/comment/85493632

http://stackoverflow.com/q/49203023
tagged with: openai-gym
has answer: http://stackoverflow.com/a/66794014
tagged with: python
has answer: http://stackoverflow.com/a/67944086
favorite count: 0
type: Question
score: 9
has body: I've just installed openAI gym on Google Colab, but when I try to run 'CartPole-v0' environment as explained here. Code: import gym env = gym.make('CartPole-v0') for i_episode in range(20): observation = env.reset() for t in range(100): env.render() print(observation) action = env.action_space.sample() observation, reward, done, info = env.step(action) if done: print("Episode finished after {} timesteps".format(t+1)) break I get this: WARN: gym.spaces.Box autodetected dtype as &lt;class 'numpy.float32'&gt;. Please provide explicit dtype. --------------------------------------------------------------------------- NameError Traceback (most recent call last) &lt;ipython-input-19-a81cbed23ce4&gt; in &lt;module&gt;() 4 observation = env.reset() 5 for t in range(100): ----&gt; 6 env.render() 7 print(observation) 8 action = env.action_space.sample() /content/gym/gym/core.py in render(self, mode) 282 283 def render(self, mode='human'): --&gt; 284 return self.env.render(mode) 285 286 def close(self): /content/gym/gym/envs/classic_control/cartpole.py in render(self, mode) 104 105 if self.viewer is None: --&gt; 106 from gym.envs.classic_control import rendering 107 self.viewer = rendering.Viewer(screen_width, screen_height) 108 l,r,t,b = -cartwidth/2, cartwidth/2, cartheight/2, -cartheight/2 /content/gym/gym/envs/classic_control/rendering.py in &lt;module&gt;() 21 22 try: ---&gt; 23 from pyglet.gl import * 24 except ImportError as e: 25 reraise(prefix="Error occured while running `from pyglet.gl import *`",suffix="HINT: make sure you have OpenGL install. On Ubuntu, you can run 'apt-get install python-opengl'. If you're running on a server, you may need a virtual frame buffer; something like this should work: 'xvfb-run -s \"-screen 0 1400x900x24\" python &lt;your_script.py&gt;'") /usr/local/lib/python3.6/dist-packages/pyglet/gl/__init__.py in &lt;module&gt;() 225 else: 226 from .carbon import CarbonConfig as Config --&gt; 227 del base 228 229 # XXX remove NameError: name 'base'…
linked to: http://stackoverflow.com/q/66335165
upvote count: 9
has answer: http://stackoverflow.com/a/49698722
answer count: 5
linked to: http://stackoverflow.com/q/44150310
downvote count: 0
has answer: http://stackoverflow.com/a/49205552
possible better answer: http://stackoverflow.com/a/50719412
tagged with: google-colaboratory
has title: openAI Gym NameError in Google Colaboratory
has answer: http://stackoverflow.com/a/50719412
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49205552

http://stackoverflow.com/comment/85289198
type: QuestionComment
comment on: http://stackoverflow.com/q/49140942
has text: This may help: https://stackoverflow.com/q/42470133/334402
type: Comment
score: 0

http://stackoverflow.com/q/49170605
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: I am using raw sockets in python to send SYN packets repeatedly at high rate for a project. I am able to send SYN at a rate of 120 Mb/S using below python Script. Is there a way to optimize it to increase the rate of the packets? I think CPU is the bottleneck, as my NIC supports upto 1 Gbps. I am even constructing the packet once and just resending it repeatedly. # some imports import thread import socket, sys from struct import * import time import datetime as dt def sendFunc(s, packet, dest_ip, sizeOfPacket): start_time = time.time() i = 0 while(1): time_diff = time.time() - start_time i = i + 1 if time_diff &gt; 1: start_time = time.time() print i*sizeOfPacket i = 0 s.sendto(packet, (dest_ip , 0 )) # put this in a loop if you want to flood the target # checksum functions needed for calculation checksum def checksum(msg): s = 0 # loop taking 2 characters at a time for i in range(0, len(msg), 2): w = (ord(msg[i]) &lt;&lt; 8) + (ord(msg[i+1]) ) s = s + w s = (s&gt;&gt;16) + (s &amp; 0xffff); #s = s + (s &gt;&gt; 16); #complement and mask to 4 byte short s = ~s &amp; 0xffff return s #create a raw socket try: s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP) except socket.error , msg: print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() # tell kernel not to put in headers, since we are providing it s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # now start constructing the packet packet = ''; source_ip = 'x.x.x.x' dest_ip = 'y.y.y.y' # or socket.gethostbyname('www.google.com') # ip header fields ihl = 5 version = 4 tos = 0 tot_len = 20 + 20 # python seems to correctly fill the total length, dont know how ?? id = 54321 #Id of this packet frag_off = 0 ttl = 255 protocol = socket.IPPROTO_TCP check = 10 # python seems to correctly fill the checksum saddr = socket.inet_aton ( source_ip ) #Spoof the source ip address if you want to daddr = socket.inet_aton ( dest_ip ) ihl_version = (version &lt;&lt; 4…
upvote count: 4
tagged with: raw-sockets
has title: Increase SYN packet sending rate in the python script
score: 3
has comment: http://stackoverflow.com/comment/85446517
has comment: http://stackoverflow.com/comment/85441818
has comment: http://stackoverflow.com/comment/85441029
has comment: http://stackoverflow.com/comment/85444624
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85446583
has comment: http://stackoverflow.com/comment/85651170
has comment: http://stackoverflow.com/comment/85687572
has comment: http://stackoverflow.com/comment/85455440
type: Question
tagged with: network-programming
tagged with: sockets

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/49266926
tags question: http://stackoverflow.com/q/49166617
tags question: http://stackoverflow.com/q/49222761
tags question: http://stackoverflow.com/q/49165589
tags question: http://stackoverflow.com/q/49187150
tags question: http://stackoverflow.com/q/49205744
tags question: http://stackoverflow.com/q/49157672
tags question: http://stackoverflow.com/q/49179549
tags question: http://stackoverflow.com/q/49251267
type: Tag
tags question: http://stackoverflow.com/q/49274956
tags question: http://stackoverflow.com/q/49245779

http://stackoverflow.com/q/49181413
type: Question
has body: I encountered a difficulty in tagging location with its type. (I mean mountain, lake, beach and so on) please click here to see the screenshot of my data, it doesn't allow me to show image The geo info I have are longitude/latitude and country code/city/postcode. I'm wondering how can I tag them with the nearest geographic object (mountain, lake...)? Thank you, guys!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85370913
tagged with: geospatial
has title: Tag location with its type (mountain, lake, beach and so on)
tagged with: python
has comment: http://stackoverflow.com/comment/85368936
has comment: http://stackoverflow.com/comment/85372015
score: 0
answer count: 0
tagged with: geolocation

http://stackoverflow.com/a/60052816
answers question: http://stackoverflow.com/q/49177222
upvote count: 8
downvote count: 0
has body: For Python3. chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option("useAutomationExtension", False) chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"]) driver = webdriver.Chrome(options=chrome_options)
type: Answer
score: 8

http://stackoverflow.com/a/51332805
type: Answer
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49197269
has body: You need to inherit from Base Widget. If you use the template below, you can easily create your custom bootstrap groups. in forms.py from django import forms from django.forms import Widget from django.utils.safestring import mark_safe class PrependWidget(Widget): """ Widget that prepend boostrap-style span with data to specified base widget """ def __init__(self, base_widget, data, *args, **kwargs): u"""Initialise widget and get base instance""" super(PrependWidget, self).__init__(*args, **kwargs) self.base_widget = base_widget(*args, **kwargs) self.data = data def render(self, name, value, attrs=None): u"""Render base widget and add bootstrap spans""" field = self.base_widget.render(name, value, attrs) return mark_safe(( u' ' u' ' u' %(data)s' u' ' u' ' u' ' ) % {'field': field, 'data': self.data}) class MyForm(forms.Form): example_field = forms.CharField(max_length=255, min_length=1, label='', required=False, widget=PrependWidget(base_widget=forms.TextInput, data='$')) Source
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/49197269
downvote count: 0

http://stackoverflow.com/comment/85544940
score: 0
has text: what about using "r" for reading, "binary()" for writing into DB and then "wb" for recovering
type: Comment
comment on: http://stackoverflow.com/q/49249200
type: QuestionComment

http://stackoverflow.com/comment/85427058
score: 0
type: Comment
type: QuestionComment
has text: You probably just have to change `self.movex += x` to `self.movex = x` (and the same for `self.movey`), but I can't say that certainly without seeing the complete code.
comment on: http://stackoverflow.com/q/49210083

point
type: Tag
tag name: point
tags question: http://stackoverflow.com/q/49122352

http://stackoverflow.com/a/49138408
score: 0
type: Answer
has body: I think you want set e.g. set(arr2).issubset(arr1)
answers question: http://stackoverflow.com/q/49138355

aes
tag name: aes
tags question: http://stackoverflow.com/q/49186639
tags question: http://stackoverflow.com/q/49169968
tags question: http://stackoverflow.com/q/49245524
type: Tag

http://stackoverflow.com/q/49247369
has answer: http://stackoverflow.com/a/49247777
has body: I'm having some trouble with pytorch. When calculating mu and sig this message appears: ValueError: result of slicing is an empty tensor Here's my code: x = mu + sig*torch.randn(N,1) S = -x**2 + 100 sorted_v , I = torch.sort(S,0) mu = alpha*torch.mean(x[I[(1-rho)*N:N]]) + (1-alpha)*mu sig = alpha*torch.std(x[I[(1-rho)*N:N]]) + (1-alpha)*sig In MATLAB I would do something like this: mu = alpha*mean(x(I((1-rho)*N:N))) + (1-alpha)*mu; sig = alpha*std(x(I((1-rho)*N:N))) + (1-alpha)*sig; What is wrong and why? Thak you so much.
has comment: http://stackoverflow.com/comment/85499113
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85509320
tagged with: python
has title: How to index a tensor in pytorch?
tagged with: matlab
tagged with: pytorch
score: 0
has comment: http://stackoverflow.com/comment/85509378
answer count: 1

http://stackoverflow.com/comment/124856898
type: Comment
has text: This is the best solution in my opinion
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/69413655

http://stackoverflow.com/a/49243781
has body: You can select the data with Loc == b and interpolate the values, then pivot df.loc[df['Loc'] == 'b', 'Value']= df.loc[df['Loc'] == 'b', 'Value'].interpolate() df.pivot(index = 'Date', columns = 'Loc', values = 'Value') Loc a b Date 1/1/2018 1.000 1.000 2/1/2018 2.000 2.000 3/1/2018 nan 3.000 OR, interpolate the required column on your pivoted data df['b'] = df['b'].interpolate()
answers question: http://stackoverflow.com/q/49243689
type: Answer
score: 4
upvote count: 4
accepted answer of: http://stackoverflow.com/q/49243689
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49209925
has answer: http://stackoverflow.com/a/49209971
score: 7
has title: 'Series' object has no attribute 'applymap'
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85424464
has body: I am trying to use applymap to my dataset to create floats into integers. But I get the "'Series' object has no attribute 'applymap'" error. import pandas as pd import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np from matplotlib.pyplot import pie, axis, show from pandas import Series,DataFrame class Dataset(): def __init__(self, input): self.choice = input self.file = 0 def read(self): if self.choice == ("1"): self.file = pd.read_csv('mycsv.csv') self.file.plot(kind='bar') print(df) self.file['Value'].applymap(float) def __str__(self): return str(self.file) def applymap(self): return self.file.applymap(float) i = (input("Pick a DataSet= ")) df = Dataset(i) df.read() plt.show()
downvote count: 0
answer count: 1
tagged with: python
upvote count: 7
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49209971
tagged with: pandas

http://stackoverflow.com/comment/85285449
has text: @feetwet sometime multiple line is good for reading and speed:-)
comment on: http://stackoverflow.com/a/49140028
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/a/49186963
type: Answer
answers question: http://stackoverflow.com/q/49186510
score: 0
has body: In Java, For this, I will write a script which will first convert one file into Object of your json data. And in any loop, I will do same for your 100 files and set those objects into list. So that I can write that list in single file easily using Jackson library. To convert your Json file data to Pojo, you can take help of a site mentioned below : http://pojo.sodhanalibrary.com/

http://stackoverflow.com/comment/85561233
score: 0
type: Comment
type: QuestionComment
has text: `ws.append()` will automatically write to the next row in a worksheet.
comment on: http://stackoverflow.com/q/49273261

http://stackoverflow.com/comment/85402129
has text: The code you show loads the shapefile, but it does not draw anything, so it's not clear how you draw it and hence we cannot know why `facecolor` is not working.
comment on: http://stackoverflow.com/q/49198240
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49179052
type: AnsweredQuestion
score: 0
possible better answer: http://stackoverflow.com/a/49179427
has comment: http://stackoverflow.com/comment/85364005
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85384764
tagged with: import
favorite count: 0
has comment: http://stackoverflow.com/comment/85363618
type: Question
answer count: 2
has body: I am having trouble trying to import a dictionary object that I have declared and filled with key,value pairs in another Python file. A bit of background -- I am working with accessing the Reddit API and then filling a dictionary with subreddit names and a score I have given them, based off of Reddit comments that have been retrieved. My main goal with importing the dictionary is in order to find a way to work with said dictionary of data, to mess around with, without having to make repeated calls to the API and having to wait to keep refilling the dictionary each time I want to test if it runs. At the moment, I have looked around the internet and other questions on StackOverflow about importing just a dictionary object from another file and class and I keep getting the same error where it says that the 'module' object has no attribute. Please see my example below: from subreddit_score import main # the dictionary obj that I wish to use in subreddit_score.py is called top_five d = subreddit_score.top_five I'm unsure as to why this is, so if someone would be able to help me I would greatly appreciate it. Also: if there is a better way to do this, I would also appreciate any input. But I am mainly just asking for a way to import a dictionary variable. Thanks! EDIT: Traceback error: Traceback (most recent call last): File "tester.py", line 8, in &lt;module&gt; d = subreddit_score.top_five AttributeError: 'module' object has no attribute 'top_five' subreddit_score.py def main(): # fetchRedditData() returns a dictionary top_five = fetchRedditData()
has title: How to use a dictionary that's been declared and filled in another file in Python?
has answer: http://stackoverflow.com/a/49179427
upvote count: 1
has comment: http://stackoverflow.com/comment/85363556
accepted answer: http://stackoverflow.com/a/49179519
downvote count: 1
has answer: http://stackoverflow.com/a/49179519

http://stackoverflow.com/comment/85666335
has text: did one of the below solutions help? If so, feel free to accept one (green tick on left), or ask further questions.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49187748

http://stackoverflow.com/q/49275827
accepted answer: http://stackoverflow.com/a/49276304
type: AnsweredQuestion
tagged with: conv-neural-network
has answer: http://stackoverflow.com/a/49276304
score: 1
has title: Preblem in shape of data with Conv1D in Keras
has body: I'm learning Keras, and I’m trying to classify signals according to their frequencies. So for beginning my code is like that: import numpy as np from keras.models import Sequential from keras.layers import Conv1D from keras.layers import AveragePooling1D from keras.layers import Dense from keras.layers import Dropout #DATA time=np.arange(0,20,0.05) signal=np.sin(time) out=np.array([1,0,0]) #MODEL model = Sequential() model.add(Conv1D(4, 60, padding='same', activation='relu',input_shape=(400,1))) model.add(AveragePooling1D(pool_size=5, strides=None, padding='valid')) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(3, activation='softmax')) model.compile(loss='binary_crossentropy', optimizer='Adam', metrics=['accuracy']) history = model.fit(signal, out) and I have this error. builtins.ValueError: Error when checking input: expected conv1d_1_input to have 3 dimensions, but got array with shape (400, 1) but I don't understand where the problem is.
favorite count: 0
type: Question
upvote count: 2
answer count: 1
tagged with: neural-network
tagged with: machine-learning
tagged with: python
tagged with: keras
downvote count: 1

http://stackoverflow.com/comment/85268759
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49131331
type: AnswerComment
has text: Sorry, forgot an offset :) it has been corrected now.

http://stackoverflow.com/comment/85526284
type: QuestionComment
has text: `while True: try:....except EOFError: break`?
comment on: http://stackoverflow.com/q/49261006
type: Comment
score: 0

http://stackoverflow.com/q/49143852
favorite count: 0
has title: Trouble opening files in python with VS Code
answer count: 3
has comment: http://stackoverflow.com/comment/85293001
upvote count: 5
tagged with: python
has comment: http://stackoverflow.com/comment/136118464
has body: I can't seem to open basic text files when I run a python script in VS Code, the code runs fine when I use it in Idle but VSCode will give me a FileNotFound error, is there some sort of extension that allows me to do this? Right now I'm only using the Python and Code Runner extension. example of my code: def getInput(textFile): file=open(textFile,'r') print(file.readlines())
type: Question
has comment: http://stackoverflow.com/comment/85293072
has comment: http://stackoverflow.com/comment/85293698
score: 5
tagged with: visual-studio-code
has answer: http://stackoverflow.com/a/49275867
has comment: http://stackoverflow.com/comment/85293028
has comment: http://stackoverflow.com/comment/85293024
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85293035
downvote count: 0
has comment: http://stackoverflow.com/comment/85295583
has comment: http://stackoverflow.com/comment/115795760
has answer: http://stackoverflow.com/a/63443854
has answer: http://stackoverflow.com/a/61166143

http://stackoverflow.com/q/49233035
has comment: http://stackoverflow.com/comment/85469374
has answer: http://stackoverflow.com/a/49233091
tagged with: python-2.7
tagged with: try-except
upvote count: 0
answer count: 1
has title: Unable to get the type of data user inputs
has body: I am trying to get the type of data user inputs, but I am getting some issues with code. I tried with the below code: def user_input_type(): try: user_input = int(raw_input("Enter set of characters or digit")) except: try: user_input = str(user_input) except Exception as e: print e return type(user_input) return type(user_input) print user_input_type() but it gives me 2 warnings before running the code. Local variable user_input might be referenced before assignment. Too broad exception clause such as no exception class specified, or specified as Exception. After running the code when I enter digits it gives me proper value but when I enter character it gives me an error: UnboundLocalError: local variable 'user_input' referenced before assignment Please help.
downvote count: 1
favorite count: 0
score: -1
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85469380
tagged with: python

http://stackoverflow.com/comment/85299184
score: 0
has text: Can you add `register.html` code also?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49147284

http://stackoverflow.com/comment/104790246
score: 0
type: QuestionComment
type: Comment
has text: What do you get when you do `result.summary()`? Do you know if you have a good model?
comment on: http://stackoverflow.com/q/49239727

http://stackoverflow.com/q/49266989
tagged with: python
has answer: http://stackoverflow.com/a/49267953
has title: Converting a binary image file into a 224*224 image in numpy array
type: Question
tagged with: numpy
type: UnansweredQuestion
score: 0
has body: I am reading an image (image size is Not 224*224) and it is this type: def fetch_from_s3(client, image_s3url): bucket, key = image_s3url.split('/',2)[-1].split('/',1) result = client.get_object(Bucket=bucket, Key=key) return result['Body'].read() img =fetch_from_s3(client, image_s3url) # print(img) &gt;&gt; '\xff\xd8\xff\xdb\x00C\x00\....' What I need: convert it into 224*224 image and then into numpy array. I have a time consuming way to do it: save it as an jpg file convert the jpg into 224*224, and then into numpy array delete this jpg file Since I have millions of images to process, I wish to find a way to skip step 1 and 3 because they request a lot of extra time. Is there a way to convert an arbitrary binary image file into numpy array that represent 224*224 image, directly ?
answer count: 1
tagged with: amazon-ec2
has comment: http://stackoverflow.com/comment/85537516
tagged with: amazon-s3

http://stackoverflow.com/a/49164480
type: Answer
downvote count: 1
score: 8
answers question: http://stackoverflow.com/q/49164443
upvote count: 9
has body: The trailing comma makes a tuple, with a single element, s. Python doesn't require parentheses to make a tuple unless there is ambiguity (e.g. with function call parens); aside from the empty tuple (()), you can usually make tuples with just commas, no parentheses at all. In this case, a single trailing comma, s,, is equivalent to (s,). Since groups has list values, this means that doing += s, is equivalent to .append(s) (technically, it's closer to .extend((s,)), but the end result is the same). Someone is probably trying to save a few keystrokes. If you omitted the comma, it would be doing list += str, interpreting the str as a sequence of characters and extending the list with each of the resulting len 1 strings, as you observed.

http://stackoverflow.com/comment/85536060
score: 0
type: Comment
has text: You may want to mention _os.exit directly after “the only way to defeat it is to crash the compiler”. Right now it’s mixed inbeteween examples where finally wins.
type: AnswerComment
comment on: http://stackoverflow.com/a/49262555

http://stackoverflow.com/comment/85423414
has text: Aah, as Englisch is not my first language, I misinterpreted "sibling" - it was not clear to me that in `ax2 = ax1.twinx()` both axes are like brother and sister, not like mother and son. And another "Aah": I didn't know that you can create custom attributes just like that - a gaping hole in my python knowledge. I agree, that is the cleanest and safest solution.
comment on: http://stackoverflow.com/a/49208080
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/49155728
has comment: http://stackoverflow.com/comment/85321009
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85316096
has comment: http://stackoverflow.com/comment/85316296
upvote count: 1
has comment: http://stackoverflow.com/comment/85316229
has comment: http://stackoverflow.com/comment/85316514
has comment: http://stackoverflow.com/comment/85316399
answer count: 1
has comment: http://stackoverflow.com/comment/85316094
has comment: http://stackoverflow.com/comment/85316223
has comment: http://stackoverflow.com/comment/85316361
has comment: http://stackoverflow.com/comment/85316143
linked to: http://stackoverflow.com/q/10140610
has comment: http://stackoverflow.com/comment/85321156
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85316324
has comment: http://stackoverflow.com/comment/85316488
downvote count: 2
has title: Maximal elements in partial order
has comment: http://stackoverflow.com/comment/85322644
linked to: http://stackoverflow.com/q/21560659
has comment: http://stackoverflow.com/comment/85316271
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85316236
has answer: http://stackoverflow.com/a/49238066
has comment: http://stackoverflow.com/comment/85316403
accepted answer: http://stackoverflow.com/a/49238066
has comment: http://stackoverflow.com/comment/85321311
has body: I am looking for Python code to find maximal elements in a partial order. There are two other posts, which address the problem, Efficient algorithm to find the maximal elements of a partially ordered set Finding maximal elements of a poset&#39;s subset but they only have vague descriptions and no code. Also some years have passed, since these were asked. edit: To be more specific, both of them suggest building a DAG. My own idea is with some loops, and adding to and deleting from lists. However, I would like to know whether there is some short "pythonic" way, of coding this. More precisely, I have a list of arrays with entries 0,1; all of the same length. These arrays are the image space of some matrix over GF(2), the field with just 0 and 1. Let x and y be two arrays. I say x &lt;= y, if this inequality holds piecewise. edit: More precisely, my inequality is given by the function def leq(x,y): return all([x[i] &lt;= y[i] for i in range(len(x))]) Example Input: [1 1 0] [1 0 0] [1 0 1] Output: [1 1 0] [1 0 1] edit I have written down my idea import numpy as np l = [np.array([1, 1, 0]), np.array([1, 0, 0]), np.array([0, 1, 1])] l.sort(reverse=True, key=np.sum) maximal = [l[0]] for e in l: i = 0 replaced = False while i &lt; len(maximal): if (maximal[i] &lt;= e).all(): if replaced: maximal.remove(maximal[i]) else: maximal[i] = e.copy() replaced = True if (e &lt;= maximal[i]).all(): break i += 1 if i == len(maximal) and not replaced: maximal.append(e.copy()) How can I compute this nicely (shorter code/faster runtime) in Python?
has comment: http://stackoverflow.com/comment/85321067

http://stackoverflow.com/comment/85440771
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49213331
has text: first sentence of my question body describe it. :) Your second example works, but completely ruin main goal of use data validation library, you move part of logic outside of validation procedure, it`s definitely not what i want .Tnx for your answer.

http://stackoverflow.com/q/49178621
has answer: http://stackoverflow.com/a/49178994
tagged with: python
tagged with: css
tagged with: selenium-webdriver
type: AnsweredQuestion
answer count: 2
has title: ElementNotVisibleException: element not visible Python
score: 0
possible better answer: http://stackoverflow.com/a/49180624
tagged with: selenium
has comment: http://stackoverflow.com/comment/85366759
has answer: http://stackoverflow.com/a/49180624
has body: I'm new to Python and Selenium and I've come across an issue when trying to click on a button via webdriver. The HTML of the div I'm trying to click through is: Decline Accept I want to use .click() on the button with class name 'class="btn btn-green"'. I have used the following code to select the element (after following the solutions in other similar SO questions. driver.find_element_by_css_selector(".btn-green") It looks like webdriver can find the element but when I try to apply .click() I get: ElementNotVisibleException: element not visible I then did some digging into the element (thinking I could bypass by using x, y coordinates to click through) but after using .size and .location I get: {'x': 0, 'y': 0} {'height': 0, 'width': 0} Any help you could give on how to get around this would be really appreciated. Thanks
accepted answer: http://stackoverflow.com/a/49178994
type: Question
tagged with: xpath

http://stackoverflow.com/q/49241476
tagged with: matplotlib
has title: Matlibplot table stretching and moving
has answer: http://stackoverflow.com/a/49241562
type: Question
has answer: http://stackoverflow.com/a/49241667
answer count: 2
accepted answer: http://stackoverflow.com/a/49241667
tagged with: figure
possible better answer: http://stackoverflow.com/a/49241562
has body: Im trying to adjust this table so that it will take up the entire window, but no combination of the top, bottom left and right sliders will allow me to do it, all they do is shrink the grid while translating it. Is there a way to stretch this vertically? Here is my code: import numpy as np import matplotlib.pyplot as plt from matplotlib import colors from random import randint def colour(value): r,g,b = 0,0,0 if value &lt; 1: r = 1 g = 1*value if value &gt; 1: r = 1 - 1*(value-1) g = 1 if value == 1: r = 1 g = 1 if value &gt; 2: b = 1 colour = (r,g,b) return colour ncols, nrows = 7,8 row= [[]]*nrows for i in range(nrows): row[i] = i*3 print(row) col = ['M', 'T', 'W', 'Th', 'F', 'Sat', 'Sun'] list = [] text = ['','','','','','',''] for a in range(nrows): list.append(text) fig, ax = plt.subplots() ax.axis('tight') ax.axis('off') image = ax.table(cellText=list, colLabels = col, rowLabels=row) for j in range(ncols): for i in range(nrows): print(i,j) value = randint(0,200) value = value / 100 image._cells[(i+1,j)].set_facecolor(colour(value)) figManager = plt.get_current_fig_manager() figManager.window.showMaximized() fig.tight_layout() plt.show()
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: stretch

http://stackoverflow.com/comment/85544159
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49270573
score: 0
has text: If it will always be the same format, try splitting on `'WW'` and then parsing the right side as a float and sorting on that

http://stackoverflow.com/q/49167070
type: Question
has body: I want to do Cross Validation on my SVM classifier before using it on the actual test set. What I want to ask is do I do the cross validation on the original dataset or on the training set, which is the result of train_test_split() function? import pandas as pd from sklearn.model_selection import KFold,train_test_split,cross_val_score from sklearn.svm import SVC df = pd.read_csv('dataset.csv', header=None) X = df[:,0:10] y = df[:,10] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=40) kfold = KFold(n_splits=10, random_state=seed) svm = SVC(kernel='poly') results = cross_val_score(svm, X, y, cv=kfold) #Cross validation on original set or import pandas as pd from sklearn.model_selection import KFold,train_test_split,cross_val_score from sklearn.svm import SVC df = pd.read_csv('dataset.csv', header=None) X = df[:,0:10] y = df[:,10] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=40) kfold = KFold(n_splits=10, random_state=seed) svm = SVC(kernel='poly') results = cross_val_score(svm, X_train, y_train, cv=kfold) #Cross validation on training set
type: UnansweredQuestion
tagged with: cross-validation
tagged with: python
has title: Cross Validation Python Sklearn
tagged with: svm
score: 0
tagged with: classification
answer count: 1
upvote count: 1
tagged with: scikit-learn
downvote count: 1
has answer: http://stackoverflow.com/a/49167129
favorite count: 0

http://stackoverflow.com/comment/85391818
type: Comment
comment on: http://stackoverflow.com/q/49193589
type: QuestionComment
score: 0
has text: did this helps: https://stackoverflow.com/questions/42874825/python-functions-with-multiple-parameter-brackets

http://stackoverflow.com/a/49263611
has body: The reason two for loops are faster than slicing is that when slicing returns only a small subset of the array iterating is faster. def npslice(arr,num): arr[num::num]+=num def arriter(arr,num,l): for a in range(num,l,num): arr[a]+=num and the timing*: %timeit -n1 -r1 npslice(sod2,50000) %timeit -n1 -r1 arriter(sod2,50000,N+1) 1 loop, best of 1: 82 µs per loop 1 loop, best of 1: 65.1 µs per loop So for most of the way (inside the outer for loop) the (inner) for loop is a bit faster than slicing using numpy. the "-n1 -r1" options are set because the python interpeter optimizes the slicing operation when it is preformed more than once so the timeit function throws this warning when it is not set - The slowest run took 5.07 times longer than the fastest. This could mean that an intermediate result is being cached.
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49261593

http://stackoverflow.com/q/49153945
has title: How to take in > 1 positional argument in a sequence
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 2
accepted answer: http://stackoverflow.com/a/49154062
has answer: http://stackoverflow.com/a/49154062
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85312462
downvote count: 1
has comment: http://stackoverflow.com/comment/85312375
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49154418
has answer: http://stackoverflow.com/a/49154418
has body: Here is my code: def max_sum2(nums): new_sequence = [] # first run: add up positive numbers for i in range(0, len(nums)): if i &gt;= len(nums) - 1: if nums[i - 1] &gt;= 0 and nums[i] &gt;= 0: new_sequence.append(nums[i - 1] + nums[i]) else: new_sequence.append(nums[i - 1]) new_sequence.append(nums[i]) if nums[i] &gt;= 0 and nums[i + 1] &gt;= 0: new_sequence.append(nums[i] + nums[i + 1]) else: new_sequence.append(nums[i]) new_sequence.append(nums[i + 1]) return new_sequence When I tried print(max_sum2(3, -10, 4, -1, 2, 3, 6, -7)) it gave the following error: Traceback (most recent call last): File "D:/Coding/Daniel/CS2231/Test.py", line 36, in &lt;module&gt; print(max_sum2(3, -10, 4, -1, 2, 3, 6, -7)) TypeError: max_sum2() takes 1 positional argument but 8 were given May I ask how to use these sort of sequences (as in "(num, num...)") effectively, or how to take in more than 1 argument? Note: code is unfinished, please do not highlight unfinished areas
score: 0

http://stackoverflow.com/q/49159217
tagged with: python
has body: I am trying to arrange content in a tuple to fit a specific column layout. Example layout: PETER PAUL MALE 100000 MARGARET FEMALE 1000 MICHAEL JORDAN MALE 1 AGNES FEMALE 200 But when I iterate over the tuple to print the contents, it outputs: PETER PAUL MALE 100000 MARGARET FEMALE 1000 MICHAEL JORDAN MALE 1 AGNES FEMALE 200 Also when I return row, it only returns the first tuple and not all of them. I am returning it because I want to use it in another function. This is the code below: def text(): rows = (("PETER PAUL", "MALE", "100000"), ("MARGARET ", "FEMALE", "1000"), ("MICHAEL JORDAN", "MALE", "1"),("AGNES", "FEMALE", "200")) for row in rows: # print(" ".join(row)) print("".join(row[0]), "".join(" "), "".join(row[1]), "".join(" "), "".join(row[2])) #return row text() I use the join method, but I couldn't find ljust, which I think is no longer available in python3.
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49159309
answer count: 2
has title: How to arrange content in printed tuple
upvote count: 3
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85326312
favorite count: 0
has comment: http://stackoverflow.com/comment/85323564
type: Question
has answer: http://stackoverflow.com/a/49159264
score: 3
has comment: http://stackoverflow.com/comment/85323510

http://stackoverflow.com/a/49176935
score: 5
upvote count: 5
has body: You have two lists, so using: [df.columns.values.tolist()] + df.values.tolist() &gt;&gt;&gt; [['Col 1', 'Col 2', 'Col 3'], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
type: Answer
answers question: http://stackoverflow.com/q/49176376
downvote count: 0

http://stackoverflow.com/comment/85506836
score: 0
type: Comment
has text: does removing `target="_blank"` help ? I think the token is not being passed because the link is getting opened in a new tab, not sure though.
type: QuestionComment
comment on: http://stackoverflow.com/q/49208083

http://stackoverflow.com/comment/85440027
has text: @piRSquared - In my opinion `np.array([t.hour * 3600 + t.minute * 60 + t.second for t in s.index.get_level_values(1)],'timedelta64[s]')` should be better, because more general.
type: Comment
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49217798

http://stackoverflow.com/a/49163998
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49163663
upvote count: 1
type: AcceptedAnswer
score: 1
has body: My answer is totally based on the text below (you typed, of course): I need to remove all invalid Windows characters so directory/file names do not include: &lt; > : " / \ | ? * Windows also doesn’t seem to like spaces at the end of a directory/file name. Windows also doesn’t like periods at the end of directory names. So here we go (for file/directory): unicode(re.sub(r'(\&lt;|\&gt;|\:|\"|\/|\\|\||\?|\*', '', file/directory)) Explanation: \&lt;|\&gt;|\:|\"|\/|\\|\||\?|\* &lt;= matches alll of your undesired chars At this time you will have erased all of your undesired chars EXCEPT the spaces/dots at the end of the name. For yours file_name you can update its variable with file_name = re.sub(r'( +)$', '', file_name) ( +)$ &lt;= matches spaces or a dot at the end of the string. and you'll be done because there are no more restrictions besides that the name can't contain any spaces at its end (remember we already removed the special chars). For directories however, you can't have both periods and spaces. So the best way, my opinion of course, is to implement a recursive procedure, once that stops only when: dir_name == re.sub(r'( +|\.+)$', '', dir_name) and dir_name keeps being updated with dir_name = re.sub(r'( +|\.+)$', '', dir_name) while the above statement is false. Hope this helps you.
has comment: http://stackoverflow.com/comment/87761056
type: Answer
answers question: http://stackoverflow.com/q/49163663
has comment: http://stackoverflow.com/comment/85375642

http://stackoverflow.com/comment/85528323
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49262352
has text: "via python/JS", then why did you tag [tag:c#]? Also, nobody will do your job for free here. Please read [ask]

http://stackoverflow.com/comment/85294197
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49134593
has text: So even if you can save some time using the TfidfVectorizer patch from the question tagged by @Metropolis, you will still need to re-train your model with all the data due to increased number of columns.

http://stackoverflow.com/comment/85350706
type: AnswerComment
comment on: http://stackoverflow.com/a/49155494
score: 0
has text: Yes and Yes. Full information in the Saxon documentation at www.saxonica.com
type: Comment

http://stackoverflow.com/comment/85325132
type: QuestionComment
has text: what do you think `(resultmovies[counter])` should yield? what is the result if you substitute this piece of code for `item` or maybe `item[0]`?
comment on: http://stackoverflow.com/q/49139458
score: 0
type: Comment

http://stackoverflow.com/q/49207577
upvote count: 1
tagged with: python
has title: DataFrame to List format
tagged with: pandas
score: 1
has comment: http://stackoverflow.com/comment/85508357
has body: Im converting DataFrame into List using following code resultDataFrame = [] resultDataFrame = pd.DataFrame(resultDataFrame, columns=('day', 'hour', 'minute')) and appending values ... resultDataFrame.to_dict('l') {'day': [6], 'hour': [12], 'minute': [54]} But, I want to get it like {'day': 6, 'hour': 12, 'minute': 54} How to change the format?
answer count: 1
has answer: http://stackoverflow.com/a/49207590
favorite count: 0
type: Question
type: UnansweredQuestion
downvote count: 0

http://stackoverflow.com/q/49166071
favorite count: 0
type: Question
has title: How to extract noun adjective pairs from a sentence
has answer: http://stackoverflow.com/a/49166586
tagged with: nltk
upvote count: 5
score: 5
downvote count: 0
accepted answer: http://stackoverflow.com/a/49166586
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85337972
has body: I wish to extract noun-adjective pairs from this sentence. So, basically I want something like : (Mark,sincere) (John,sincere). from nltk import word_tokenize, pos_tag, ne_chunk sentence = "Mark and John are sincere employees at Google." print ne_chunk(pos_tag(word_tokenize(sentence)))
answer count: 1
linked to: http://stackoverflow.com/q/35030009
tagged with: python

http://stackoverflow.com/comment/85540892
has text: I'd also suggest you take a look at the default `Manager.get_or_create` Django provides, so you don't have to do the logic yourself inside the `try except` https://docs.djangoproject.com/en/2.0/ref/models/querysets/#get-or-create
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49268778

http://stackoverflow.com/comment/85345049
type: Comment
type: QuestionComment
has text: Already voted to close this question, but here is the dupe - https://stackoverflow.com/questions/15112125/how-do-i-test-multiple-variables-against-a-value
comment on: http://stackoverflow.com/q/49169824
score: 0

http://stackoverflow.com/comment/85272816
comment on: http://stackoverflow.com/q/49134079
type: QuestionComment
has text: Why do you think it fails? What does "not working" mean? What is it doing that is different than what you expect? Is it throwing an error? Is it returning the wrong data?
type: Comment
score: 0

http://stackoverflow.com/comment/85413614
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49203958
score: 0
has text: See https://en.wikipedia.org/wiki/64-bit_computing for an idea on n-bit origin. I remember reading some old Intel CPU datasheets that had 4-bit. Usually available CPU registers bit width, or width of memory addresses when specified by a register, or data bus widths...

http://stackoverflow.com/a/75623679
downvote count: 0
score: 1
type: Answer
has body: It looks like you ran into a Crome/chromedriver/selenium version incompatibility issue. Try using known-good combinations. See the chromedriver release notes for compatible versions here: chromedriver.storage.googleapis.com/2.35/notes.txt
upvote count: 1
answers question: http://stackoverflow.com/q/49129452

http://stackoverflow.com/q/49123814
has comment: http://stackoverflow.com/comment/85252787
linked to: http://stackoverflow.com/q/20625582
answer count: 0
type: UnansweredQuestion
tagged with: function
has title: How do you use .loc with .apply to modify data in pandas?
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85253000
tagged with: pandas
has body: I have a Dataframe, and one column is full of lists of words. I am using a function to remove all words that are not in a secondary list. When I use apply to trim my lists I get a warning telling me I should use .loc but I'm not sure how to use it properly with apply. here is my function def trimTo20(tweet): for check in reversed(tweet): if check not in over20Hash: tweet.remove(check) return(tweet) here is my call group20.sumText = group20.sumText.apply(trimTo20) and here is the warning. Anaconda3\lib\site-packages\pandas\core\generic.py:3110: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas- docs/stable/indexing.html#indexing-view-versus-copy self[name] = value and here is a slice of my Dataframe UserID sumText 3 1644 [#life, #contentmarketing, #ContentMarketing] 5 1737 [@SwiftOnSecurity, @erinscafe, @ComfortablySmug] 8 2391 [@, @MikeIsaac, @fmanjoo, @rtraister, @TheCut, @twitter] 10 2426 [@MikeIsaac, @GOP, @united, @facebook, @gruber] everything appears fine in my dataframe, should I be concerned that some data didn't copy over correctly? I've used apply a couple times this way and never gotten this warning.
has comment: http://stackoverflow.com/comment/85254062
tagged with: python
score: 1
tagged with: apply
favorite count: 0
type: Question

http://stackoverflow.com/q/49206732
tagged with: class
has body: I want to create a class, called NeuralNetworkClassifier, that sets up and fits a neural network classifier, and returns its predictions on some test data. To set up and fit the neural network, I'm using tensorflow's DNNClassifier class. My problem is that my fit method thus returns an object of type tensorflow.python.estimator.canned.dnn.DNNClassifier, and when I subsequently try to run my predict method on this DNNClassifier object, nothing happens. I think this is because I'm trying to run a NeuralNetworkClassifier method on an object that is not of this class? How can I solve this problem? Is there any way to keep using the DNNClassifier class within my own class? Here is the code: class NeuralNetworkClassifier(object): def __init__(self, batch_size, n_steps, n_hidden_units1, n_hidden_units2, n_classes): self.batch_size = batch_size self.n_steps = n_steps self.n_hidden_units1 = n_hidden_units1 self.n_hidden_units2 = n_hidden_units2 self.n_classes = n_classes def set_up_architecture(self, train_data_features, train_sentiments): # Convert the scarce scipy feature matrices to pandas dataframes train_df = pd.DataFrame(train_data_features.toarray()) # Convert column names from numbers to strings train_df.columns = train_df.columns.astype(str) # Create feature columns which describe how to use the input feat_cols = [] for key in train_df.keys(): feat_cols.append(tf.feature_column.numeric_column(key=key)) # Set up classifier with two hidden unit layers classifier = tf.estimator.DNNClassifier( feature_columns=feat_cols, hidden_units=[self.n_hidden_units1, self.n_hidden_units2], n_classes=self.n_classes) return train_df, classifier def shape_train_input(self, features, labels, batch_size): """An input function for training""" # Convert the input to a dataset dataset = tf.data.Dataset.from_tensor_slices((dict(features), labels)) # Shuffle, repeat, and batch the examples dataset = dataset.shuffle(1000).repeat().batch(self.batch_size) return dataset def fit(self, train_data…
has comment: http://stackoverflow.com/comment/85418468
tagged with: oop
answer count: 0
score: 0
has title: Python: using one class inside another
tagged with: tensorflow
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85419424
tagged with: python

http://stackoverflow.com/comment/85538631
score: 0
comment on: http://stackoverflow.com/q/49215833
type: Comment
type: QuestionComment
has text: @shuwnyuantee see the answer below

http://stackoverflow.com/comment/85402880
type: AnswerComment
comment on: http://stackoverflow.com/a/49184433
type: Comment
has text: Try it. From [Boto3 docs](https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.Table.put_item): `table.put_item( Item={ 'string': 'string'|123|Binary(b'bytes')|True|None|set(['string'])|set([123])|set([Binary(b'bytes')])|[]|{} }, ........`. It may and must be a number.
score: 0

http://stackoverflow.com/comment/85252375
type: QuestionComment
has text: https://www.geeksforgeeks.org/g-fact-43-logical-operators-on-string-in-python/ this may help you
comment on: http://stackoverflow.com/q/49123594
type: Comment
score: 0

http://stackoverflow.com/q/49135640
answer count: 0
tagged with: opengl
has comment: http://stackoverflow.com/comment/85306755
linked to: http://stackoverflow.com/q/42417987
type: Question
has comment: http://stackoverflow.com/comment/85301937
has title: Overpainting 2D graphics over QGLWidget in Python
has comment: http://stackoverflow.com/comment/85307092
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85282076
has comment: http://stackoverflow.com/comment/85278669
tagged with: qt
has body: def paintEvent(self, event): """ Paint scene and selected region""" super(self.__class__, self).paintGL() #Draw selected region if self.selectionMode: painter = QtGui.QPainter(self) painter.setRenderHint(QtGui.QPainter.Antialiasing, True) dxx = self.lastPos.x()-self.lastPosInit.x() dyy = self.lastPos.y()- self.lastPosInit.y() painter.drawRect(self.lastPosInit.x(), self.lastPosInit.y(), self.pose[0]+dxx, self.pose[1]+dyy) # Paint vertexes inside selected volume box #for vert in self.meshmodel.point_to_draw: # painter.drawEllipse(vert[0] - 5, vert[1] - 5, 10, 10) painter.end() where the parent class is painting OpenGL stuff. When I load the configure file everything is fine: My issue is after drawing the bounding box, the mesh colours change: Can anyone give help me?
score: 0

on-the-fly
type: Tag
tag name: on-the-fly
tags question: http://stackoverflow.com/q/49239036

http://stackoverflow.com/q/49175282
tagged with: setuptools
has body: I have forked a repo and now I have cloned it. When running the setup.py file inside, Python installs the package inside site-packages as an obscure name, that of which importing this within a Python file will not be viable. For example, I fork and clone a repo called foo. I can also see this in the setup.py file: setup( name='foo', version='3.3.0-rc6', packages=find_packages('src'), package_dir={'': 'src'}, include_package_data=True, When I run python setup.py install, I find the package has been installed as foo-3.3.0rc6-py3.6.egg. I do not want to have to import the package as this name in every one of my projects utilizing it. How can I just change the package name to foo (when running/installing via setup.py), so that I can run import foo and not import foo-3.3...? I feel I can not just rename it, as if I wanted other users to clone the repo and not have to go through the same trouble as me. Is the package name embedded somewhere in the setup.py folder? Let me know if you need anything else, I'm willing to have this issue resolved.
has title: Change package name when running setup.py
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85356441
possible better answer: http://stackoverflow.com/a/49175864
has answer: http://stackoverflow.com/a/49175864
downvote count: 0
tagged with: python
tagged with: git
accepted answer: http://stackoverflow.com/a/49175769
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/49175769
answer count: 2
tagged with: clone
upvote count: 3

http://stackoverflow.com/q/49128449
tagged with: python
tagged with: pypi
upvote count: 3
type: UnansweredQuestion
answer count: 1
downvote count: 0
tagged with: artifactory
tagged with: pip
favorite count: 0
has answer: http://stackoverflow.com/a/49255259
type: Question
score: 3
has title: Python package metadata endpoint not available in JFrog Artifactory PyPI repository
has body: I'm using JFrog Artifactory as an artifact store to keep private python modules. When our build server pushes a compiled python module to the Artifactory PyPI repository it makes a GET request to another endpoint (to validate that the module was pushed). I can see that the module was stored but the /json endpoint returns a 404 not found. When I try doing this on the public PyPI site I get a metadata document in JSON format. Is this a feature of PyPI which isn't supported by JFrog? Or is it a problem with my build artifacts? I already tried searching around but couldn't find much information about this. https://wiki.python.org/moin/PyPIJSON?action=show&amp;redirect=PyPiJson URL which works on PyPI: https://pypi.python.org/pypi/{{ packagename }}/json Example: https://pypi.python.org/pypi/requests/json URL which gives 404 on Artifactory: https://{{ myorg }}.jfrog.io/{{ myorg }}/api/pypi/{{ myteam }}/{{ packagename }}/json Thank you

http://stackoverflow.com/q/49137777
accepted answer: http://stackoverflow.com/a/49137865
has answer: http://stackoverflow.com/a/49137865
tagged with: numpy
type: AnsweredQuestion
score: 0
tagged with: pandas
answer count: 1
upvote count: 1
downvote count: 1
has body: Trying to create a query that returns either 3 or 2 or 1 Table ID Field1 Field2 1 J JLP10A 2 J JLP22A 3 S JLP25C I want if Field1=J AND the first 4 letters of Field2='JLP10' then return 3, else if Field1=J then return 2 else return 1. So ID 1 should return 3, ID 2 should return 2 and ID 3 should return 1. I have tried the following: Table=Table.assign(Field3=np.where(((Table.Field1=='J')&amp;(Table.Field2.astype(str).str[0:4].isin(['JLP10', 'JLP15']))),3, np.where(Table.Field1=='J'),2,1)))) This does not return 3 for ID1.. When I remove the [0:4] condition and make Field2 actually match I get 3 for ID1. Table=Table.assign(Field3=np.where(((Table.Field1=='J')&amp;(Table.Field2.isin(['JLP10A', 'JLP15']))),3, np.where(Table.Field1=='J'),2,1)))) So the code is not reading the 0:4 correctly.. any ideas why??
has title: pandas and numpy logic using 'isin' and 'str'
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/comment/85434155
type: Comment
has text: Did you search SO before asking the question? [what-is-the-difference-between-re-search-and-re-match](https://stackoverflow.com/questions/180986/what-is-the-difference-between-re-search-and-re-match/180993) or [python-regex-search-and-findall](https://stackoverflow.com/questions/8110059/python-regex-search-and-findall)? **Research first**, then ask.Please go over [how to ask](https://stackoverflow.com/help/how-to-ask) and read it. Both explain various `re`gex methods in detail.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49214894

http://stackoverflow.com/comment/85389221
comment on: http://stackoverflow.com/a/49177115
type: AnswerComment
has text: Then it's not an `iframe` :) Try couple more selectors: `(By.PARTIAL_LINK_TEXT, "BOOK THIS CLASS NOW")`, `(By.XPATH, "//div[.='ICE II - Zaf']/following::a")`, `(By.ID, "ctl00_cphContents_btnBook")`
score: 0
type: Comment

http://stackoverflow.com/q/49201897
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49201945
has answer: http://stackoverflow.com/a/49202242
has comment: http://stackoverflow.com/comment/85409033
tagged with: python
tagged with: dictionary
answer count: 4
has answer: http://stackoverflow.com/a/49201950
has body: I have a school dictionary as follow- { ID('6a15ce'): { 'count': 5, 'amount': 0, 'r_amount': None, 'sub': &lt; subobj &gt; }, ID('464ba1'): { 'count': 2, 'amount': 120, 'r_amount': None, 'sub': &lt; subobj2 &gt; } } I want to find out the sum of amount , doing as follow- {k:sum(v['amount']) for k,v in school.items()} but here I am getting error TypeError: 'int' object is not iterable what could be efficient way to achieve.
has comment: http://stackoverflow.com/comment/85409153
downvote count: 0
type: UnansweredQuestion
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49202346
has comment: http://stackoverflow.com/comment/85409171
has title: Sum of specific key-value in python dictionary
has comment: http://stackoverflow.com/comment/85666319

http://stackoverflow.com/comment/85484247
has text: _Also_, instead of linearly scanning the heap in `a_star_lowest_f_score`, you should instead use [`heapq`](https://docs.python.org/3/library/heapq.html) for O(logn) heap operations.
comment on: http://stackoverflow.com/q/49237582
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49272908
score: 0
has comment: http://stackoverflow.com/comment/85548557
has comment: http://stackoverflow.com/comment/85548706
has comment: http://stackoverflow.com/comment/85548685
has body: wordList is not instantiated as a list or not in scope. If wordList is a global variable, the beginning of your function will need global wordList Not needed because the object is mutated If the list should only be in scope of the function you will need to instantiate it as a list. wordList = [] Edit: as deceze pointed out Within the function itself you should be appending to the list since the index does not exists. wordList.append(word)
has comment: http://stackoverflow.com/comment/85548679
answers question: http://stackoverflow.com/q/49272861
has comment: http://stackoverflow.com/comment/85548455
has comment: http://stackoverflow.com/comment/85548817
type: Answer
has comment: http://stackoverflow.com/comment/85548833
has comment: http://stackoverflow.com/comment/85548613
has comment: http://stackoverflow.com/comment/85548778

http://stackoverflow.com/comment/85310440
type: QuestionComment
comment on: http://stackoverflow.com/q/49152607
type: Comment
has text: Just call transform()
score: 0

http://stackoverflow.com/comment/85372217
has text: Thanks @Mr.Rebot -- he columns actually contain "1" "2" etc. not "one" "two" and so on. But Google seems to be seeing the "1" "2" etc as text, not numbers, even if they're an int in python, hence my desire to format them as numbers.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49162648

http://stackoverflow.com/comment/85280988
type: AnswerComment
comment on: http://stackoverflow.com/a/49133289
has text: The method name is `ends_within_50_days`. This would mean that the entry will end at some point from today within the next 50 days. However the method checks if the entry ended within the last 50 days. Do you think that renaming the method would be beneficial for the code readabilty and maintainability?
type: Comment
score: 0

http://stackoverflow.com/comment/85251425
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49122977
has text: You can use the row series as a dictionary and unpack with a double splat.
type: Comment

http://stackoverflow.com/comment/85416869
type: Comment
score: 0
has text: Are you sure the numbers are always going to be sorted?
comment on: http://stackoverflow.com/q/49205881
type: QuestionComment

http://stackoverflow.com/q/49148632
type: Question
has body: One of my project requirement, I need to write script to fetch hardware info of esxi server remotely. If some has explored python module pywbem for esxi or some other module.
score: 0
has comment: http://stackoverflow.com/comment/85376133
type: UnansweredQuestion
answer count: 1
has title: Need to write script for ESXi for fetching hardware info
has answer: http://stackoverflow.com/a/49185272
tagged with: esxi
tagged with: python

http://stackoverflow.com/comment/85344753
comment on: http://stackoverflow.com/q/49169071
score: 1
type: Comment
type: QuestionComment
has text: Thanks! This simplified my code and I immediately noticed that I only lowered the word in the list once to print out at the top of the column, and I forgot to do the same for the comparison. Now it works! Python is great!

http://stackoverflow.com/a/49238100
answers question: http://stackoverflow.com/q/49238027
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/85479495
has body: You need to add $: re.match(r'[a-zA-Z0-9,. ]+$', word)
has comment: http://stackoverflow.com/comment/85479575
score: 5
accepted answer of: http://stackoverflow.com/q/49238027
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/q/49139772
type: Question
has comment: http://stackoverflow.com/comment/85285738
type: UnansweredQuestion
has body: Right now I have code in my script def run(self): while True: try: self.one() self.two() self.three() self.four() except (IndexError, ProxyError, SSLError, ConnectionError, errno.ECONNREFUSED): print statusTime(self.index) + 'Bad Proxy' break def jobWorker(username,password,proxy): bot = Bot(username,password,proxy) bot.start() bot.join() return How can I tell python to continuously run def run(self) so basically keep looping through self.one(), self.two(), self.three(), self.four() so it doesnt stop. Right now each Bot stops at self.four() and doesnt start again at self.one()
has comment: http://stackoverflow.com/comment/85285646
tagged with: python
has answer: http://stackoverflow.com/a/49139836
score: 0
has title: How to Loop in threaded script on Python
answer count: 1

http://stackoverflow.com/a/50012837
has body: Assuming your dataset is called df, and that you are performing the scaling for the (i)th column, it has to look something like this: df[list(df)[i]] = min_max_scaler.fit_transform(df[list(df) [i]].values.reshape(-1,1))
score: 0
answers question: http://stackoverflow.com/q/49275570
type: Answer

http://stackoverflow.com/q/49223825
has body: I have a numpy array 3d rgb image of size (500,500,3), a boolean mask array of size (500, 500), and an rgb color array of size (3,). I want to replace the pixels on my numpy array image where my mask array is True at that index and replace it with my color pixel.
score: 0
tagged with: python
tagged with: image
has comment: http://stackoverflow.com/comment/85451248
has comment: http://stackoverflow.com/comment/85451151
type: Question
has title: python: Adding numpy array and color with boolean array mask
tagged with: numpy
has comment: http://stackoverflow.com/comment/85451219
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85451212

http://stackoverflow.com/comment/85369135
comment on: http://stackoverflow.com/q/49181697
has text: Is this intended to work across any application?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49259015
answers question: http://stackoverflow.com/q/49256860
has body: Not exactly sure what you have asked for, assuming you want to return color and color list without the color selected. cnames = ['green', 'blue'...] to pick one color from list use random.choice color = random.choice(cnames) to get other colors init new list and pop by index other_colors = list(cnames) other_colors.pop(colors.index(color)) return selected color and others return color, other_colors in graphwin color, other_colors = randomize() ucolor = '{0}{1}'.format(color[0].upper(), color[1:]) target = Text(Point(300,100),ucolor) target.setOutline(color) ... Boxes = other_colors #
type: Answer
score: 0

http://stackoverflow.com/comment/85270396
has text: Yeah, the map function only returns a single example. So I cannot use that. Do you know what I mean? tf.data.TFRecordDataset(filenames) and then in the map function I only retrieve a single example to parse obs. @Maxim
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49132111

http://stackoverflow.com/comment/85505755
score: 0
type: AnswerComment
has text: yes, I don't know what the user wanted exactly, but there's a wrong magnitude order :)...
type: Comment
comment on: http://stackoverflow.com/a/49251203

http://stackoverflow.com/comment/85407794
type: Comment
comment on: http://stackoverflow.com/a/49201197
type: AnswerComment
has text: This should be `pipes.quote(VarFromFirstScript)` (or, in Python 3, `shlex.quote(...)`) to avoid security issues.
score: 1

http://stackoverflow.com/q/49248489
has answer: http://stackoverflow.com/a/49254109
type: Question
tagged with: python
accepted answer: http://stackoverflow.com/a/49376529
has title: Mysql Connector issue in Python
type: AnsweredQuestion
score: 0
answer count: 2
tagged with: centos7
possible better answer: http://stackoverflow.com/a/49254109
tagged with: pip
has body: I have installed MySQL connector for python 3.6 in centos 7 If I search for installed modules with below command it's showing as below pip3.6 freeze mysql-connector==2.1.6 mysql-connector-python==2.1.7 pymongo==3.6.1 pip3.6 search mysql-connector mysql-connector-python (8.0.6) -MYSQL driver written in Python INSTALLED: 2.1.7 LATEST: 8.0.6 mysql-connector (2.1.6) - MySQL driver written in Python INSTALLED: 2.1.6 (latest) MySQL connector installed.But when trying to run the program using MySQL connector then its showing error no module installed MySQL connector.I am using MariaDB 10.0 python3.6 mysql1.py Traceback (most recent call last): File "mysql1.py", line 2, in import mysql.connector as mariadb File "/root/Python_environment/my_Scripts/mysql.py", line 2, in import mysql.connector ModuleNotFoundError: No module named 'mysql.connector'; 'mysql' is not a package can any one know how to resolve
tagged with: mariadb
has answer: http://stackoverflow.com/a/49376529

http://stackoverflow.com/a/75890464
has body: Executemany() is slow because it's using the for loop and in that it's using the execute() function itself. the easiest way which i found it is to use the execute() command itself in range of 1000. for e.g i have data like this => data = [(1,"test1","123"),(2,"test2","543"),(3,"test3","876"),(4,"test4","098")] so you can insert in this way def bulk_batch_insertion(self,data,tablename): print("Data==============>",len(data)) start = 0 end = 1000 while data[start:end]: print("start ",start,'end ',end) new_data = ','.join(data[start:end]) print("length of new data =========>",len(data[start:end])) query = f"INSERT INTO {tablename} VALUES {new_data}" print("Insert QUERY ====> ",query) self.cursor.execute(query) self.conn.commit() print("Successfully Inserted the data ") start = end end = start + 1000 print("Execution successfulll=======endss=====>>") Note : I'm not using BULK insert because I have some encoding and some manipulations to be done before passing it into the database.
score: 0
answers question: http://stackoverflow.com/q/49270560
type: Answer

http://stackoverflow.com/comment/134417960
score: 0
type: Comment
type: AnswerComment
has text: but where's the log file located, @Jacobski ??
comment on: http://stackoverflow.com/a/49148927

http://stackoverflow.com/a/49264321
type: Answer
has body: Alright OP, figured this one out. Not exactly sure why this is the case, but it's because of what you named your file. Somehow naming your script dateutil.py and importing dateutil/pandas is causing a problem. I got the same error locally until I renamed it. Try renaming your file to something like myfile.py and your problem should be solved.
has comment: http://stackoverflow.com/comment/103181159
has comment: http://stackoverflow.com/comment/85532824
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49263369
has comment: http://stackoverflow.com/comment/85532590
upvote count: 9
score: 9
accepted answer of: http://stackoverflow.com/q/49263369

http://stackoverflow.com/q/49274426
has comment: http://stackoverflow.com/comment/85551345
type: Question
tagged with: numpy
has body: I want have dictionaries that contain numpy arrays of different sizes and dimensions as values. I want to dump and reload those dictionaries. The natural choice for this is of course pickle. Pickle performs this nicely. However, the dumped files are not human readable. The question is now: Is there an alternative to using pickle. Since I need some flexibility, I don't really want to do it myself... The data size is only a couple of MB, so performance is not so much of an issue. Edit to clarify: I dump into a .txt The files look like: (dp0 S'ind_SR1_DO' p1 (dp2 S'**MEASUREMENT NAME**' p3 (dp4 S'**MEASURED DATA 1**' p5 cnumpy.core.multiarray _reconstruct p6 (cnumpy ndarray p7 (I0 tp8 S'b' p9 tp10 Rp11 (I1 (I3 I13 tp12 cnumpy dtype p13 (S'f8' p14 I0 I1 tp15 Rp16 (I3 S'&lt;' p17 NNNI-1 I-1 I0 tp18 bI00 S'9.\x855\x05\x9aN&gt;\x89\xeb\xe4\x14x\rO&gt;!\x8bc\xd9\xe5IP&gt;\xf7\xd5\xb7\xc8\x97\xc5P&gt;\xf0\xaeo\xe7\xfc\xb1Q&gt;\xfb\xd3Y4\xfc\xeaS&gt;\x89S\x91\xee\x82\x15X&gt;g\x90(\x88|\xb3\\&gt;J\x88\xe7\xb0;\xa3`&gt;\x91\xebW\x0c\\\xecc&gt;S\xf5\xa9\xc4B\xb1S&gt;&gt;9($\xb8\x0eT&gt;&amp;\xa5\xaa72\x0e]&gt;GKi\xc1^\xa5\x1a&gt;\x12\x06\xd3s\x816\x1b&gt;,h\x9f?9\xef\x1b&gt;%\x8f\xadqT\xc2\x1c&gt;"F\t\t\xbf_\x1e&gt;\xb7u8[&lt;F!&gt;\xfe\x8aR\xa3\xa6\xa8$&gt;T5\xa6\xaa\x00\x9a(&gt;\xea\xf1"\x0c\x00$,&gt;\xdel&gt;\xe6\xe3\x8d2&gt;\x8am\xe7\xb4\xd76!&gt;^\xc9\xe9\xe7\x06Z!&gt; Which is not a human readable but of course can easily be handled by python/pickle
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85551920
has comment: http://stackoverflow.com/comment/85569800
tagged with: pickle
tagged with: python
has comment: http://stackoverflow.com/comment/85551357
has title: python: dump dictionary containin numpy arrays
has comment: http://stackoverflow.com/comment/85577337
has comment: http://stackoverflow.com/comment/85561694
score: 0
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85552379
has comment: http://stackoverflow.com/comment/85552370

http://stackoverflow.com/a/49233966
has comment: http://stackoverflow.com/comment/85471443
upvote count: 2
score: 2
downvote count: 0
type: Answer
has body: numpy syntax is convenient for this task: import numpy as np l = [[[1, 'a'], [2, 'b'], [3, 'c']], [[4, 'd'], [5, 'e'], [6, 'f']]] a = np.array(l) l1 = a[:, :, 0].astype(int).tolist() # [[1, 2, 3], [4, 5, 6]] l2 = a[:, :, 1].tolist() # [['a', 'b', 'c'], ['d', 'e', 'f']]
answers question: http://stackoverflow.com/q/49233880

http://stackoverflow.com/q/49156225
has answer: http://stackoverflow.com/a/49156900
accepted answer: http://stackoverflow.com/a/49156900
has title: Scrapy to dataframe to csv?
tagged with: dataframe
tagged with: python
score: -1
type: AnsweredQuestion
downvote count: 2
tagged with: pandas
upvote count: 1
answer count: 1
tagged with: scrapy
favorite count: 0
type: Question
has body: I have a scrapy code here that outputs a json file. I then imported the json file into a dataframe using jupyter notebook to clean the data. However, what I really want to do is be able to run the scrapy spider and output the data as a CSV already cleaned, instead of me saving the scraped data as a json file and going into jupyter notebook to clean it. Is there anyway to connect the two process? Below is my spider code: import scrapy import pandas as pd import json import datetime from seatgeek.items import SeatgeekItem class seatgeekSpider(scrapy.Spider): name = "seatgeek_spider" #showname = input("Enter Show name (lower case please): ") #showname = showname.replace(' ', '-') start_urls = ["https://seatgeek.com/come-from-away-tickets?page={}".format(i) for i in range (1,35)] custom_settings = { 'DOWNLOAD_DELAY': 3, 'CONCURRENT_REQUESTS_PER_DOMAIN': 3, 'HTTPCACHE_ENABLED': True, 'FEED_FORMAT': 'json', 'FEED_URI': 'test.json' } def parse(self, response): for href in response.xpath('//a[@class="event-listing-title"]/@href').extract(): item = SeatgeekItem() item['performance'] = href.split('/')[-3] item["eventId"] = href.split('/')[-1] yield scrapy.Request( url = 'https://seatgeek.com/listings?id=' + item['eventId'] + '&amp;aid=11955&amp;client_id=MTY2MnwxMzgzMzIwMTU4', callback=self.parse_ticketinv, meta={'item': item}) def parse_ticketinv(self, response): jsonresponse = json.loads(response.body_as_unicode()) item = response.meta['item'] for i in jsonresponse["listings"]: item["sectionName"] = i["s"] item["zoneName"] = i["s"].split(' ')[0] item["currentPrice"] = i["p"] item["listingPrice"] = i["p"] item["row"] = i["r"] item["seatNumbers"] = "" item['listingId'] = i["id"] item['quantity'] = i["q"] item['vendor'] = "SeatGeek" yield item And this is my code for cleaning the data: import json import pandas as pd import datetime path = r'C:\Users\...\Desktop\Code\seatgeek\test.json' with open(path) as f: data = json.load(f) df = pd.DataFrame(data) df = df[df.performance.st…

http://stackoverflow.com/q/49278571
has comment: http://stackoverflow.com/comment/85561874
has comment: http://stackoverflow.com/comment/85562131
has title: Python, Machine Learning: Are there any API that can split dataset and shuffle?
has comment: http://stackoverflow.com/comment/85561040
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/49278620
has comment: http://stackoverflow.com/comment/85567745
score: -2
linked to: http://stackoverflow.com/q/41859605
has comment: http://stackoverflow.com/comment/85559661
answer count: 2
has body: I have a dataset with 10000 samples, and 4 classes (0, 1, 2, 3) label. &gt;&gt;&gt;data.shape (10000, 250) &gt;&gt;&gt;label.shape (10000,) and, I wonder are there any API that could split the data into training and test data and shuffle? for example: (training_data, training_label, test_data, test_label) = split_shuffle(data, label, 80) # 80 means 80% training, 20% test What is the most efficient way to achieve such functions? Further, what if we want 5-fold (straight) cross validation data?
tagged with: deep-learning
has comment: http://stackoverflow.com/comment/85562041
has comment: http://stackoverflow.com/comment/85560587
downvote count: 3
tagged with: machine-learning
upvote count: 1
has comment: http://stackoverflow.com/comment/85563808
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/49278671

http://stackoverflow.com/comment/85453150
type: QuestionComment
score: 1
has text: @nicht the second link _is_ python 3
comment on: http://stackoverflow.com/q/49221309
type: Comment

http://stackoverflow.com/comment/85443705
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49219602
score: 0
has text: My bad, sorry on my part. I will rephrase my question which function should be used **model.to_json** or **model.save** i.e. which format is better **.h5** or **.json** in terms of space.

http://stackoverflow.com/comment/85543361
type: QuestionComment
comment on: http://stackoverflow.com/q/49269997
has text: Any attempts so far?
score: 0
type: Comment

http://stackoverflow.com/a/49142919
type: Answer
has body: You could loop through each file, grabbing the index of each and creating a set union of all indices. import glob tickers = set() for csvfile in glob.glob('*.csv'): data = pd.read_csv(csvfile, index_col=0, header=None) # or True, however your data is set up tickers.update(data.index.tolist()) pd.Series(list(tickers)).to_csv('index.csv', index=False)
score: 1
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49142826

http://stackoverflow.com/q/49233547
has body: I am using this command to convert .las to .pcd format pdal translate input.las output.pcd. But I am getting error while using this command PDAL: Couldn't create writer stage of type 'writers.pcd'. Please help me in solving this issue. Thanks in advance
tagged with: python
has comment: http://stackoverflow.com/comment/90844336
has answer: http://stackoverflow.com/a/66383652
score: 0
answer count: 1
type: Question
has comment: http://stackoverflow.com/comment/91214501
has title: How to convert .las file to .pcd file using PDAL package in Python
type: UnansweredQuestion

http://stackoverflow.com/comment/85523186
comment on: http://stackoverflow.com/q/49254129
score: 0
has text: Yes I know that, I already tried that and [had lots of issue](https://stackoverflow.com/questions/49130879/setting-up-ntlk-proxy) as stated in the question? I will be happy if you resolve that too.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49223760
has answer: http://stackoverflow.com/a/49223912
tagged with: nginx
tagged with: python
score: 2
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85451182
downvote count: 0
accepted answer: http://stackoverflow.com/a/49223912
tagged with: api
answer count: 1
tagged with: centos7
has title: Make a python script API
has body: I have a script on python, which prints some data. The script is on Centos7, nginx. How could I connect to the script via URL (GET query) to be able to parse the data?
favorite count: 0
type: Question

http://stackoverflow.com/comment/85304866
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49150073
has text: Thank you for your answer! I have access to a GPU server.

wrapper
tag name: wrapper
tags question: http://stackoverflow.com/q/49155266
tags question: http://stackoverflow.com/q/49177260
type: Tag
tags question: http://stackoverflow.com/q/49266792
tags question: http://stackoverflow.com/q/49256000
tags question: http://stackoverflow.com/q/49216412

http://stackoverflow.com/q/49122044
has comment: http://stackoverflow.com/comment/85268572
type: UnansweredQuestion
downvote count: 0
answer count: 1
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85250593
tagged with: centos
has body: I am trying to run python program in shell, CentOS 7.0 x64, on VPS python3 version is 3.6.4 pip3 version is 9.0.1 when I use pip3 freeze it has tensorflow==1.6.0 The first line of xx.py is import tensorflow whether I use python3 xx.py or type import tensorflow in python3 shell, it turns out to be Illegal instruction Besides, any other import like import numpy, import sklearn function well, nothing wrong with them How to solve this?
tagged with: linux
has title: Illegal instruction when import tensorflow in Python
has comment: http://stackoverflow.com/comment/85267528
score: 1
has comment: http://stackoverflow.com/comment/85262742
has answer: http://stackoverflow.com/a/50551880
has comment: http://stackoverflow.com/comment/85269918
tagged with: tensorflow
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85250195

http://stackoverflow.com/comment/85252261
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49123158
has text: @cricket_007 this is what is at the head of my code and the .rvs did not work for me
score: 0

http://stackoverflow.com/comment/85454535
type: Comment
comment on: http://stackoverflow.com/q/49225393
type: QuestionComment
has text: Right, so maybe you should start by *actually creating a list?* See e.g. https://docs.python.org/3/tutorial/introduction.html#lists, https://docs.python.org/3/tutorial/datastructures.html#more-on-lists. Once you have the list, look at e.g. https://docs.python.org/3/howto/sorting.html for information on ordering the results.
score: 1

http://stackoverflow.com/comment/85456838
comment on: http://stackoverflow.com/q/49226421
type: Comment
type: QuestionComment
score: 0
has text: If you check the time of my publication and of my edition you will see that I first comment, and after a while I edit it.

http://stackoverflow.com/q/49142362
tagged with: python
has answer: http://stackoverflow.com/a/49142434
has answer: http://stackoverflow.com/a/49142459
tagged with: class
score: 2
has comment: http://stackoverflow.com/comment/85290438
type: AnsweredQuestion
tagged with: oop
answer count: 3
has answer: http://stackoverflow.com/a/49142495
has body: from math import pi class Circle(object): 'Circle(x,y,r)' def __init__(self, x=0, y=0, r=1): self._r = r self._x = x self._y = y def __repr__(self): return 'Circle({},{},{})'.\ format(self.getx(), self.gety(),\ self.getr()) #silly, but has a point: str can be different from repr def __str__(self): return 'hello world' def __contains__(self, item): 'point in circle' px, py = item return (self.getx() - px)**2 + \ (self.gety() - py)**2 &lt; self.getr()**2 def getr(self): 'radius' return self._r def getx(self): 'x' self._lst.append(self._x) return self._x def gety(self): 'y' self._lst.append(self._y) return self._y def setr(self,r): 'set r' self._r = r def setx(self,x): 'set x' self._x = x def sety(self,y): 'set y' self._y = y def move(self,x,y): self._x += x self._y += y def concentric(self, d): d = self._list def area(self): 'area of circle' return (self.getr())**2*pi def circumference(self): 'circumference of circle' return 2*self.getr()*pi My question is worded kinda awkwardly but what I am trying to do is check if 2 different circles have the same center (x,y). I think the easiest way to solve this would be to input the 2 points into a list but I am not sure how to compare the 2 lists as every time i try my code it adds everything to the same list
possible better answer: http://stackoverflow.com/a/49142434
accepted answer: http://stackoverflow.com/a/49142459
favorite count: 0
type: Question
tagged with: python-3.x
upvote count: 2
has title: How to check if one list is equal to another list created using a class?
downvote count: 0

http://stackoverflow.com/a/49196240
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85399955
has comment: http://stackoverflow.com/comment/85403681
has comment: http://stackoverflow.com/comment/85398648
has comment: http://stackoverflow.com/comment/85398702
has body: As body = soup.find('div', attrs={'id':'newsarticle'}), the body variable contains the following HTML: ... ... ... ... ... That means, the direct descendants of the tag are only the tags. Using body.div means the code tries to find a div tag which is a direct descendant of the current div tag. Since there is no such tag present, body.div evaluates to None. Because of this, body.div.unwrap() evaluates to None.unwrap() which as you can see will throw the error AttributeError: 'NoneType' object has no attribute 'unwrap'. If you want to remove the div tag, simply use this: body = soup.find('div', attrs={'id':'newsarticle'}) body.unwrap() or soup.find('div', attrs={'id':'newsarticle'}).unwrap()
has comment: http://stackoverflow.com/comment/85399569
answers question: http://stackoverflow.com/q/49195819
has comment: http://stackoverflow.com/comment/85398689

http://stackoverflow.com/comment/132227466
type: Comment
score: 0
has text: Bless you my friend
type: AnswerComment
comment on: http://stackoverflow.com/a/57758023

http://stackoverflow.com/a/49169828
has body: As stated in the REAMDE JayDeBeApi implements Python DB-API v2.0. Basically you have to call the execute on a cursor and pass the insert statement. But you are right. Some more guidance for novices would be nice. Mybe the Python Wiki or the docs for the sqlite implementation give you some guidance. Adapting one rather basic sqlite example: import jaydebeapi conn = jaydebeapi.connect(...) curs = conn.cursor() curs.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)") ##changes c to curs conn.commit() conn.close()
accepted answer of: http://stackoverflow.com/q/49147702
type: AcceptedAnswer
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/107292868
answers question: http://stackoverflow.com/q/49147702

http://stackoverflow.com/comment/127458398
has text: Does the failing Mac have an M1 processor?
comment on: http://stackoverflow.com/q/49200832
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85494143
type: Comment
type: QuestionComment
has text: Lock doesn’t lock every file, stream, etc. in the universe and force them all to flush their buffers. That would be terrible.
comment on: http://stackoverflow.com/q/49241429
score: 0

http://stackoverflow.com/comment/85489362
type: Comment
comment on: http://stackoverflow.com/a/49225167
has text: I updated the code...this is what I use and the numbers are still the old ones (e.g. Appearances 230)
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85322867
type: Comment
has text: Doing some digging through the Pupil Labs docs, here is an important section: https://docs.pupil-labs.com/#ffmpeg-to-pupil-external
comment on: http://stackoverflow.com/a/49158534
type: AnswerComment
score: 0

http://stackoverflow.com/q/49277103
tagged with: python
type: AnsweredQuestion
downvote count: 0
upvote count: 1
score: 1
answer count: 1
favorite count: 0
has title: error in installing the python packages in caffe installing
type: Question
has answer: http://stackoverflow.com/a/49293173
accepted answer: http://stackoverflow.com/a/49293173
has body: Im installing caffe using this instructers (link) and refer to this i use this command for install all of requirments: sudo pip install -r $CAFFE_ROOT/python/requirements.txt but, unfortuantly i got this error: Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build- jseAuV/leveldb/setup.py';f=getattr(tokenize, 'open', open) (__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install -- record /tmp/pip-brJMTP-record/install-record.txt --single-version-externally- managed --compile" failed with error code 1 in /tmp/pip-build- jseAuV/leveldb/ Im searched for solving this problem , somone said this error will solve by this command: pip install --upgrade setuptools and other commands related to upgrade setuptools ... . can , anyone help me? I use Jetson TX2 GPU.
tagged with: gpu
tagged with: caffe

http://stackoverflow.com/q/49151850
type: AnsweredQuestion
score: 0
tagged with: pytest
has body: I am testing 389 Directory server testing with lib389. I am following the bellow link. https://fedorapeople.org/~spichugi/html/guidelines.html#add-modify-and-delete-operations from lib389._constants import * # Add an entry USER_DN = 'cn=mreynolds,{}'.format(DEFAULT_SUFFIX) standalone.add_s(Entry((USER_DN, { 'objectclass': (b'top', b'person'), 'cn': b'mreynolds', 'sn': b'reynolds', 'userpassword': b'password' }))) # Modify an entry standalone.modify_s(USER_DN, [(ldap.MOD_REPLACE, 'cn', b'Mark Reynolds')]) # Delete an entry standalone.delete_s(USER_DN) What is the meaning of "standalone" here?
answer count: 1
accepted answer: http://stackoverflow.com/a/49158439
type: Question
has answer: http://stackoverflow.com/a/49158439
tagged with: linux
has title: 389 Directory server testing with lib389
tagged with: openldap
tagged with: python

http://stackoverflow.com/comment/85412352
has text: Have you tried if `polyfit` is working better than `legfit`? Do you have to use the Legendre polynomials? Or just fit the data?
type: QuestionComment
comment on: http://stackoverflow.com/q/49201515
type: Comment
score: 0

timeout
tags question: http://stackoverflow.com/q/49259055
tags question: http://stackoverflow.com/q/49203706
type: Tag
tag name: timeout
tags question: http://stackoverflow.com/q/49246800

http://stackoverflow.com/q/49180213
tagged with: formalchemy
type: Question
has body: I have recently updated FormAlchemy to the newest version 1.5.3. Up to now my select tags were created like this: helpers.select(self.name, value, variants, class_="form-control") where variants is a list e.g.: ['created', 'edited', 'published', 'rejected', 'unpublished'] and were working fine. After the update all my selects contains only first two options with reversed order. The source code of helpers.py (https://github.com/FormAlchemy/formalchemy/blob/master/formalchemy/helpers.py) shows in the line 185 it is a correct behaviour (at least according to the code I can see there). But why? What should I do to display all my options again?
type: UnansweredQuestion
tagged with: python
score: 0
has title: Python FormAlchemy helpers select tag
answer count: 1
has answer: http://stackoverflow.com/a/49189793

http://stackoverflow.com/a/49190723
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/85390263
has comment: http://stackoverflow.com/comment/85388905
has body: The long running times you're experiencing are quite likely to result from memory being paged out to your hard drive in order to make room for the addition of new items to mac_list. I can't think of any good reason why you would need to store all these MACs in memory. They're numbered consecutively, so you can easily generate them on the fly: gen_mac = lambda n: ":".join([("%012X" % n)[i:i+2] for i in range(0,12,2)]) Then instead of fetching items from mac_list, just use this function instead. In other words, replace m = mac_list[12345678] with m = gen_mac(12345678)
has comment: http://stackoverflow.com/comment/85390869
has comment: http://stackoverflow.com/comment/85395009
has comment: http://stackoverflow.com/comment/85388400
upvote count: 5
type: Answer
has comment: http://stackoverflow.com/comment/85394782
answers question: http://stackoverflow.com/q/49190186

http://stackoverflow.com/comment/85388451
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49190912
type: AnswerComment
has text: the reason for 100 million mac is: i am trying to simulate the mac-table(i.e. in networks it stores all the mac address of the received packets during learning time). so once the mac table(in our case list/other data structure like hash) populated then whenever new packet comes with this already learned mac address then lookup happens and returns the index from this list/hash. so that is the reason i am trying to populate my list(in future hash) with 100 million mac. so in future if i learn packet with this mac address then i will do lookup and return index. that is the whole idea

http://stackoverflow.com/q/49237498
accepted answer: http://stackoverflow.com/a/49559584
type: AnsweredQuestion
score: 0
has answer: http://stackoverflow.com/a/49559584
has title: Event mouse click in visual python
has comment: http://stackoverflow.com/comment/85478528
has comment: http://stackoverflow.com/comment/85478403
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85478576
has comment: http://stackoverflow.com/comment/85478453
type: Question
tagged with: python-3.x
tagged with: vpython
has body: This is a simple code from "vpython.org" tutorial: from vpython import * scene = canvas(title='Rubic solver!', width=800, height=600, center=vector(5,0,0), background=color.white,userzoom=0,userspin=0,userpan=0) box() while True: ev = scene.waitfor('mousedown mouseup') print(ev) if ev.event == 'mousedown': print('You pressed the mouse button') else: print('You released the mouse button') print(ev.pos) # the position of the mouse and when I print "ev" the output is None and then there is an error: if ev.event == 'mousedown': AttributeError: 'NoneType' object has no attribute 'event' note: I'm using Vpython7 and Python3.6 .
has comment: http://stackoverflow.com/comment/85478379
tagged with: python-3.6

http://stackoverflow.com/a/49263628
type: Answer
answers question: http://stackoverflow.com/q/49263524
has body: Assuming pointtable is a dict like {'e': 1, 'q': 8, ...}, then you want to use items from word as the index into pointtable. def scrabble_word_score(pointtable, word): score = 0 for letter in word: score += pointtable[letter] return score Using more descriptive variable names can help you notice expressions that don't make sense.
downvote count: 0
upvote count: 1
score: 1

http://stackoverflow.com/comment/86391014
type: Comment
has text: Updating drivers with which method exactly? .run file or .deb package?
type: AnswerComment
comment on: http://stackoverflow.com/a/49132865
score: 0

http://stackoverflow.com/q/49235731
type: AnsweredQuestion
score: 0
has title: Kivy GUI - fill color in circle like water fill in circle container level wise
has body: As shown in the image above I need to code a .kv file in the Kivy GUI so I can show a circle filling with color as a value increase. For 0 value it is empty as value increase circle is fill with color. How can I do that?
answer count: 1
upvote count: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49240983
has answer: http://stackoverflow.com/a/49240983
tagged with: python
tagged with: kivy

http://stackoverflow.com/q/49153585
has comment: http://stackoverflow.com/comment/85312600
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/json
tagged with: python
has answer: http://stackoverflow.com/a/49153879
answer count: 2
score: 0
has title: Python ValueError: No JSON object could be decoded when accessing requests.get(apiUrl).json()
has answer: http://stackoverflow.com/a/49153890
has body: I am working on a tiny script which loads JSON data from several different URLs. Most of the requests work well using requests.get(apiUrl).json() but one endpoint connection causes ValueError: No JSON object could be decoded. The thing is that I can view proper (?) JSON response in the web browser - Firefox recognizes it and show it using nice JSON formatting. I can also view the content using requests.get(apiUrl).text but I'd rather have it in JSON to quick process it using list of dicts. Do I have to validate the response to check if it really is JSON? Do not know how to approach this issue.. Response in Firefox Firefox Response Headers try: r = requests.get(apiUrl) if r.status_code == 200: try: json_data = r.json() except ValueError as value_exc: print("Request to {} failed: {}".format(apiUrl, value_exc)) print("Returned raw content: {}".format(r.text.encode('utf8'))) print("Headers: {}".format(r.headers)) The response I get is: Returned raw content: ï»¿[{"Id":1003616882932,"Sum":547.0,"Average":547.0,"WeightedNumerator":547.0,"Weight":1.0,"Cumulative":547.0,"Incremental":547.0,"EffectiveDate":"2016-03-31T00:00:00","Year":"2016-01-01T00:00:00","Quarter":"2016-01-01T00:00:00","Month":"2016-03-01T00:00:00","IsTarget":false,"IndicatorID":75879,"AwardID":39421,"ReportingPeriodID":6793,"LocationID":null,"AdminDivisionID":152472,"Level0AdminDivisionID":152337,"Level1AdminDivisionID":152472,"Level2AdminDivisionID":null,"Level3AdminDivisionID":null,"Level4AdminDivisionID":null,"OrganizationID":28058,"AwardingOrganizationID":28054,"AttributeValues":[]},{"Id":1003616882947,"Sum":889.0,"Average":889.0,"WeightedNumerator":889.0,"Weight":1.0,"Cumulative":1436.0,"Incremental":889.0,"EffectiveDate":"2016-09-30T00:00:00","Year":"2016-01-01T00:00:00","Quarter":"2016-07-01T00:00:00","Month":"2016-09-01T00:00:00","IsTarget":false,"IndicatorID":75879,"AwardID":39421,"ReportingPeriodID":6795,"LocationID":null,"AdminDivisionID":152472,"Level0AdminDivisionID":152337,"Level1AdminDivisio…
has comment: http://stackoverflow.com/comment/85311889
type: Question

http://stackoverflow.com/comment/85461545
has text: The first line in the output "scrapy shell data-blogger.com" also doesn't work. it also gives the same error. Which probably means that scrapy shell isn't getting start.
type: AnswerComment
comment on: http://stackoverflow.com/a/49189790
score: 0
type: Comment

http://stackoverflow.com/comment/85291059
has text: @MohideenibnMohammed That was the question, yes. Any forms of "hello" in the text with a character (could be a space or nothing) in between.
type: QuestionComment
comment on: http://stackoverflow.com/q/49123636
type: Comment
score: 0

http://stackoverflow.com/comment/85259804
comment on: http://stackoverflow.com/a/49126067
score: 0
type: AnswerComment
has text: Nothing has changed. When I print out args on the website, there is still no "dept" or "course_num" values and there are no results returned (since args is incorrect).
type: Comment

http://stackoverflow.com/comment/85257158
has text: Its gives the "MultiValueDictKeyError"
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49125996
score: 0

http://stackoverflow.com/comment/85258044
comment on: http://stackoverflow.com/q/49125517
score: 0
has text: It sounds like a logic error in your code structure. Do you have a `if __name__ == '__main__':` trap in your code (see the `multiprocessing` doc.)?
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49233487
has comment: http://stackoverflow.com/comment/125491809
upvote count: 2
score: 2
downvote count: 0
has body: I just needed to get the values (numpy array) from the data frame, so the column names won't be considered. df.eq(df_equal.values).all().all() I would still like to see a parameter on equals, or assert_frame_equal. Maybe I am missing something. An advantage of this compared to @jpp answer is that, I can get see which columns do not match, calling only all() only once: df.eq(df_diff.values).all() Out[24]: A True B False dtype: bool One problem is that when eq is used, then np.nan is not equal to np.nan, in which case the following expression, would serve well: (df.eq(df_equal.values) | (df.isnull().values &amp; df_equal.isnull().values)).all().all()
type: Answer
answers question: http://stackoverflow.com/q/49233359

http://stackoverflow.com/comment/85354951
comment on: http://stackoverflow.com/q/49174910
type: Comment
score: 0
type: QuestionComment
has text: We won't write it for you, there are other sites for that.

pycharm
tags question: http://stackoverflow.com/q/49217482
tags question: http://stackoverflow.com/q/49121561
tags question: http://stackoverflow.com/q/49176041
tags question: http://stackoverflow.com/q/49139668
tags question: http://stackoverflow.com/q/49154429
tags question: http://stackoverflow.com/q/49187483
tags question: http://stackoverflow.com/q/49122916
tags question: http://stackoverflow.com/q/49153985
tags question: http://stackoverflow.com/q/49146678
tags question: http://stackoverflow.com/q/49217448
tags question: http://stackoverflow.com/q/49143626
tags question: http://stackoverflow.com/q/49260833
tags question: http://stackoverflow.com/q/49251379
tag name: pycharm
tags question: http://stackoverflow.com/q/49258284
tags question: http://stackoverflow.com/q/49231762
tags question: http://stackoverflow.com/q/49143803
tags question: http://stackoverflow.com/q/49184502
type: Tag
tags question: http://stackoverflow.com/q/49262132
tags question: http://stackoverflow.com/q/49201203
tags question: http://stackoverflow.com/q/49157831
tags question: http://stackoverflow.com/q/49186263
tags question: http://stackoverflow.com/q/49255742
tags question: http://stackoverflow.com/q/49142748
tags question: http://stackoverflow.com/q/49175604
tags question: http://stackoverflow.com/q/49242531

user-interface
tags question: http://stackoverflow.com/q/49200621
tags question: http://stackoverflow.com/q/49240453
tags question: http://stackoverflow.com/q/49163895
tags question: http://stackoverflow.com/q/49210436
tags question: http://stackoverflow.com/q/49175245
tags question: http://stackoverflow.com/q/49121492
tags question: http://stackoverflow.com/q/49210523
tags question: http://stackoverflow.com/q/49165220
tags question: http://stackoverflow.com/q/49277758
type: Tag
tags question: http://stackoverflow.com/q/49173468
tags question: http://stackoverflow.com/q/49198728
tag name: user-interface
tags question: http://stackoverflow.com/q/49241739
tags question: http://stackoverflow.com/q/49155875
tags question: http://stackoverflow.com/q/49213178
tags question: http://stackoverflow.com/q/49267706

http://stackoverflow.com/comment/85279865
has text: As you can see the graph consrtuction's time (with DB access) is around 100 times slower than the search itself.: graph construction time: 0.26601505279541016 shortest_paths_dijkstra time: 0.0030002593994140625 get_shortest_paths time: 0.002000093460083008
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49131451

http://stackoverflow.com/q/49225456
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/90582296
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85536938
has comment: http://stackoverflow.com/comment/85489299
tagged with: discord.py
downvote count: 4
has comment: http://stackoverflow.com/comment/85457373
upvote count: 0
type: UnansweredQuestion
score: -4
has answer: http://stackoverflow.com/a/49289618
has comment: http://stackoverflow.com/comment/85492689
tagged with: python
has comment: http://stackoverflow.com/comment/85491168
has comment: http://stackoverflow.com/comment/85491109
has comment: http://stackoverflow.com/comment/85568922
has comment: http://stackoverflow.com/comment/89435729
has comment: http://stackoverflow.com/comment/90811637
has body: I have this idea on my Discord Server which would allows people to do ?playtime [TheirID] and it would display their playtime as a reply by my BOT(I am talking about their Unturned Server Playtime, which is explained below:) Everyone's Unturned Server Playtime is stored in a Google Sheets table (It is also stored in a MySQL database), so is there a way to allow them to do ?Playtime and then their ID, it searches their ID, finds the row they are in and then embeds the whole row into a reply by the bot? Any help will be appreciated, if you are confused please ask me more questions.
has comment: http://stackoverflow.com/comment/85488836
linked to: http://stackoverflow.com/q/12661999
has title: Is there a way to call from Google Sheets (Or MySQL) with Discord.py?
has comment: http://stackoverflow.com/comment/90842393
tagged with: mysql-python
has comment: http://stackoverflow.com/comment/90980548
answer count: 1
has comment: http://stackoverflow.com/comment/85568147
tagged with: discord
has comment: http://stackoverflow.com/comment/85568066
has comment: http://stackoverflow.com/comment/85536635

http://stackoverflow.com/q/49268374
tagged with: python
has comment: http://stackoverflow.com/comment/85541399
has comment: http://stackoverflow.com/comment/85541938
score: 2
has comment: http://stackoverflow.com/comment/85541355
answer count: 0
upvote count: 2
downvote count: 0
tagged with: amazon-web-services
has comment: http://stackoverflow.com/comment/85541643
tagged with: aws-lambda
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85590644
has title: How can I handle POST requests in a Lambda function using Python?
type: UnansweredQuestion
has body: I'm trying to change a bit of Python code at the moment that is being used as a Lambda function. Currently, the code in question takes a number of parameters that are URLs, and uses the urllib2 library to get the images at those URLs (for example, a URL could be: https://www.sundanceresort.com/wp-content/uploads/2016/08/nature-walk-1600x1400-c-center.jpg). I'd like to change this so that the code will handle a POST request that has the image in its body. Looking at some tutorials I thought Flask request might do the trick but I’m confused as to how it would work in this particular case. At the moment, the relevant code that would be replaced is in three sections: urls = urls_str.split(",") results = [] for url in urls: headers = {"User-Agent": "Mozilla/5.0"} try: req = urllib2.Request(url, None, headers) image = urllib2.urlopen(req).read() ... def get_param_from_url(event, param_name): params = event['queryStringParameters'] return params[param_name] ... def predict(event, context): try: param = get_param_from_url(event, 'url') result = model.predict(param) The overall code is here. Any help or suggestions would be greatly appreciated.

http://stackoverflow.com/q/49155875
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49156959
answer count: 2
has body: I am trying to have a Tkinter gui with 4 boxes that will let me add users to Centos7. If it was a dialog using raw input it works fine but when i try to get the input from the entry fields it doesnt. I saw other related subprocess questions but none of them used Entry frields which confuse me. I get an error of argument is not iterable but i am sure maybe the way i declare the variables is probably wrong and the way i input into the subprocess entry the oucu,name,group fields. Any ideas ? from tkinter import * import subprocess global oucu global fname global sname global group def add(): subprocess.call(['adduser', '-N', '-g', group, '-c', fname, '-d','/home/oucu']) root = Tk() oucu = StringVar() e2 = Entry(root, textvariable=oucu).grid(row=0, column=0) fname = StringVar() e3 = Entry(root, textvariable=fname).grid(row=1, column=0) sname = StringVar() e4 = Entry(root, textvariable=sname).grid(row=1, column=1) group = StringVar() e6 = Entry(root, textvariable=group).grid(row=0, column=1) b1 = Button(root, text='Next', command=add).grid(row=2, column=1) root.mainloop()
tagged with: subprocess
has answer: http://stackoverflow.com/a/49156959
has comment: http://stackoverflow.com/comment/85316496
tagged with: user-interface
has title: Tkinter Entry values to Subprocess
has comment: http://stackoverflow.com/comment/85316337
downvote count: 1
favorite count: 0
score: -1
type: Question
has comment: http://stackoverflow.com/comment/85316559
has comment: http://stackoverflow.com/comment/85316665
tagged with: tkinter
accepted answer: http://stackoverflow.com/a/49156032
has comment: http://stackoverflow.com/comment/85316553
linked to: http://stackoverflow.com/q/47334885
upvote count: 0
has answer: http://stackoverflow.com/a/49156032
has comment: http://stackoverflow.com/comment/85316932

http://stackoverflow.com/a/49211438
has body: Both your Company._registry and the names k and b are just references to your actual instances. Neither play any role in what you'd store in the database. Python's object model has all objects living on a big heap, and your code interacts with the objects via such references. You can make as many references as you like, and objects automatically are deleted when there are no references left. See the excellent Facts and myths about Python names and values article by Ned Batchelder. You need to decide, for yourself, if the Company._registry structure needs to have names or not. Iteration over a list is slow if you already have a name for a company you wanted to access, but a dictionary gives you instant access. If you are going to use an ORM, then you don't really need that structure anyway. Leave it to the ORM to help you find your objects, or give you a sequence of all objects to iterate over. I recommend using SQLAlchemy for this.
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49211118
type: Answer
accepted answer of: http://stackoverflow.com/q/49211118

http://stackoverflow.com/q/49227062
accepted answer: http://stackoverflow.com/a/49227365
upvote count: 1
tagged with: multithreading
answer count: 1
type: Question
has title: Python background threads
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85458421
downvote count: 1
tagged with: python
favorite count: 0
has body: Given this code snippet: import time if __name__ == "__main__": list = [] counter = 0 while True: counter = counter + 1 time.sleep(0.0033) list.append(counter) I would like to create a thread which runs in the background doing some metadata calculations (finding the sum of the elements in the array) on the array "list" being populated in real time in the while loop.
has answer: http://stackoverflow.com/a/49227365

http://stackoverflow.com/comment/85415500
comment on: http://stackoverflow.com/q/49201581
has text: Are you getting any errors? Also I think the `return render` statement should be inside the else statement at the end, and you probably would want to pass `user_form` and `profile_form` as context or args into that just to clean it up a bit
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49256917
tagged with: python
has answer: http://stackoverflow.com/a/49259085
has body: I was trying to adopt this solution proposed in this thread to determine the parameters of a simple normal distribution. Even though the modifications are minor (based on wikipedia), the result is pretty off. Any suggestion where it goes wrong? import math import numpy as np from scipy.optimize import minimize import matplotlib.pyplot as plt def gaussian(x, mu, sig): return 1./(math.sqrt(2.*math.pi)*sig)*np.exp(-np.power((x - mu)/sig, 2.)/2) def lik(parameters): mu = parameters[0] sigma = parameters[1] n = len(x) L = n/2.0 * np.log(2 * np.pi) + n/2.0 * math.log(sigma **2 ) + 1/(2*sigma**2) * sum([(x_ - mu)**2 for x_ in x ]) return L mu0 = 10 sigma0 = 2 x = np.arange(1,20, 0.1) y = gaussian(x, mu0, sigma0) lik_model = minimize(lik, np.array([5,5]), method='L-BFGS-B') mu = lik_model['x'][0] sigma = lik_model['x'][1] print lik_model plt.plot(x, gaussian(x, mu, sigma), label = 'fit') plt.plot(x, y, label = 'data') plt.legend() Output of the fit: jac: array([2.27373675e-05, 2.27373675e-05]) message: 'CONVERGENCE: REL_REDUCTION_OF_F_&lt;=_FACTR*EPSMCH' success: True x: array([10.45000245, 5.48475283])
tagged with: scipy
favorite count: 0
has title: Scipy MLE fit of a normal distribution
upvote count: 2
accepted answer: http://stackoverflow.com/a/49259085
has comment: http://stackoverflow.com/comment/85516884
answer count: 1
tagged with: gaussian
downvote count: 1
type: Question
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/29324222
tagged with: curve-fitting

http://stackoverflow.com/comment/85535433
has text: thats what i thought, but when i switch it, the labels just get jumbled up in another direction.
type: QuestionComment
comment on: http://stackoverflow.com/q/49265951
score: 0
type: Comment

http://stackoverflow.com/comment/85451976
score: 0
comment on: http://stackoverflow.com/q/49224133
type: Comment
type: QuestionComment
has text: I have added a scrapy generated xml

http://stackoverflow.com/comment/85324931
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49158983
has text: is your series St a pandas Series?
type: Comment

http://stackoverflow.com/comment/85345148
has text: @bkcollection Your data is not json, and has unclosed braces/brackets
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/49169868
type: Comment

http://stackoverflow.com/comment/85451213
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49223863
has text: What kind of errors?

http://stackoverflow.com/q/49221417
favorite count: 0
type: Question
has title: PyRun_File with recursive functions in Python C-API
has comment: http://stackoverflow.com/comment/85446554
tagged with: python
tagged with: python-c-api
accepted answer: http://stackoverflow.com/a/49222112
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49222112
has body: I am working on embedding python interpreter in a larger system and one of the features is to run a python script on the fly. Testing with the following code snippet works great, but with recursive function only the first call is executed then crashes //C++ code int main() { Py_Initialize(); PyObject* m_pMainModule = PyImport_AddModule("__main__"); PyObject* m_pGlobalDict = PyModule_GetDict(m_pMainModule); PyObject* m_pLocalDict = PyDict_New(); PyObject* fd = PyFile_FromString("script.py", "r"); if (fd == NULL) { PyErr_SetString(PyExc_IOError, "File not found"); } PyObject * s = PyRun_File(PyFile_AsFile(fd), "script.py", Py_file_input, m_pGlobalDict, m_pLocalDict); Py_XDECREF(fd); Py_XDECREF(s); if (PyErr_Occurred()) { std::string result; PyObject* ptype; PyObject* pvalue; PyObject* ptraceback; PyErr_Fetch(&amp;ptype, &amp;pvalue, &amp;ptraceback); PyErr_NormalizeException(&amp;ptype, &amp;pvalue, &amp;ptraceback); // in order to convert pvalue from tuples to real objects //Attach exception name first PyObject* objectStr = PyObject_GetAttrString(ptype, "__name__"); result = PyString_AS_STRING(objectStr); result = "Exception: " + result;; Py_XDECREF(objectStr); objectStr = PyObject_Str(pvalue); if (objectStr != NULL) { result = result + " was raised with error message : " + PyString_AS_STRING(objectStr); Py_XDECREF(objectStr); } std::cout &lt;&lt; result; } return 0; } Here is the python script I use def fac(i): print "Call to FAC(",i,") !" if i &lt;= 1: return 1 else: return i*fac(i-1) print "Hello world" print fac(4) And here is the output Hello world Call to FAC( 4 ) ! Exception: NameError was raised with error message : global name 'fac' is not defined While the expected output ( when run directly by invoking the script ) Hello world Call to FAC( 4 ) ! Call to FAC( 3 ) ! Call to FAC( 2 ) ! Call to FAC( 1 ) ! 24 Any ideas on how to proceed ? Edit: Platform: Windows 10 x64 Python: 2.7.14
score: 1
answer count: 1
downvote count: 0
upvote count: 1

http://stackoverflow.com/comment/85533636
has text: That is np.where..
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49265053
score: 0

http://stackoverflow.com/a/49277061
answers question: http://stackoverflow.com/q/49275599
type: Answer
has comment: http://stackoverflow.com/comment/85556705
score: 0
has body: To query a database you must first create an object of its class definition in your Flask code. From your code, the class Building and the class Location should be queried. So it should be like: class BuildingList(Resource): def get(self): buildings = Building.query.all() results = buildings_schema.dump(buildings) print(results) class LocationList(Resource): def get(self): locations = Location.query.all() results = locations_schema.dump(locations) print(results) I don't see any definition for buildingModel or locationModel in your code.
has comment: http://stackoverflow.com/comment/85557724

http://stackoverflow.com/q/49127947
tagged with: numpy
has title: how to change a object-form array to a normal one
score: 0
answer count: 1
has body: Here is a .txt data file,where the first 2 lines are some headers: REC OBS REPORT TIME STATION LATI- LONGI- ELEV STN PR STN DSLP ALTIM AIR.T DEWPT R.HUM WIND WIND HOR 3H PR 24H PR | TYPE TYPE YYYYMMDDHHMM BBSSS TUDE TUDE (M) (HP=MB) (HP=MB) (HP=MB) (C) (C) (%) DIR SPD(M/S) VIS(M) (KG/M2) (KG/M2) | PRES PMSL TMDB ALSE TMDP REHU WDIR WSPD TP03 TP24 HOVI ADPSFC SYNOP 201209191754 72533 41.00 -85.20 252 990.3 1020.1 -9999.9 18.3 2.2 -9999.9 240.0 4.1 16000.0 -9999.9 -9999.9 | 99030.00 102010.00 291.45 -9999.90 275.35 -9999.90 240.00 4.10 -9999.90 -9999.90 16000.00 ADPSFC SYNOP 201209191754 72438 39.73 -86.27 246 991.7 1020.5 -9999.9 18.3 3.3 -9999.9 200.0 3.6 16000.0 -9999.9 -9999.9 | 99170.00 102050.00 291.45 -9999.90 276.45 -9999.90 200.00 3.60 -9999.90 -9999.90 16000.00 ADPSFC SYNOP 201209191756 72423 38.18 -85.73 149 1004.1 1021.5 -9999.9 19.4 1.1 -9999.9 0.0 0.0 16000.0 -9999.9 -9999.9 | 100410.00 102150.00 292.55 -9999.90 274.25 -9999.90 0.00 0.00 -9999.90 -9999.90 16000.00 ADPSFC SYNOP 201209192054 72533 41.00 -85.20 252 988.4 1017.9 -9999.9 19.4 2.8 -9999.9 200.0 6.2 16000.0 0.0 -9999.9 | 98840.00 101790.00 292.55 -9999.90 275.95 -9999.90 200.00 6.20 0.00 -9999.90 16000.00 ADPSFC SYNOP 201209192056 72423 38.18 -85.73 149 1001.8 1019.2 -9999.9 21.7 0.6 -9999.9 0.0 0.0 16000.0 0.0 -9999.9 | 100180.00 101920.00 294.85 -9999.90 273.75 -9999.90 0.00 0.00 0.00 -9999.90 16000.00 Actually, it can be downloaded here. I read and store these data in obs, a dataframe using pd.read_table() obs.values[1] Out[4]: array([ ' ADPSFC SYNOP 201208312354 72533 41.00 -85.20 252 988.4 1017.6 -9999.9 27.2 22.8 -9999.9 200.0 2.1 16000.0 -9999.9 -9999.9 | 98840.00 101760.00 300.35 -9999.90 295.95 -9999.90 200.00 2.10 -9999.90 -9999.90 16000.00'], dtype=object) However, in the array ,it is a string. Applying the splitlines(),we can get the result: str(obs.values[1]).splitlines() Out[5]: ["[ ' ADPSFC SYNOP 201208312354 72533 41.00 -85.20 252 988.4 1017.6 -9999.9 27.2 22.8 -9999.9 200.0 2.1…
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49128803
has answer: http://stackoverflow.com/a/49128803
tagged with: pandas
tagged with: python
type: Question

http://stackoverflow.com/comment/85330081
type: Comment
comment on: http://stackoverflow.com/a/49162073
score: 0
type: AnswerComment
has text: This seems good but I need it to keep going if there is "b (x)" in list b and so on.. What I posted what just an example

http://stackoverflow.com/a/49222448
has comment: http://stackoverflow.com/comment/85449315
has body: You can apply join df.str.apply(' '.join) Out[162]: 0 a b 1 b c 2 c d 3 d e 4 e f Name: str, dtype: object Also without apply df['str'].str.join(sep=' ') Out[163]: 0 a b 1 b c 2 c d 3 d e 4 e f Name: str, dtype: object
score: 3
answers question: http://stackoverflow.com/q/49222414
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85449423
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85448595
has comment: http://stackoverflow.com/comment/85449265
has comment: http://stackoverflow.com/comment/85448487
type: Answer
accepted answer of: http://stackoverflow.com/q/49222414
has comment: http://stackoverflow.com/comment/85449365

http://stackoverflow.com/comment/85375733
type: Comment
type: QuestionComment
has text: The model contains operations names. These names are evolving with most TF versions, and you need the same operations available on client and server side. Do you know what TF version is on client and server?
score: 0
comment on: http://stackoverflow.com/q/49166240

http://stackoverflow.com/a/56999992
has comment: http://stackoverflow.com/comment/109574999
upvote count: 16
answers question: http://stackoverflow.com/q/49235486
downvote count: 0
has comment: http://stackoverflow.com/comment/115114744
score: 16
has body: For example I open SQL log in dev settings My file structure: create settings folder and mv original settings.py to settings/defaults.py load defaults in init.py # proj/proj/settings/__init__.py from .defaults import * Edit dev.py # proj/proj/settings/dev.py from .defaults import * DEBUG = True # print sql to the console LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', } }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level': 'DEBUG', } }, } run in the python env ./manage.py runserver --settings proj.settings.dev Django 2.1.7 | Mac
type: Answer

http://stackoverflow.com/comment/85497371
type: Comment
comment on: http://stackoverflow.com/q/49246790
has text: As you already stated this has been answered a million times. You'll have to explain what exactly is not answered in the million existing posts.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85318051
score: 0
has text: @fasouto updated. thanks
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49156529

http://stackoverflow.com/comment/85359233
has text: @liliscent C has the ternary conditional operator like `c ? a : b` where c gets assigned a if c is true and b if c is false.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49176905
type: QuestionComment

http://stackoverflow.com/comment/85450500
type: AnswerComment
has text: There is a solution, and we've given the various options twice already. The OP has just not been able to see how they can be applied.
comment on: http://stackoverflow.com/a/49221423
type: Comment
score: 0

http://stackoverflow.com/a/49128028
has body: returned-rent returns a timeDelta object, not an integer, so it can't be compared to an integer. what you want is the number of days, so you can use (returned-rent).days
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49127697
score: 1
type: Answer

http://stackoverflow.com/a/66383652
type: Answer
score: 0
has body: First, follow the quickstart instructions from PDAL website in order to be sure your environnement is correctly settled and all packages installed: https://pdal.io/quickstart.html Then, you can write a pipeline in a file named for example "pipeline.json" as follows: [ { "type": "readers.las", "filename": "D:\\myLAS\\myFile.las" }, { "type": "writers.pcd", "compression": "binary", "order": "X,Y,Z,intensity", "keep_unspecified": "false", "filename": "D:\\myPCD\\myFile.pcd" } ] You change the parameters "compression", "order" and "keep_unspecified" as wanted (https://pdal.io/stages/writers.pcd.html) Finally, you run your pipeline in Anaconda command line: pdal pipeline pipeline.json
answers question: http://stackoverflow.com/q/49233547

http://stackoverflow.com/a/49259610
type: Answer
answers question: http://stackoverflow.com/q/49259470
upvote count: 3
downvote count: 0
score: 3
has body: Here is a way to do it with only one pass over the file. You have to abandon the nice built-in sum and do it yourself: def read(filename): A, B = 0, 0 with open(filename) as f: for line in f: x = float(line) A += x B += x**2 print(A) print(B) Also note that you are actually iterating in a weird way over the lines of the file, since you have an outer loop for line in f and an inner loop in the sum that also runs over for line in f. Since f is an iterator, this means that the outer loop will only get to the first line, the inner loop will consume all other lines and sum them and then the outer loop has nothing else to process and quits. You should be able to see this by noting that the print(B) statement is only executed once.

http://stackoverflow.com/comment/85372135
type: QuestionComment
score: 0
has text: Actually, one more one more thing: I see a C++ lambda in the code, so I assume this is compiled as C++. But I don't see an extern C anywhere. So, do you actually have a `PyInit_turkey`, or just some name-mangled function that you can't find via `dlsym` on the expected name?
comment on: http://stackoverflow.com/q/49182978
type: Comment

pipenv
tags question: http://stackoverflow.com/q/49178797
tags question: http://stackoverflow.com/q/49268638
tag name: pipenv
type: Tag

http://stackoverflow.com/comment/85335698
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49165112
type: Comment
has text: You need to add a control dependency.

http://stackoverflow.com/comment/85411780
type: AnswerComment
has text: Is this the case I wonder? I am loading 3 lab files with the pathLabel function. However, all the files are contained in 1 list. Lab1 index 0 to 19, lab2 index 20 to 51 etc...
score: 0
comment on: http://stackoverflow.com/a/49203140
type: Comment

http://stackoverflow.com/a/49266107
upvote count: 1
has comment: http://stackoverflow.com/comment/85536268
accepted answer of: http://stackoverflow.com/q/49265887
score: 1
type: Answer
has body: Your code can be improved in the following things: You do not have to create box_share2 in the .py since you're creating it in the .kv When you use sm = ScreenManager() you are creating another ScreenManager different from the original, that is not necessary. It is not necessary to use range and len, make your code less readable, you just have to iterate. If we look at the structure of the .kv we see that the presentation object is the ScreenManager so you can get it via app.root. Using the above your code the solution is: [...] class GarageNameBoxLayout(BoxLayout): def __init__(self, **kwargs): super(GarageNameBoxLayout, self).__init__(**kwargs) self.orientation = "vertical" Clock.schedule_interval(self.create_button, 5) def create_button(self, *args): self.box_share2.clear_widgets() app = App.get_running_app() sm = app.root #put GarageNameStartList data into app class, then pull from it in this class top_button_share = 1.1 color = (.4, .4, .4, 1) for text in app.GarageNameStartList: top_button_share -= .4 id_ = text button_share = Button(background_normal='', background_color = color, id = id_, pos_hint = {"x": 0, "top": top_button_share}, size_hint_y = None, height = 60, font_size = 30, text = text) button_share.bind(on_press=lambda *args: setattr(sm, 'current', "main")) self.box_share2.add_widget(button_share) [...]
answers question: http://stackoverflow.com/q/49265887
has comment: http://stackoverflow.com/comment/85536326
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49247356
score: 3
has title: How to close file of FileHandler opened in Python process
type: UnansweredQuestion
tagged with: python
has body: I'm using a logger inside Python process (multiprocessing.process) to log. I declare a FileHandler to log to disk, once the job is done I try to close the underlying file but can't achieve that. My real problem is that I spawn a lot of process resulting in IOError: [Errno 24] Too many open files I reproduce the error with this snippet (test_process.py): import logging import multiprocessing class TestProcess(multiprocessing.Process): def __init__(self): multiprocessing.Process.__init__(self) self.logger = logging.getLogger('test') self.logger.setLevel(logging.INFO) self.handler = logging.FileHandler('test.log') self.handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') self.handler.setFormatter(formatter) self.logger.addHandler(self.handler) def run(self): self.logger.info('hello') self.logger.removeHandler(self.handler) self.handler.close() and when I run this: from test_process import TestProcess p=TestProcess() p.start() p.join() You can check that there is file descriptor alive for the file test.log. Any hint to overcome this behaviour?
has comment: http://stackoverflow.com/comment/85518015
has answer: http://stackoverflow.com/a/49257862
tagged with: python-multiprocessing
upvote count: 3
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49257449
favorite count: 0
type: Question

http://stackoverflow.com/comment/85291979
type: AnswerComment
has text: I think this clearly does what the OP asked.. do people think it requires more explanation?
comment on: http://stackoverflow.com/a/49143207
type: Comment
score: 3

http://stackoverflow.com/q/49134926
type: UnansweredQuestion
tagged with: python
has body: I need to perform FFT on gait signals that are not strictly periodic. Below is the code I created for double and single sided. However, I do not know if it is right as the signal is not strictly periodic -- people walk differently every step. If I sample the same number of samples each period, then I do not know what to give fftpack.fftfreq( n, d ) parameter d. Right now I set the d as the time elapse between samples. If I created same number of samples each period, then the d will be changing. Not sure what to do. Are there existing code here? def plotDoubleSidedSpectrum(y,timestep,SigName,xlimit): n=len(y) FFT = fftpack.fft(y) freqs = fftpack.fftfreq(n,d=timestep) print(FFT) fig,ax=plt.subplots() ax.plot(freqs,np.abs(FFT)/n,'r') ax.set_xlabel(SigName+ ': Double Sided Frequency in Hertz [Hz]') ax.set_ylabel('Frequency Domain (Spectrum) Magnitude') ax.set_xlim(-xlimit, xlimit) def plotSingleSidedSpectrum(y,timestep,SigName,xlimit): n=len(y) FFT = fftpack.fft(y) freqs = fftpack.fftfreq(n,d=timestep) freqSingle = freqs[:n//2] AmpSingle = 2*np.abs(FFT[:n//2])/n # divided by n is to normalize it fig,ax=plt.subplots() ax.plot(freqSingle,AmpSingle,'r') ax.set_xlabel(SigName+':Single Sided Frequency in Hertz [Hz]') ax.set_ylabel('Frequency Domain (Spectrum) Magnitude') ax.set_xlim(0,xlimit)
score: 0
has comment: http://stackoverflow.com/comment/85291037
has comment: http://stackoverflow.com/comment/85334283
has comment: http://stackoverflow.com/comment/85335885
tagged with: fftpack
has title: How to do FFT on signal of different period
answer count: 1
has answer: http://stackoverflow.com/a/50336411
tagged with: signal-processing
tagged with: fft
type: Question
tagged with: numpy

http://stackoverflow.com/a/49183800
has body: Try using your_string.encode('utf-8'). Using your example: print('\u5475\u5475'.encode('utf-8')) Here's another answer explaning this in more detail.
has comment: http://stackoverflow.com/comment/85458319
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49179818

http://stackoverflow.com/a/49129324
has comment: http://stackoverflow.com/comment/85263322
answers question: http://stackoverflow.com/q/49129256
score: 4
type: Answer
upvote count: 4
downvote count: 0
has body: This should work: df['desired'] = '' df.loc[df['col1'] &gt; 20, 'desired'] = 'col1 is ' + df['col1'].astype(str) Example import pandas as pd df = pd.DataFrame({'col1': [25, 10, 15, 21]}) df['desired'] = '' df.loc[df['col1'] &gt; 20, 'desired'] = 'col1 is ' + df['col1'].astype(str) # col1 desired # 0 25 col1 is 25 # 1 10 # 2 15 # 3 21 col1 is 21 The problem with this The power of pandas is in holding structured data. As soon as you combine strings with numeric data, you lose that structure. Manipulating strings is tedious, for example you can't add 1 to the "desired" column. A better idea It is better to use a Boolean column to signify a desired condition. For example: df['desired'] = df['col1'] &gt; 20 This will give a Boolean [True or False] series depending on the condition specified.
has comment: http://stackoverflow.com/comment/85263451

http://stackoverflow.com/q/49215406
type: Question
has body: I need to extract number from string 'iama5559348number'. Answer should do non capturing and expected output is 5559348. I am trying by doing this way print(re.search(r'([^(.*)]?[0-9]*)','iama5559348number'))but I am getting only only first letter
possible better answer: http://stackoverflow.com/a/49215437
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/49215437
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49215583
answer count: 2
has comment: http://stackoverflow.com/comment/85435043
has answer: http://stackoverflow.com/a/49215583
score: 1
downvote count: 0
upvote count: 1
has title: extract number from string using regular expression
favorite count: 0

http://stackoverflow.com/a/67999511
type: Answer
upvote count: 4
score: 4
downvote count: 0
has body: I do not have enough rep to comment, therefore I am posting this as an answer. As @CheradenineZK mentions, if the input is coming from an (Azure) blob storage, it needs to be wrapped in a byte buffer. I was struggling to figure out exactly how to do this... import io import openpyxl bytes_in = io.BytesIO(myblob.read()) wb = openpyxl.load_workbook(bytes_in) is doing the trick for me.
answers question: http://stackoverflow.com/q/49194667

http://stackoverflow.com/a/49790514
type: Answer
answers question: http://stackoverflow.com/q/49168198
score: 0
has body: So I figured it out, and this is what I did. def delete(): notepad.delete(0.0, END) def redo(): notepad.edit_redo() def undo(): notepad.edit_undo()

http://stackoverflow.com/a/49280552
upvote count: 14
has comment: http://stackoverflow.com/comment/96359804
type: AcceptedAnswer
downvote count: 0
score: 14
type: Answer
answers question: http://stackoverflow.com/q/49274650
accepted answer of: http://stackoverflow.com/q/49274650
has body: No, that's currently not possible. The main purpose of the .tar.gz archives is to make them easy to install via pip install. However, you can always extract the model data from the archive, and then load it in from a path – see here for more details. nlp = spacy.load('/path/to/en_core_web_md') Using the spacy link command you can also create "shortcut links" for your models, i.e. symlinks that let you load in models using a custom name instead of the full path or package name. This is especially useful if you're working with large models and multiple environments (and don't want to install the data in each of them). python -m spacy link /path/to/model_data cool_model The above shortcut link would then let you load your model like this: nlp = spacy.load('cool_model') Alternatively, if you really need to load models from an archive, you could always write a simple wrapper for spacy.load that takes the file, extracts the contents, reads the model meta, gets the path to the data directory and then calls spacy.util.load_model_from_path on it and returns the nlp object.

http://stackoverflow.com/comment/85275060
type: Comment
has text: `python3 --help` gives me a `-m mod : run library module as a script (terminates option list)`
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49133234

http://stackoverflow.com/comment/85477838
type: AnswerComment
has text: Yes, replace `(...)` with `(:?...)`
type: Comment
comment on: http://stackoverflow.com/a/49235023
score: 0

http://stackoverflow.com/comment/86775313
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49212095
has text: @Oliver Never mind I suppose it's a different question: how to test if a tuple exists. I did find the answer elsewhere.

http://stackoverflow.com/comment/139929785
comment on: http://stackoverflow.com/a/49249910
type: Comment
type: AnswerComment
has text: @Joe You can select pandas columns using dot notation. It is not advised to do so. The OP's example had a "v" column.
score: 0

http://stackoverflow.com/q/49165454
has body: So my pygame script in python works perfectly, so I decided to try to bundle the program in order to distribute it, using Pyinstaller. I compiled and ran Pyinstaller just as directed: sudo pip install pyinstaller pyinstaller Loop.py It worked fine. Then I ran the generated executable file to see it in action: cd /dist/Loop/ ./Loop The result, was this: Fatal Python error: (pygame parachute) Segmentation Fault Aborted (core dumped) Not a single line of Loop.py seems to be executed, since the first lines after importing packages is to open a new window (which didn't happen). With a little googling, it seems the only recommended solution is to debug the code to find where the segmentation took place. However, that doesn't make sense since the code works perfectly fine on its own, it only does this after using pyinstaller. I even entered a python shell in the same directory as the Loop executable, and verified that there is no problem in importing pygame. At any rate, I'm just looking for a way to bundle the python project. Of course, if you know any better way to bundle a python project for distribution (using Python 2.7 on Ubuntu 16) I'd be happy to check it out :) Edit I created a version of my code which is as simplified as possible, in order to focus on the main issue (and of course to prove that the problem is reproducible). Here is the main program (Loop.py): from Car import* vehicle = Car() def display_all(main_surface, display_list): main_surface.fill((0, 100, 100)) for element in display_list: element.display(main_surface) def update_all(update_list): for element in update_list: element.update() running = True while running: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: None key = pygame.key.get_pressed() to_update = [vehicle] to_display = [vehicle] update_all(to_update) display_all(main_s, to_display) pygame.display.flip() And here is Car.py: from Startup import* class Car: def _…
has title: Error after creating executable Pygame with Pyinstaller
upvote count: 2
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/49228425
accepted answer: http://stackoverflow.com/a/49228425
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/85383399
tagged with: segmentation-fault
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85380379
has comment: http://stackoverflow.com/comment/85381308
has comment: http://stackoverflow.com/comment/85411924
has comment: http://stackoverflow.com/comment/85379461
tagged with: pyinstaller
has comment: http://stackoverflow.com/comment/85380678
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/85543144
type: QuestionComment
comment on: http://stackoverflow.com/q/49204114
score: 0
has text: I haven't forgotten about your answer, and thanks for taking the time to post it. I just had to shift projects momentarily. I will be checking this tomorrow and will follow up suitably. Thank you!
type: Comment

http://stackoverflow.com/comment/85316755
comment on: http://stackoverflow.com/q/49153403
has text: this sounds similar: https://github.com/ansible/ansible/issues/25559
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/tag/r
tags question: http://stackoverflow.com/q/49160818
tags question: http://stackoverflow.com/q/49129471
tags question: http://stackoverflow.com/q/49200518
tags question: http://stackoverflow.com/q/49196752
tags question: http://stackoverflow.com/q/49234807
tags question: http://stackoverflow.com/q/49149348
tags question: http://stackoverflow.com/q/49144110
type: Tag
tags question: http://stackoverflow.com/q/49276547
tags question: http://stackoverflow.com/q/49247796
tags question: http://stackoverflow.com/q/49200000
tags question: http://stackoverflow.com/q/49260862
tags question: http://stackoverflow.com/q/49186510
tags question: http://stackoverflow.com/q/49241079
tags question: http://stackoverflow.com/q/49237298
tags question: http://stackoverflow.com/q/49257867
tags question: http://stackoverflow.com/q/49258407
tag name: r
tags question: http://stackoverflow.com/q/49277795
tags question: http://stackoverflow.com/q/49278873

http://stackoverflow.com/a/49214676
answers question: http://stackoverflow.com/q/49214609
score: 1
type: Answer
has body: Here's a solution for computing a shifted character: def shift_lc( c, shift ): new_ord = ord(c) + shift return chr( new_ord - (26 if new_ord &gt; ord('z') else 0) )
has comment: http://stackoverflow.com/comment/85434025
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/49271435
has body: Maybe this is what you have in mind. Start with a pandas Series df: 2018-03-14 06:38:46.308425+00:00 2 2018-03-14 06:38:47.308425+00:00 3 2018-03-14 06:38:48.308425+00:00 4 2018-03-14 06:38:54.308425+00:00 3 2018-03-14 06:38:55.308425+00:00 4 dtype: int64 Find the indices where the cumulative sum crosses a multiple of 5: df[:] = df.values.cumsum() // 5 * 5 hit5 = (df.diff() == 5).nonzero()[0] In this case it's array([1, 3, 4]). Then iterate over those indices and take the difference with the previous index: for i in hit5: print(df.index[i] - df.index[i-1]) Giving: 0 days 00:00:01 0 days 00:00:06 0 days 00:00:01
answers question: http://stackoverflow.com/q/49269856
score: 0
type: Answer

http://stackoverflow.com/a/49267950
score: 0
answers question: http://stackoverflow.com/q/49267696
has body: Because you already used pandas, so you can just simple join excel data with your list. Or you can create one dict to store the key/value pair, then loop your list to get the value from that dict. The codes will be like below: (Assuming all keys can be found in excel, you may need to add some validations for real use): #uses one dict store index test = ['a' ,'b', 'c'] excel = [['a', 1], ['b', 2], ['c', 3]] G_indexes = {} def buildIndexes(data): G_indexes[data[0]] = data[1] return data list(map(buildIndexes, excel)) print('normal',list(map(lambda item: G_indexes[item], test))) #use pandas join import pandas as pd df_excel = pd.DataFrame({'key': ['a', 'b', 'c', 'd', 'e'], 'value': [1, 2, 3, 4, 5]}) your_list = ['a', 'b', 'c'] df_yours = pd.DataFrame({'key': your_list}) df_result = df_yours.join(df_excel.set_index('key'), on='key') print('pandas',list(df_result['value'])) Output: normal [1, 2, 3] pandas [1, 2, 3] [Finished in 1.04s]
type: Answer

http://stackoverflow.com/comment/85424591
score: 0
has text: Because the points simply do not follow a polynomial, what exactly do you expect?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49210025

http://stackoverflow.com/a/49243291
has body: It turns out that djangorestframework was an older version. It was most definitely not a duplicate of the question suggested but I was able to solve it by upgrading my version (as suggested by @Alexy). I'm leaving this up in case someone else has a similar issue.
downvote count: 0
has comment: http://stackoverflow.com/comment/85649695
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/49242250
type: Answer

http://stackoverflow.com/comment/85355456
comment on: http://stackoverflow.com/q/49175172
score: 0
type: Comment
type: QuestionComment
has text: have you tried to use `os.chmod(file_path, 000)` ?

http://stackoverflow.com/q/49251688
has answer: http://stackoverflow.com/a/49251830
possible better answer: http://stackoverflow.com/a/49251861
has body: A basic question but I've got a file, say file.csv, in the directory, C:/Users/User/Desktop/Other/DataAnalysis/CurrentData/file.csv, and so I've written, df = pd.read_csv("C:/Users/User/Desktop/Other/DataAnalysis/CurrentData/file.csv") and I get an error - &gt; FileNotFoundError: File &gt; b'C:/Users/User/Desktop/Other/DataAnalysis/CurrentData/file.csv' does not exist I've tried df = pd.read_csv("file.csv") As the file.csv is in the exact same folder as my python script, and I still get the same error. I'm not sure what I've done wrong. I've checked the python API and I've tried reversing the brackets (so using \\ instead of /), and still doesn't work. Thank you.
has comment: http://stackoverflow.com/comment/85506876
tagged with: python
has answer: http://stackoverflow.com/a/54813947
has answer: http://stackoverflow.com/a/49251861
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85506788
has title: Python/CSV - File not found error
answer count: 3
has comment: http://stackoverflow.com/comment/85506841
tagged with: http://stackoverflow.com/tag/csv
score: 1
has comment: http://stackoverflow.com/comment/85506950
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49251830
upvote count: 2

http://stackoverflow.com/comment/85357192
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49175688
score: 1
has text: The browser will treat `class="class1 class2 class3 "` and `class="class1 class2 class3"` the same way, so one option is to not worry about the space.

http://stackoverflow.com/comment/85406867
comment on: http://stackoverflow.com/q/49200363
score: 0
type: Comment
has text: This is a question about (applied) math, not programming.
type: QuestionComment

http://stackoverflow.com/a/49240971
downvote count: 1
answers question: http://stackoverflow.com/q/49240881
has body: df.A = pd.to_timedelta(df.A) df.fillna(0) A 0 3 days 1 0 days 2 4 days
type: Answer
score: 6
upvote count: 7

http://stackoverflow.com/comment/85311967
score: 0
has text: You can send messages to *some* servers. Discord servers used to come with a default channel, which is where your message would go if you tried to message the server. New Discord servers ([After August of last year](https://stackoverflow.com/questions/46673995/discord-py-invalid-arguments-inside-member-server-default-channel)) no longer have a default channel, so messaging those servers isn't possible. At this point, it's best to assume you can only message channels (those channels can be any channel the bot can access, even across servers).
type: AnswerComment
comment on: http://stackoverflow.com/a/49153607
type: Comment

http://stackoverflow.com/comment/85513902
comment on: http://stackoverflow.com/a/49255415
type: AnswerComment
has text: `np.isnan` won't accept the value as an input type, but using `pd.isnull` returns `False`.
score: 0
type: Comment

http://stackoverflow.com/comment/85368567
has text: you iterate numbers other than file contents, x is numerical value
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49181460

http://stackoverflow.com/a/49258087
answers question: http://stackoverflow.com/q/49163929
type: Answer
has comment: http://stackoverflow.com/comment/85519169
has body: Since you are trying to perform a "search" (or filtering) you should use "fitler()" instead of get(), it makes more sense semantically. For your information, filter does not raise an exception if the result is empty. Your code will look similar to: from django.db.models import Q def search(request): results = [] query = request.GET.get('q', '') if query: qset = Q(titulo__icontains=query) | Q(cuerpo__icontains=query) results = Articulo.objects.filter(qset).distinct() ctx = {"results": results, "query": query} return render_to_response('web/buscar.html', ctx) If you are getting DoesNotExist exceptions with code which uses filter() you should take a look to the traceback to look for the liurls.py file to ensure that your desired views is being called and not other one.
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49163929

http://stackoverflow.com/q/49272584
type: AnsweredQuestion
has title: Extract Number from String Python
has comment: http://stackoverflow.com/comment/85547998
answer count: 3
has answer: http://stackoverflow.com/a/49272642
has comment: http://stackoverflow.com/comment/85548413
tagged with: python
has answer: http://stackoverflow.com/a/49272683
tagged with: regex
has comment: http://stackoverflow.com/comment/85547925
downvote count: 4
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49273148
upvote count: 2
possible better answer: http://stackoverflow.com/a/49272642
has comment: http://stackoverflow.com/comment/85548106
score: -2
has comment: http://stackoverflow.com/comment/85547876
has body: I would like to extract a certain numbers in a string, after numerous tries with regex, I can't seem to find the correct pattern for it. There are other numbers but I require only the 3 digits after "M". Thank you. Example: line: "2018-01-23 - member data. member_id=[M001]." Result: 001
has comment: http://stackoverflow.com/comment/85548179
accepted answer: http://stackoverflow.com/a/49272683
has comment: http://stackoverflow.com/comment/85548073
has comment: http://stackoverflow.com/comment/85548050

http://stackoverflow.com/comment/85475575
type: Comment
has text: Yes, that's the problem. 0.19 Unfortunately, I can't upgrade because It's not local, is not depending on me.
comment on: http://stackoverflow.com/a/49234026
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85483398
type: AnswerComment
has text: And two minutes before I saw your post I ran into this: https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch01s03.html
comment on: http://stackoverflow.com/a/49239470
type: Comment
score: 0

http://stackoverflow.com/q/49133764
has title: How to maintain Cluster map index order same as my DataFrame index order
answer count: 1
type: Question
type: UnansweredQuestion
has body: I am trying to plot a cluster map with python Sea-born package I want the row order of heat map same as DataFrame index order But the image seems not my data have some character like : data['character']= ['A','A','A','B','B','C','C'] I use the color bar to show the character If the order of the cluster map is the same order as my data frame Same character with be together in my color bar But it is not What can I do to make the cluster map order same as the data frame index order THANKS a lot
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/52336794
tagged with: plot
tagged with: heatmap
score: 0
has comment: http://stackoverflow.com/comment/91545383

http://stackoverflow.com/a/49207431
has body: Try this:- s = 'azcbobobegghakl' count = 0 result = '' ind = 0 for i in range(3,len(s),3): result += s[ind:i] if "bob" in result: count+=1 ind = i result = s[i-1] print(count)
answers question: http://stackoverflow.com/q/49205686
type: Answer
score: 0

http://stackoverflow.com/a/49262299
type: Answer
answers question: http://stackoverflow.com/q/49262171
score: 0
has comment: http://stackoverflow.com/comment/85529384
accepted answer of: http://stackoverflow.com/q/49262171
has body: Use a context manager to handle reading the list, and the file will remain open only for the operation it contains. import csv def get_stock_count(): ITEM_COUNT = 0 with open('stock.csv', 'r') as STOCK_READ: reader = csv.reader(STOCK_READ) for line in reader: ITEM_COUNT = ITEM_COUNT + 1 print("{0} - {1} - {2} in stock".format(ITEM_COUNT,line[0],line[1])) return ITEM_COUNT Once the contained for loop is complete, the file will close. Any time you wish to get a new ITEM_COUNT, just call get_stock_count again.
has comment: http://stackoverflow.com/comment/85531026
type: AcceptedAnswer

caching
tags question: http://stackoverflow.com/q/49151668
tags question: http://stackoverflow.com/q/49220617
type: Tag
tags question: http://stackoverflow.com/q/49235259
tag name: caching
tags question: http://stackoverflow.com/q/49257427

http://stackoverflow.com/q/49189402
upvote count: 169
has body: In my Django project I have a user_manage app. I create a model named UserManage in my user_manage app's model.py: from django.db import models from django.contrib.auth.models import AbstractUser class UserManage(AbstractUser): username = models.CharField(max_length=12) Then I run: $ python3 manage.py makemigrations There comes the error: ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'UserManage.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'UserManage.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'UserManage.user_permissions'. users_management.UserManage.groups: (fields.E304) Reverse accessor for 'UserManage.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'UserManage.groups' or 'User.groups'. users_management.UserManage.user_permissions: (fields.E304) Reverse accessor for 'UserManage.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'UserManage.user_permissions' or 'User.user_permissions'.
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/53029234
downvote count: 0
has title: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'
has comment: http://stackoverflow.com/comment/85384027
has answer: http://stackoverflow.com/a/53029234
answer count: 7
has answer: http://stackoverflow.com/a/72023163
score: 169
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/66294885
has answer: http://stackoverflow.com/a/65413300
has answer: http://stackoverflow.com/a/63244995
has answer: http://stackoverflow.com/a/49189522
accepted answer: http://stackoverflow.com/a/49189522
has answer: http://stackoverflow.com/a/71613629
tagged with: django
tagged with: python

http://stackoverflow.com/comment/85443361
type: AnswerComment
has text: For small names only, name.lower() is faster
comment on: http://stackoverflow.com/a/49219723
type: Comment
score: 0

http://stackoverflow.com/q/49127454
has answer: http://stackoverflow.com/a/51536440
has body: I write an application using Pyinstaller which installs Python on the target machine and some packages. At the end of the application I am supposed to spawn a Python script and I use subprocess.Popen(). However, it appears that script cannot execute it as it appears to still use the application's (pyinstaller's) runtime environment. However, running the resulting script stand alone after the installation works. Is there a way to spawn a process outside the pyinstaller's context?
tagged with: popen
tagged with: pyinstaller
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/85259954
score: 0
tagged with: subprocess
has title: Running external Python script from Pyinstaller
type: UnansweredQuestion
answer count: 1
has comment: http://stackoverflow.com/comment/85259724

http://stackoverflow.com/comment/85563103
comment on: http://stackoverflow.com/a/49278905
has text: @ImportanceOfBeingErnest I skipped this part of his question unintentionally, to be honest. However, I am not sure if he really needs the column to be named 's' or if it is just a dummy name. There are a few possibilities for sorting the columns of a plot. You posted one of them. He can also set the order manually depending on his data. Nevertheless, you're right.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49239369
has body: You need to match your string exactly. Reference: strftime-and-strptime-behavior from datetime import datetime dt = datetime.strptime('2018-03-07 06:46:02.737951', '%Y-%m-%d %H:%M:%S.%f') print(dt.date()) print(dt.time()) d = dt.date() # extract date t = dt.time() # extract time print(type(d)) # printout the types print(type(t)) Output: 2018-03-07 06:46:02.737951 &lt;class 'datetime.date'&gt; &lt;class 'datetime.time'&gt; Your format string is something along the lines of: Month as locale’s abbreviated name. Day of the month as a zero-padded decimal number. Year with century as a decimal number. Hour (12-hour clock) as a zero-padded decimal number. Minute as a zero-padded decimal number. Locale’s equivalent of either AM or PM. with some spaces and : in it - which does not match your format.
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49239262
type: Answer
accepted answer of: http://stackoverflow.com/q/49239262

http://stackoverflow.com/q/49157349
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/49157783
possible better answer: http://stackoverflow.com/a/49157783
has answer: http://stackoverflow.com/a/49157800
type: Question
has title: Why can't I search for a row in a pandas df using a date as part of a tuple index?
accepted answer: http://stackoverflow.com/a/49157800
has body: I am trying to search a pandas df I made which has a tuple as an index. The first part of the tuple is a date and the second part is a forex pair. I've tried a few things but I can't seem to search using a date-formatted string as part of a tuple with .loc or .ix My df looks like this: Open Close (11-01-2018, AEDAUD) 0.3470 0.3448 (11-01-2018, AEDCAD) 0.3415 0.3408 (11-01-2018, AEDCHF) 0.2663 0.2656 (11-01-2018, AEDDKK) 1.6955 1.6838 (11-01-2018, AEDEUR) 0.2277 0.2261 Here is the complete code : import pandas as pd import numpy as np import matplotlib.pyplot as plt forex_11 = pd.read_csv('FOREX_20180111.csv', sep=',', parse_dates=['Date']) forex_12 = pd.read_csv('FOREX_20180112.csv', sep=',', parse_dates=['Date']) time_format = '%d-%m-%Y' forex = forex_11.append(forex_12, ignore_index=False) forex['Date'] = forex['Date'].dt.strftime(time_format) GBP = forex[forex['Symbol'] == "GBPUSD"] forex.index = list(forex'Date', 'Symbol'.itertuples(index=False, name=None)) forex_open_close = pd.DataFrame(np.array(forex'Open','Close'), index=forex.index) forex_open_close.columns = ['Open', 'Close'] print(forex_open_close.head()) print(forex_open_close.ix[('11-01-2018', 'GBPUSD')]) How do I get the row which has index ('11-01-2018', 'GBPUSD') ?
tagged with: datetime
tagged with: python
tagged with: tuples
type: AnsweredQuestion

http://stackoverflow.com/comment/85412208
score: 0
has text: If you have an AWS account, you can run it in lambda as a cronjob.
comment on: http://stackoverflow.com/q/49203359
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49262590
downvote count: 0
score: 1
upvote count: 1
answer count: 1
favorite count: 0
has body: I am trying to import Pybedtools in Spyder. from pybedtools import BedTool This is the error I am getting: Traceback (most recent call last): File "&lt;ipython-input-13-7a8ea5d1dea8&gt;", line 1, in &lt;module&gt; from pybedtools import BedTool File "/Users/michaelsmith/anaconda2/lib/python2.7/site-packages/pybedtools/__init__.py", line 9, in &lt;module&gt; from . import scripts ImportError: cannot import name scripts I just downloaded Anaconda and there doesn't seem to be a reason as to why this happens. What is the typical protocol for resolving bugs like this? UPDATE: So within my pybedtools folder there is a scripts folder (which is presumably the module we're trying to import). I changed both the command within __init__.py to: from . import scripts2 and changed the name of the folder to scripts2 as well. However, I still get the error as such: ImportError: cannot import name scripts2 So I must be doing something wrong here, which module should I be renaming exactly? Sorry if this is a silly question, I am quite new to python.
has title: pybedtools: ImportError: cannot import name scripts
has answer: http://stackoverflow.com/a/49265710
tagged with: anaconda
type: Question
tagged with: python
type: UnansweredQuestion

periodicity
tag name: periodicity
type: Tag
tags question: http://stackoverflow.com/q/49259055

http://stackoverflow.com/q/49224322
answer count: 1
accepted answer: http://stackoverflow.com/a/49374212
favorite count: 0
score: 8
type: Question
has answer: http://stackoverflow.com/a/49374212
has title: moto not mocking ec2?
upvote count: 8
tagged with: mocking
tagged with: moto
downvote count: 0
tagged with: python
tagged with: amazon-web-services
tagged with: boto
type: AnsweredQuestion
has body: I'm trying to test some python code that uses boto. I'd rather not try and do an integration test against AWS, so I am trying to mock it out with moto, and it's not behaving as I'd expect. Here's the test code: import io import boto3 from moto import mock_ec2 from unittest.mock import patch from argparse import Namespace from awswl import commands @mock_ec2 @patch('awswl.externalip.get_external_ip', return_value='192.0.2.1') def test_list_command_lists_ipv4_and_ipv6_cidrs(exip_method): # Given options = Namespace() options.sgid = "sg-123456" ec2 = boto3.resource('ec2') sg = ec2.create_security_group( Description='Security Group for SSH Whitelisting', GroupName='SSH Whitelist' ) print("Created security group: {0}".format(sg.GroupId)) And the error: Testing started at 16:46 ... /path/.virtualenvs/awswl-Ir8BWU8l/bin/python "/path/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/173.4301.16/PyCharm.app/Contents/helpers/pycharm/_jb_pytest_runner.py" --target test_commands.py::test_list_command_lists_ipv4_and_ipv6_cidrs Launching py.test with arguments test_commands.py::test_list_command_lists_ipv4_and_ipv6_cidrs in /path/awswl/tests ============================= test session starts ============================== platform darwin -- Python 3.6.4, pytest-3.4.2, py-1.5.2, pluggy-0.6.0 rootdir: /path/awswl, inifile: collected 1 item test_commands.py F tests/test_commands.py:22 (test_list_command_lists_ipv4_and_ipv6_cidrs) exip_method = &lt;MagicMock name='get_external_ip' id='4547595848'&gt; @mock_ec2 @patch('awswl.externalip.get_external_ip', return_value='192.0.2.1') def test_list_command_lists_ipv4_and_ipv6_cidrs(exip_method): # Given options = Namespace() options.sgid = "sg-123456" &gt; ec2 = boto3.resource('ec2') test_commands.py:30: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ../../../../../.virtualenvs/awswl-Ir8BWU8l/lib/python3.6/site-packages/boto3/__init__.py:92: in resource return _get_default_session().resource(…

http://stackoverflow.com/comment/85505234
has text: I'm using Version 3.5
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49250667
type: Comment

http://stackoverflow.com/comment/85450161
has text: @Franz in that case, it sounds like you may have some additional errors in the code that is not shown here, since the numbers I have come directly from the code you have put in the question. If you can update the question, I will continue later on to help resolve it. But please take not of the extra issue I mentioned regarding the under-determined system.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49222585
type: Comment

http://stackoverflow.com/comment/85552291
type: AnswerComment
has text: Seems, `sel_data: JSON.stringify(table.rows( { filter : 'applied'} ).data().toArray())` works fine, however, now I don't know how to access the column titles correctly (opened a [new question](https://stackoverflow.com/questions/49274691/how-to-return-all-column-names-titles-and-avoid-typeerror-table-columns))
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49255167

http://stackoverflow.com/comment/85319736
score: 0
has text: why is `t` a tuple? it adds unnecessary complexity, just start with a string as in the question.
comment on: http://stackoverflow.com/a/49157444
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85287201
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49140705
score: 0
has text: it works! but it also eliminates C-D from the output being C-D (or D-C) correct... I edited the question to add also my file and show it complete if you can help me

http://stackoverflow.com/comment/85415260
type: Comment
type: AnswerComment
has text: strange i couldn't get it to work with the %s for the string, // does work for me.
score: 0
comment on: http://stackoverflow.com/a/49198286

http://stackoverflow.com/q/49226523
accepted answer: http://stackoverflow.com/a/49226792
score: 1
has title: How to index a 3-D tensor with 2-D tensor in Tensorflow?
tagged with: python
has answer: http://stackoverflow.com/a/49226792
tagged with: tensorflow
type: Question
answer count: 1
downvote count: 0
upvote count: 1
has body: I am trying to use a 2-D tensor to index a 3-D tensor in Tensorflow. For example, I have x of shape [2, 3, 4]: [[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]] and I want to index it with another tensor y of shape [2, 3], where each element of y index the last dimension of x. For example, if we have y like: [[0, 2, 3], [1, 0, 2]] The output should of shape [2, 3]: [[0, 6, 11], [13, 16, 22]]
favorite count: 0
type: AnsweredQuestion

http://stackoverflow.com/comment/85462927
has text: Thanks...appreciate the help
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49229831

annotations
tags question: http://stackoverflow.com/q/49153509
type: Tag
tag name: annotations

http://stackoverflow.com/a/49178162
upvote count: 1
has comment: http://stackoverflow.com/comment/85362139
has body: You'll need an unstack operation: v = df.set_index(['epic_fullname', 'status']) df = v.set_index( v.groupby(level=[0, 1]).cumcount(), append=True ).key\ .unstack(-2)\ .fillna('') You'll also need an extra index column so that you can unstack. The groupby + cumcount operation is for that purpose.
answers question: http://stackoverflow.com/q/49177741
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49177741
has comment: http://stackoverflow.com/comment/85362239
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49207338
tagged with: tensorflow
favorite count: 0
type: Question
type: UnansweredQuestion
tagged with: python
has title: Keras - time per steps increases per epoch. Is there an issue with memory management in my code?
has body: [from anaconda prompt, progress bar removed] Epoch 1/200000 250/250 - 15s 61ms/step - loss: 6.6400 - val_loss: 1.0008 Epoch 2/200000 250/250 - 43s 173ms/step - loss: 6.6387 - val_loss: 1.0003 Epoch 3/200000 250/250 - 70s 280ms/step - loss: 6.6201 - val_loss: 0.9997 Epoch 4/200000 250/250 - 94s 377ms/step - loss: 6.6736 - val_loss: 0.9991 Epoch 5/200000 250/250 - 123s 491ms/step - loss: 6.6491 - val_loss: 0.9999 As you can see, time taken per step increases every epoch. Not sure why this is happening when the model is being fed with same format of data every time. My Cpu, ram, and Gpu usage are all less than 30% load, but my GPU RAM is always maxed out (7GB) Below is my keras code. import keras as kr import h5py as hp import numpy as np import tensorflow as tf #generator def generator(filename, dataset, batch): with hp.File(filename) as h: d = h[dataset] size = d.size i = 0 while i &lt;= np.ceil(size/batch): t = d[i:min((i + 1) * batch, size)] _price = np.swapaxes(np.array([t['ask'], t['bid'], t['price']]), 0, 1) _time = np.swapaxes(np.array([t['year'], t['month'], t['week'], t['date'], t['day'], t['hour'], t['minute'], t['second'], t['microsecond']]), 0, 1) _sma = np.swapaxes(np.array([t['sma 1s'], t['sma 5s'], t['sma 13s'], t['sma 34s'], t['sma 1m'], t['sma 5m'], t['sma 15m'], t['sma 1h'], t['sma 4h'], t['sma 12h'], t['sma 1d'], t['sma 10d']]), 0, 1) _aa = t['alpha2'] i += 1 yield [_price, _time, _sma], _aa if i &gt; size/batch: i = 0 #inputs price = kr.layers.Input(batch_shape=(None,3), name='price') time = kr.layers.Input(batch_shape=(None,9), name='time') sma = kr.layers.Input(batch_shape=(None,12), name='sma') La = kr.layers.Dense(6, input_shape = (None, 3), activation='relu')(price) Lb = kr.layers.Dense(18, input_shape = (None, 9), activation='relu')(time) Lc = kr.layers.Dense(40, input_shape = (None, 12), activation='relu')(sma) L = kr.layers.Concatenate()([La, Lb, Lc]) L = kr.layers.Dense(32, activation='relu')(L) L = kr.layers.Dense(16, activation='relu')(L…
tagged with: keras
score: 3
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/85421898
downvote count: 0
has comment: http://stackoverflow.com/comment/85421388

http://stackoverflow.com/comment/101376639
score: 0
has text: @ClaudioN, Have you solved this issue?. Accessing indices of the current fold in a custom score function for Gridsearch?
type: QuestionComment
comment on: http://stackoverflow.com/q/49246856
type: Comment

http://stackoverflow.com/a/49199145
upvote count: 1
has body: These files obviously do not contain properly formatted json - rather they contain a separate object on each line. To turn them into valid json, you probably want a list of objects, i.e.: [{ "channelType":"TEMPGROUP", ... }, { "channelType":"TEMPGROUP", ... }] You can achieve this by doing: for i in raw_replay_data['data']['video_info']: url3 = i['msgfile'] raw_message_data = urllib.request.urlopen(url3) json_data = [] for line in raw_message_data: json_data.append(json.loads(line)) messages.insert_one(json_data) print(json_data)
has comment: http://stackoverflow.com/comment/85405421
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49198774
has comment: http://stackoverflow.com/comment/85495643
downvote count: 0
has comment: http://stackoverflow.com/comment/85410250

http://stackoverflow.com/a/49185799
type: Answer
score: 0
has body: It is very easy, you just declare a global variable x = True, then in your my_callback is something like if x: x = False return if instance.team_1_score &gt; instance.team_2_score: instance.team_1_point += 2 elif instance.team_2_score &gt; instance.team_1_score: instance.team_2_point += 2 elif instance.team_2_score == instance.team_1_score: instance.team_2_point += 1 instance.team_1_point += 1
answers question: http://stackoverflow.com/q/49185695
has comment: http://stackoverflow.com/comment/85378115
has comment: http://stackoverflow.com/comment/85378226

http://stackoverflow.com/comment/85527584
type: QuestionComment
comment on: http://stackoverflow.com/q/49250890
has text: It was more of trying to understand just how `__new__` works and objects in python work as a whole. I've learnt basic theory behind classes but am looking at projects to see how they implement it, the particular one I was looking at was this [one](https://codingsec.net/2016/05/decoding-ip-layer-python/)
score: 0
type: Comment

http://stackoverflow.com/comment/85423007
has text: You didn't say which Fortran compiler you intend; ifort should be able to vectorize the code you show. That should be significantly faster than minloc() or even findloc() (an f2008 intrinsic). As Vladimir said, you should be able to find numpy implementations which do the same. If num_elements exceeds 100000, you should be able to gain by splitting the array to search in parallel, then finishing by combining the results. If you are doing several hundred small arrays, likewise you should be able to gain by calling your function in multiple threads.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49208730

http://stackoverflow.com/comment/137521945
score: 0
type: AnswerComment
has text: simple and works, thanks!
comment on: http://stackoverflow.com/a/49270188
type: Comment

http://stackoverflow.com/q/49269877
has answer: http://stackoverflow.com/a/49269923
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49269941
tagged with: for-loop
score: 0
has answer: http://stackoverflow.com/a/49269941
has answer: http://stackoverflow.com/a/49269944
possible better answer: http://stackoverflow.com/a/49269923
has answer: http://stackoverflow.com/a/49270015
has answer: http://stackoverflow.com/a/49270417
has title: Python - using multiple lists
type: Question
has answer: http://stackoverflow.com/a/49270903
has body: Why is this program not working? available_toppings = ["mushrooms", "olives", "green peppers", "pepperoni", "pineapple", "extra cheese"] requested_toppings = ['mushrooms', 'olives', 'extra cheese'] if requested_toppings in available_toppings: for requested_topping in requested_toppings: print("Adding " + requested_topping.title() + ".") print("Finalising your order.") else: print("sorry we dont have these toppings") and the output is sorry we dont have these toppings
tagged with: if-statement
tagged with: python
answer count: 6

http://stackoverflow.com/comment/85290328
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49139350
type: Comment
has text: the folder, the path to which I hard coded into the script is a subfolder of the eventual target, with copies of it's files to experiment on, just so I could test the code. Nothing else in there but it's nice to know it can be filtered. Thanks.

http://stackoverflow.com/a/49186402
answers question: http://stackoverflow.com/q/49185980
type: Answer
has body: A powerset is defined as P(s) = {{}, {s_1}, {s_2}, ... {s_1, s_2},.., s}. To implement it in recursion, it is best to use a generator expressions. Also, sets are not hashable in Python, therefore, you will have to create your own set wrapper: class WrapperSet: def __init__(self, *args): self.val = set() if not args else args def __repr__(self): return "{}({})".format(self.__class__.__name__, str(self)) def __str__(self): return '{'+', '.join(map(str, self.val))+'}' def get_result(s): result = list(p(s)) current = sorted([a for i, a in enumerate(result) if a not in result[:i]], key=len) return WrapperSet(*[WrapperSet(), *[WrapperSet(*i) for i in current]]) def p(s, current = []): if len(s) == len(current): yield current else: for i in s: yield [i] if i in current: yield current else: yield from p(s, sorted(current+[i])) Output: print(get_result([1, 2, 3])) Output: WrapperSet({{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}})
score: 0

http://stackoverflow.com/comment/85423530
score: 0
type: AnswerComment
has text: Since English is not my mother tongue either, I just used the name you proposed. You may of course use `ax.es_hermana` or `ax.schwesterachse = True` or whatever you like, just make sure not to overwrite any existing attribute.
type: Comment
comment on: http://stackoverflow.com/a/49208080

http://stackoverflow.com/comment/85296525
type: Comment
comment on: http://stackoverflow.com/a/49145853
type: AnswerComment
has text: AttributeError: ResultSet object has no attribute 'text'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?
score: 0

http://stackoverflow.com/comment/85260681
comment on: http://stackoverflow.com/q/49127554
score: 1
type: QuestionComment
has text: Are you asking us how to build sha-256 hashes from strings? If so, here ya go friend. Don't crack any accounts with this, that would be illegal, mkay? https://www.pythoncentral.io/hashing-strings-with-python/
type: Comment

http://stackoverflow.com/comment/85250541
has text: If you showed us your algorithm, maybe we could show a better way that doesn't need such slicing...
comment on: http://stackoverflow.com/q/49122407
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85332700
comment on: http://stackoverflow.com/q/49163558
score: 0
type: Comment
type: QuestionComment
has text: Which line does it say that on?

http://stackoverflow.com/a/49216777
has comment: http://stackoverflow.com/comment/85442892
downvote count: 1
has comment: http://stackoverflow.com/comment/85442949
score: 1
has body: It's actually quit easy in python with zip. Please refer the code below and check if this is the exact same thing you want: all_text = [['Z1234', 'earth total surface area land'], ['Z1207', 'first north university']] keyword_list = ['earth', 'north'] finaldict = {} for i,item in zip(keyword_list, all_text): finaldict[item[0]] = i print(finaldict)
upvote count: 2
answers question: http://stackoverflow.com/q/49216669
type: Answer

http://stackoverflow.com/a/53621640
score: 0
has body: If you're running this on Windows (like I was), you'll run into an issue with the libraries being compiled on an incompatible OS. You can use an Amazon Linux EC2 instance, or a Cloud9 development instance to build your virtualenv as detailed above. Or, you could just download the pre-compiled wheel files as discussed on this post: https://aws.amazon.com/premiumsupport/knowledge-center/lambda-python-package-compatible/ Essentially, you need to go to the project page on https://pypi.org and download the files named like the following: For Python 2.7: module-name-version-cp27-cp27mu-manylinux1_x86_64.whl For Python 3.6: module-name-version-cp36-cp36m-manylinux1_x86_64.whl Then unzip the .whl files to your project directory and re-zip the contents together with your lambda code.
type: Answer
answers question: http://stackoverflow.com/q/49276118

http://stackoverflow.com/comment/85299445
type: QuestionComment
has text: how are you gonna decide which /n is between string and which /n is surrounding string? Your algorithm will depend much on the kind of string. It will be better if you provide a good case of the string you are trying to format.
type: Comment
comment on: http://stackoverflow.com/q/49147276
score: 0

http://stackoverflow.com/comment/85305910
has text: Phew! What an answer.
type: Comment
comment on: http://stackoverflow.com/a/49150858
score: 0
type: AnswerComment

http://stackoverflow.com/q/49136897
type: Question
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/49211807
has answer: http://stackoverflow.com/a/49211807
has body: I have a Django app that has an Angular 5 frontend connected by Django REST. Currently deployment only works with hashing disabled (--output-hashing none), because in uls.py I can only access a copy of index.html ("ang_home.html") in the template folder. ng build --prod --output-path .../backend/src/static/ --watch --output-hashing none --aot=false --env=prod I would now like to change my urls.py so that the newly created index.html in the django static folder is accessed directly so that I can use hashing. url(r'^.*', TemplateView.as_view(template_name="ang_home.html"), name='home'), The current solution is annoying because I would have to copy the index.html code into ang_home.html manually with every change. Shortly: I want url(r'^.*', index.html in the static folder), name='home'),
type: AnsweredQuestion
tagged with: angular
score: 0
has title: How to build Angular 5 to Django static folder with hashing enabled
answer count: 1
has comment: http://stackoverflow.com/comment/85279664
has comment: http://stackoverflow.com/comment/85278976

http://stackoverflow.com/comment/85415486
has text: @juanpa.arrivillaga comp sci teacher. it's very frustrating.
comment on: http://stackoverflow.com/q/49205082
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49156969
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85318710
has title: Error in launching IE with Python-Selenium while the exact same script works fine with Java-Selenium
tagged with: internet-explorer
tagged with: python
accepted answer: http://stackoverflow.com/a/49157105
type: AnsweredQuestion
has body: I get the following error when I try to launch the Internet explorer using Selenium. My code is: from selenium import webdriver driver = webdriver.Ie('C:\\workspace\\IEDriverServer.exe') driver.get("http://wwww.facebook.com") The error I get is Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. Combination that does not work: Python/PyCharm while the combination that works : Java/Eclipse IE explorer driver is the same single file in both cases. It is on same PC
downvote count: 0
tagged with: automated-tests
score: 1
upvote count: 1
tagged with: java
answer count: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/85318789
has answer: http://stackoverflow.com/a/49157105

http://stackoverflow.com/comment/85357933
type: QuestionComment
has text: some similar question in `r` language is found... in this [link](https://stackoverflow.com/questions/27442506/find-nearest-points-of-latitude-and-longitude-from-different-data-sets-with-diff)
score: 0
comment on: http://stackoverflow.com/q/49176252
type: Comment

http://stackoverflow.com/comment/85412305
has text: @abarnert You're totally right, but it's never too late to help a lost soul to escape from the Dark Side. Maybe he'll reconsider and go Linux? Then **os.fork**.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49203359

http://stackoverflow.com/comment/85250929
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49122033
has text: "but the value is already converted into list" No it's not. N is a generator.
type: Comment

http://stackoverflow.com/a/49204892
type: AcceptedAnswer
score: 6
has body: Okay, the first function you wrote is an example of Exhaustive Search where you are exploring every possible branch that can be formed from a set of whole numbers up to n (which you have passed in the argument and you are using for loop for that). To explain you the time complexity I am going to consider the recursion stack as a Tree (to represent a recursive function call stack you can either use a stack or use an n-ary Tree) Let's call you first function F1: F1(3), now three branches will be formed for each number in the set S (set is the whole numbers up to n). I have taken n = 3, coz it will be easy for me to make the diagram for it. You can try will other larger numbers and observe the recursion call stack. 3 /| \ 0 1 2 ----&gt; the leftmost node is returns 0 coz (n==0) it's the base case | /\ 0 0 1 | 0 ----&gt; returns 0 So here you have explored every possibility branches. If you try to write the recursive equation for the above problem then: T(n) = 1; n is 0 = T(n-1) + T(n-2) + T(n-3) + ... + T(1); otherwise Here, T(n-1) = T(n-2) + T(n-3) + ... T(1). So, T(n-1) + T(n-2) + T(n-3) + ... + T(1) = T(n-1) + T(n-1) So, the Recursive equation becomes: T(n) = 1; n is 0 = 2*T(n-1); otherwise Now you can easily solve this recurrence relation (or use can use Masters theorem for the fast solution). You will get the time complexity as O(2^n). Solving the recurrence relation: T(n) = 2T(n-1) = 2(2T(n-1-1) = 4T(n-2) = 4(2T(n-3) = 8T(n-3) = 2^k T(n-k), for some integer `k` ----&gt; equation 1 Now we are given the base case where n is 0, so let, n-k = 0 , i.e. k = n; Put k = n in equation 1, T(n) = 2^n * T(n-n) = 2^n * T(0) = 2^n * 1; // as T(0) is 1 = 2^n So, T.C = O(2^n) So this is how you can get the time complexity for your first function. Next, if you observe the recursion Tree formed above (each node in the tree is a subproblem of the main problem), you will see that the nodes are repeating (i.e. the subproblems are repeating). So you have used a memory in your second f…
has comment: http://stackoverflow.com/comment/85432220
has comment: http://stackoverflow.com/comment/85431829
has comment: http://stackoverflow.com/comment/85425741
has comment: http://stackoverflow.com/comment/85431922
upvote count: 6
answers question: http://stackoverflow.com/q/49204502
type: Answer
has comment: http://stackoverflow.com/comment/85431848
has comment: http://stackoverflow.com/comment/85432025
has comment: http://stackoverflow.com/comment/85431853
accepted answer of: http://stackoverflow.com/q/49204502
downvote count: 0

http://stackoverflow.com/q/49183719
downvote count: 0
upvote count: 1
type: UnansweredQuestion
answer count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49183936
has title: glove = pickle.load(f) EOFError: Ran out of input
score: 1
tagged with: pickle
tagged with: python
has body: So here: glove_path = './embeddings/glove_{}_{}.pkl'.format(dataset,mode) if(os.path.isfile(glove_path)): print("Reusing glove dictionary to save time") #with open(glove_path,'r') as f: with open(glove_path, 'rb') as f: #python 3 for pickle byte size object is needed not str glove = pickle.load(f) save = False If I try with open(glove_path,'r') as f: I get the following error: Reusing glove dictionary to save time Traceback (most recent call last): File "prepare.py", line 315, in &lt;module&gt; glove = pickle.load(f) TypeError: a bytes-like object is required, not 'str' and if I try with open(glove_path, 'rb') as f: #python 3 for pickle byte size object is needed not str I get the following error: Reusing glove dictionary to save time Traceback (most recent call last): File "prepare.py", line 315, in &lt;module&gt; glove = pickle.load(f) EOFError: Ran out of input Can you please guide how to fix this? I am using the code from https://github.com/vanzytay/pytorch_sentiment_rnn and using Anaconda Python 3.6. I have imported pickle like import six; from six.moves import cPickle as pickle #import compatability with Python 2 using six while it was originally imported as: import cPickle as pickle #python 2
tagged with: nlp
tagged with: python-3.x

http://stackoverflow.com/comment/85513994
has text: Many Thanks for your help
comment on: http://stackoverflow.com/a/49255255
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49177841
score: 5
downvote count: 0
type: Answer
has body: To my knowledge, such a function does not exist natively. You can use NumPy (credit to @DSM): step = 0.2 df['B'] = np.ceil((df['A'].values / step)) * step A less performant version via pd.Series.apply: import pandas as pd import math df = pd.DataFrame({'A': [1, 1.3, 1.5, 1,6, 1.7, 2]}) def ceil(x, step=1): return step * math.ceil(x/step) df['B'] = df['A'].apply(ceil, step=0.2) # A B # 0 1.0 1.0 # 1 1.3 1.4 # 2 1.5 1.6 # 3 1.0 1.0 # 4 6.0 6.0 # 5 1.7 1.8 # 6 2.0 2.0
answers question: http://stackoverflow.com/q/49174657
has comment: http://stackoverflow.com/comment/85362145
upvote count: 5

http://stackoverflow.com/comment/85619635
has text: That's a real bummer, and means its barely any better than using `setUpClass()` and `tearDownClass()`. I see my question did not explicitly state my desire to have one test class per file, so I'll go edit that.
score: 2
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49296511

http://stackoverflow.com/comment/85378845
has text: @Wen Thanks, this is a good solution.
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49186326

http://stackoverflow.com/q/49200523
tagged with: python-3.x
has body: Suppose we have the following class: class Klass: def __init__(self): self.member_var1 = 1 def __getattribute__(self, attr_name): print('Klass.__getattribute__') # STATEMENT OF INTEREST return object.__getattribute__(self, attr_name) # Now we instantiate the class, and access its members: obj = Klass() print('obj.member_var1 == ', obj.member_var1) The Desired Behavior: Only one print statement is to be executed. The terminal output should look like this: Klass.__getattribute__ Reproducing the Error: Run the code given at the beginning of this post at pythontutor.com copy and paste code into the online editor click the Visualize Execution button click the Last&gt;&gt; button The terminal output looks like this: Klass.__getattribute__ Klass.__getattribute__ Klass.__getattribute__ Klass.__getattribute__ [...] Klass.__getattribute__ Klass.__getattribute__ Klass.__getattribute__ Klass.__getattribute__ One can also reproduce the error by running the code in the IDE named Spyder OS : Windows IDE : Spyder 3.2.7 Python : 3.6.4 64bits Qt : 5.9.3 PyQt5 : 5.9.2 IPython &gt;=4.0 : 6.2.1 (OK) jedi &gt;=0.9.0 : 0.11.1 (OK) nbconvert &gt;=4.0 : 5.3.1 (OK) pycodestyle &gt;=2.3: 2.3.1 (OK) pyflakes &gt;=0.6.0 : 1.6.0 (OK) pygments &gt;=2.0 : 2.2.0 (OK) pylint &gt;=0.25 : 1.8.2 (OK) qtconsole &gt;=4.2.0: 4.3.1 (OK) rope &gt;=0.9.4 : 0.10.7 (OK) sphinx &gt;=0.6.6 : 1.7.1 (OK) Behavior can Difffer for Functions other than print Consider the following: class CounterStream: def __init__(self): self.d = dict() def __call__(self, *args): for arg in args: self.d[arg] = 1 + self.d.get(arg, 0) def report(self): print('CounterStream says:') for key in self.d: print(str(key).ljust(20), ' was sent to stream\n', str(self.d[key]).rjust(5), ' times\n') foo = CounterStream() class Klass: def __init__(self): self.member_var1 = 1 def __getattribute__(self, attr_name): #### print('Klass.__getattribute__') foo('Klass.__getattribute__') return object.__getattribute__(self, attr_name) # Now we instantiate …
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85406320
tagged with: overriding
has comment: http://stackoverflow.com/comment/85406380
tagged with: python
tagged with: getattribute
score: 0
tagged with: printing
upvote count: 1
has answer: http://stackoverflow.com/a/49200702
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/85415138
has title: Why are print statements inside __getattribute__ being called an unusual number of times?
favorite count: 0
type: Question

http://stackoverflow.com/a/49222091
accepted answer of: http://stackoverflow.com/q/49221743
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49221743
has body: Your file has new line characters at the end of some lines. This causes line breaks in between the concatenated text in the out variable. Before appending it into keys, strip off the new line characters. There are functions that directly give you a list by reading a file. Python Docs are an amazing source for finding such functions. Keys = [] Reader = open("Keywords.txt", "r") for line in Reader: Keys.append(line.rstrip('\n'))
has comment: http://stackoverflow.com/comment/85448149
type: Answer
score: 0

http://stackoverflow.com/q/49161570
has title: Plot in python without matplotlib
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85328856
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85328948
tagged with: python
has comment: http://stackoverflow.com/comment/85329388
score: 0
answer count: 0
tagged with: jython
has body: I'm writing a program for TopSpin, an NMR processing software from Bruker. TopSpin runs the python scripts in it's own environment using jython. The python version it returns is 2.5.* (I don't remember the last one). import sys print(sys.version) &gt;&gt; 2.5.* As the code is executed in it's own environment, I cannot update the version of python/jython and I also cannot install missing packages. For my current project I would need a functionality to plot the values of two lists. The first list on the x-axis and the second one on the y-axis. For this task I wanted to use matplotlib's function plot(xlist, ylist). Unfortunately TopSpin throws an error at me, saying that the package matplotlib does not exist. As I can't install the package (or at least I have no idea how I should), I now need a workaround. Is there a way I could call a python script that runs in the normal environment of my computer (like idle) where python 3.6.3 and matplotlib are installed? Ideally this could generate the plot and ship it back to the TopSpin python program. Or is there an other workaround that enables me to plot my data and show it to the user/save it on the disk, that does not rely on fancy or new packages?
type: Question

http://stackoverflow.com/comment/85270864
has text: Is `action.owner` a string, or is it some sort of custom user class object?
type: QuestionComment
comment on: http://stackoverflow.com/q/49132703
score: 1
type: Comment

http://stackoverflow.com/a/49241596
answers question: http://stackoverflow.com/q/49241502
has comment: http://stackoverflow.com/comment/85512770
type: Answer
has comment: http://stackoverflow.com/comment/129319824
has comment: http://stackoverflow.com/comment/85487070
has comment: http://stackoverflow.com/comment/85513313
has comment: http://stackoverflow.com/comment/85487109
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85491401
has comment: http://stackoverflow.com/comment/85487251
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49241502
has body: You can do that with tf.gather_nd: idx = tf.stack([tf.range(tf.shape(a)[0], dtype=a.dtype), a], axis=1) p_selected = tf.gather_nd(p_matrix, idx) Each row in idx contains the "coordinates" of each element to retrieve, like [[0, a[0]], [1, a[1]], ...]. Alternatively batch_dims argument lets you omit those leading location dimensions from the idx idx = tf.expand_dims(a, axis=1) p_selected = tf.gather_nd(batch_dims=p_matrix, indices=idx, batch_dims=1)
has comment: http://stackoverflow.com/comment/85487353
has comment: http://stackoverflow.com/comment/85512669

http://stackoverflow.com/comment/85504541
type: Comment
comment on: http://stackoverflow.com/q/49246912
type: QuestionComment
score: 0
has text: Downloading the SCIP OPT Suite is not enough. You also have to `make` and `make install` it, see [these instructions](http://scip.zib.de/doc-5.0.1/html/CMAKE.php). Good luck

http://stackoverflow.com/a/49132483
answers question: http://stackoverflow.com/q/49131940
type: Answer
accepted answer of: http://stackoverflow.com/q/49131940
has comment: http://stackoverflow.com/comment/85271968
has comment: http://stackoverflow.com/comment/85277723
has comment: http://stackoverflow.com/comment/85272366
has comment: http://stackoverflow.com/comment/85278397
score: 0
has comment: http://stackoverflow.com/comment/85277510
has comment: http://stackoverflow.com/comment/85276496
has comment: http://stackoverflow.com/comment/85274719
has comment: http://stackoverflow.com/comment/85271437
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85271373
has comment: http://stackoverflow.com/comment/85275439
has comment: http://stackoverflow.com/comment/85272078
has comment: http://stackoverflow.com/comment/85277090
has comment: http://stackoverflow.com/comment/85271299
has comment: http://stackoverflow.com/comment/85277616
has body: We'll save the message that we sent, and then use client.logs_from to look at all the messages that come after that message. async def background_loop(): await client.wait_until_ready() last_message = None messages = deepcopy(messages_list) cleanmessages = deepcopy(messages_list) channel = client.get_channel("Channel_ID") while not client.is_closed: if not messages: messages = deepcopy(cleanmessages) if len([x async for x in client.logs_from(channel, limit=2, after=last_message)]) &gt; 1: content = messages.pop(random.randrange(0, len(messages))) last_message = await client.send_message(channel, content) await asyncio.sleep(21600)
has comment: http://stackoverflow.com/comment/85278045
has comment: http://stackoverflow.com/comment/85271872
has comment: http://stackoverflow.com/comment/85276688
has comment: http://stackoverflow.com/comment/85277951

http://stackoverflow.com/comment/85457010
comment on: http://stackoverflow.com/q/49226574
type: Comment
type: QuestionComment
has text: The problem is that you're calling `update` on the dict, `n`, not on the set `n[i]`. The `update` method on dicts requires either a dict, or a sequence of key-value pairs, not just a sequence of individual values. The `update` method on sets takes a sequence of individual values. And, more importantly, the set is what you wanted to update.
score: 0

http://stackoverflow.com/a/49289903
score: 3
answers question: http://stackoverflow.com/q/49268647
type: Answer
has body: Simple spectrum The simplest way to get an amplitude vs. frequency relationship for an evenly sampled signal x is to compute its Discrete Fourier Transform through the efficient Fast Fourier Transform algorithm. Given a signal x sampled at a regular sampling rate fs, you could do this with: import numpy as np Xf_mag = np.abs(np.fft.fft(x)) Each index of the Xf_mag array will then contain the amplitude of a frequency bin whose frequency is given by index * fs/len(Xf_mag). These frequencies can be conveniently computed using: freqs = np.fft.fftfreq(len(Xf_mag), d=1.0/fs) Finally the spectrum could be plotted using matplotlib: import matplotlib.pyplot as plt plt.plot(freqs, Xf_mag) Refining the spectrum estimation You might notice that the spectrum obtained with the simple FFT approach yields a spectrum which appears very noisy (ie. with lots of spikes). To get a more accurate estimate, a more sophisticated approach would be to compute a power spectrum estimate using techniques such as periodograms (implemented by scipy.signal.periodogram) and Welch's method (implemented by scipy.signal.welch). Note however that in these cases the computed spectrum is proportional to the square of the amplitudes, so that its square root provide an estimate of the Root-Mean-Squared (RMS) amplitudes. Going back to the signal x sampled at a regular sampling rate fs, such a power spectrum estimate could thus be obtained as described in the samples from scipy's documentation with the following: f, Pxx = signal.periodogram(x, fs) A_rms = np.sqrt(Pxx) The corresponding frequencies f are also calculated in the process, so you could then plot the result with plt.plot(f, A_rms) Using scipy.signal.welch is quite similar, but uses a slightly different implementation which provides a different accuracy/resolution tradeoff.
upvote count: 3
downvote count: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49268647

http://stackoverflow.com/a/49165069
accepted answer of: http://stackoverflow.com/q/49164985
type: Answer
answers question: http://stackoverflow.com/q/49164985
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/85361821
downvote count: 0
has comment: http://stackoverflow.com/comment/85361795
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85361071
has body: You can use __import__: Here is test.py: # test.py import sys filename = sys.argv[1] f = __import__(filename[:-3]) # This removes the `.py` extension f.test() Here is test2.py: # test2.py def test(): print('hello world') Running the following the command line: python test.py test2.py Gives the following output: hello world If you really want to load everything in local scope, you have to do the following: filename = sys.argv[1] f = __import__(filename[:-3], globals(), locals(), ['*']) for k in dir(f): locals()[k] = getattr(f, k) test()

http://stackoverflow.com/comment/85426507
comment on: http://stackoverflow.com/q/49210834
has text: @user202729 nobody hinders users with 1 rep to try to answer things - it is possible to gain 50 rep and then be able to comment - not easy, just possible :) and commments do not get you any rep as is, so experienced users giving hints might help less experienced ones to get to an answer and to rep.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49167643
downvote count: 0
has comment: http://stackoverflow.com/comment/85341034
has body: I think you should use warnings module to deal with it import warnings warnings.warn("once") The above code will print warnings only once. You can explore the warnings module here
answers question: http://stackoverflow.com/q/49167472
upvote count: 2
type: Answer
score: 2

http://stackoverflow.com/a/49211057
score: 0
type: Answer
answers question: http://stackoverflow.com/q/49210523
has body: Tkinter is an inbuilt GUI module for python. Your computer is likely to be suspicious of any file not from a verified publisher.

http://stackoverflow.com/a/49204010
answers question: http://stackoverflow.com/q/49203951
type: AcceptedAnswer
downvote count: 0
upvote count: 8
has body: Not sure if apply can be avoided here df.apply(lambda x: pd.to_numeric(x, errors = 'coerce')).dropna() 0 1 2 3 4 5 6 7 0 1 2017.0 0 321 3 20 42 18.0 3 4 1811.0 0 822 8 13 65 18.0
type: Answer
accepted answer of: http://stackoverflow.com/q/49203951
score: 8
has comment: http://stackoverflow.com/comment/85413764

http://stackoverflow.com/comment/85434559
has text: You can always pass column names as kwargs in the apply and then use `grp[MY_COL_NAME]` in your function for the that flexibility.
type: Comment
comment on: http://stackoverflow.com/a/49203683
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85436200
has text: Just one last question I promise. How do I extract the text from the button “add to cart” and the url for the pictures of each product? Thanks!
type: AnswerComment
comment on: http://stackoverflow.com/a/49195889
score: 0
type: Comment

http://stackoverflow.com/q/49175110
type: Question
tagged with: google-sheets-api
tagged with: oauth
has title: Cannot Authorize App Engine with Drive API
tagged with: google-app-engine
tagged with: python
score: 2
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/49260483
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49260483
has body: I'm trying to get a list of Drive files on my App Engine. The app is not for consumers other than the app so I'm not implementing OAuth2 for user sign in. I have enabled Drive in the GCP project and the compute instance is an owner. However, I receive the following error: Traceback (most recent call last): File "test.py", line 5, in &lt;module&gt; credentials = app_engine.Credentials(scopes=SCOPES) File "/usr/local/lib/python2.7/site-packages/google/auth/app_engine.py", line 105, in __init__ 'The App Engine APIs are not available.') EnvironmentError: The App Engine APIs are not available. Here is my code (based off this tutorial: https://developers.google.com/api-client-library/python/auth/service-accounts): from google.auth import app_engine import googleapiclient.discovery SCOPES = ['https://www.googleapis.com/auth/drive'] credentials = app_engine.Credentials(scopes=SCOPES) project_id = 'project-id' service = googleapiclient.discovery.build('drive', 'v3',credentials=credentials) bucket = service.files().list(project=project_id).execute() print bucket Something is going on with my credentials and I'm unsure what it is. Tldr; How do I authorize my App Engine Flask App (Standard) to consume Google APIs, including Google Sheets, Drive, BigQuery and others. Keep in mind, this is a server-to-server job. No users are logging in other than the app itself. Ultimately, I'm trying to have values in Google Sheets synced with BigQuery (the app needs Drive and BQ permissions) that will then get pushed to DataStore. If you have suggestions on how to fix it, ELI5.
favorite count: 0

http://stackoverflow.com/comment/85508698
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49252604
score: 0
has text: Conceringing your PS: then you probably should have read that [tour] when signing up. It directs you to the [Help], where you can find [How do I format my posts using Markdown or HTML?](https://stackoverflow.com/help/formatting). There was also a huge yellow box containing basic formatting help – *including* how to format code – and a preview while you were entering your question.

http://stackoverflow.com/comment/85393231
comment on: http://stackoverflow.com/q/49133225
type: QuestionComment
type: Comment
has text: @UsmanMutawakil So please share some snippet, python, node, java, i take it all ;) . I know it coz if i print the accessKey , its a different one every time lambda is ran, pretty much couple of times per seconds
score: 0

http://stackoverflow.com/comment/85353614
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49173597
score: 0
has text: Is it correct? I cannot see diference with input.

http://stackoverflow.com/q/49267916
answer count: 0
tagged with: singleton
has comment: http://stackoverflow.com/comment/85539367
type: Question
has title: Module as a singleton in Python
has body: There are quite a few posts on the web where ppl seem to propose using a module as a singleton in Python. Could you please help me understand how to do that? Apparently I am doing it wrong. I writing an application and I want to keep "shared state" as a singleton. This a very basic example of what I am doing singleton.py state = [] and on another file: a.py import singleton singleton.state.append("a") print(singleton.state) and the print command in a.py outputs ['a'] which is what we expect. Then if there is a module b.py that looks like b.py import singleton singleton.state.append("b") print(singleton.state) the print command will give ['b'] which is expected but not what I was hoping for if I had a singleton. I was hoping for something like [a,b]. Ofcourse any other ideas on best practices to keep shared information are highly welcome
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85539410
tagged with: python
score: 0

http://stackoverflow.com/a/49225939
downvote count: 0
upvote count: 1
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49225177
has body: You have a lot of issues with your question: 1) Your code is not properly indented 2) You've intentionally pasted a lot of irrelevant text into your question. 3) You are not providing a stack trace of the error Your code problem is that this line: print(number +1, ") Name: ", fines[number][0]," Amount Over Limit: $", fines[number][1] Does not have a closing parens ) at the end.

http://stackoverflow.com/a/49248618
score: 17
answers question: http://stackoverflow.com/q/49248551
downvote count: 0
type: AcceptedAnswer
upvote count: 17
has body: A list comprehension should do the job, no need for filter(). &gt;&gt;&gt; dic_of_dics = {1: {"a": "A"}, 2: {"b": "B"}, 3: {"c": "C"}} &gt;&gt;&gt; list_of_dics = [value for value in dic_of_dics.values()] &gt;&gt;&gt;list_of_dics [{'a': 'A'}, {'b': 'B'}, {'c': 'C'}]
accepted answer of: http://stackoverflow.com/q/49248551
type: Answer

http://stackoverflow.com/comment/87551021
has text: what is that `print()` doing?
type: Comment
comment on: http://stackoverflow.com/a/49271337
score: 0
type: AnswerComment

http://stackoverflow.com/a/49271744
has body: It is possible if append only one row and use setting with enlargement , but if use concat or append get new DataFrame object (different ids): from pandas.compat import StringIO def test(): text_data = """bcd 11 abc 12 def 13 ghi 14""" df = pd.read_csv(StringIO(text_data), header=None, sep="\s+", names=["txt", "num"]) df2 = pd.DataFrame("pqr", 1, columns=["txt", "num"]) print ("id is =",id(df), "\n" ,df) df.loc[len(df.index)] = df2.iloc[0] print ("id is =", id(df), "\n", df) test() id is = 243587168 txt num 0 bcd 11 1 abc 12 2 def 13 3 ghi 14 id is = 243587168 txt num 0 bcd 11 1 abc 12 2 def 13 3 ghi 14 4 pqr 1
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
answers question: http://stackoverflow.com/q/49271638
accepted answer of: http://stackoverflow.com/q/49271638
type: Answer

http://stackoverflow.com/comment/85250801
has text: But if you print it, you get a small square. Any explanations?
comment on: http://stackoverflow.com/a/49122688
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/49265666
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85535121
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/85535035
has comment: http://stackoverflow.com/comment/85534919
has title: All urls not showing up on django.rest_framework documentation
has comment: http://stackoverflow.com/comment/85535107
has body: This is my main urls.py urlpatterns = [ url(r'^', include_docs_urls(title='Foot The Ball API')), url(r'^admin/', admin.site.urls), url(r'^api/v1/aggregator/', include('aggregator.urls')), url(r'^api/v1/bouncer/', include('bouncer.urls')), ] These are the urls in bouncer.urls urlpatterns = [ url(r'^login/$', LoginView.as_view(), name='login'), url(r'^logout/$', LogoutView.as_view(), name='logout'), url(r'^register/(?P&lt;location_id&gt;[\w.-]+)/$', RegisterView.as_view(), name='register'), url(r'^location/$', LocationView.as_view(), name='location'), ] I'm using rest_framework.documentation. Strangely only login and logout view show up in the documentation home page. These are the relevant views that are routed to by the urls. This is the login view class LoginView(views.APIView): def post(self, request): user = authenticate( email=request.data.get("email"), password=request.data.get("password") ) if not user: return Response({ 'status': 'Unauthorized', 'message': 'Email or password incorrect', }, status=status.HTTP_401_UNAUTHORIZED) login(request, user) return Response(UserSerializer(user).data) This is the logout view, class LogoutView(views.APIView): def get(self, request): logout(request) return Response({}, status=status.HTTP_204_NO_CONTENT) This is the Register View, class RegisterView(views.APIView): def get_or_create(self, request, **kwargs): try: user = User.objects.get(email=request.data.get("email")) return Response(user, status=status.HTTP_200_OK) except User.DoesNotExist: location = Location.objects.get(id=kwargs.get('location_id')) serializer = UserSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() user.location = location user.save() subject = "Please Activate Your FootTheBall Account!" token = self._generate() link = HOST + PREFIX + str(user.id) + SUFFIX + token message = 'Please use the following link to activate your account.\n\n{}'.format(link) from_email = settings.EMAIL_HOST_USER to_list = [user.email, 'soumasish@foo…
score: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85535150
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49266177
has comment: http://stackoverflow.com/comment/85535137
tagged with: django
answer count: 2
has comment: http://stackoverflow.com/comment/85535277
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49266521

http://stackoverflow.com/comment/85558568
score: 0
type: AnswerComment
has text: It does seem like it is obligatory to reference some form of index at some point though to return an actual value, rather than an array or series.
type: Comment
comment on: http://stackoverflow.com/a/49277927

http://stackoverflow.com/q/49246806
type: Question
has title: Empty .csv file after python script export
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85497552
tagged with: export-to-csv
score: 2
upvote count: 2
has body: File is showing as being "modified" but remains 0kb and empty. Using the following code: import csv from craigslist import CraigslistForSale cl_f = CraigslistForSale (site = 'boston', area = 'gbs', category = 'sys', filters = {'min_price':5, 'max_price':300, 'has_image':True, 'query':"by owner",'query':"imac"}) for result in cl_f.get_results(sort_by='newest',limit=5): print result with open('CL-iMac.csv', 'wb') as f: writer = csv.writer(f, delimiter=',') Read through other "similar" questions but still unclear on how to resolve this. e/print result after adding for result in cl_f.get_results(sort_by='newest',limit=5): writer.writerow(result) : {'name': u'iMac Mid 2009', 'has_image': True, 'url': u'https://boston.craigslist.org/gbs/sys/d/imac-mid-2009/6504630631.html', 'has_map': True, 'price': u'$190', 'geotag': None, 'where': u'Bedford', 'id': u'6504630631', 'datetime': u'2018-03-12 21:03'} {'name': u'Apple - iMac Model A1311', 'has_image': True, 'url': u'https://boston.craigslist.org/gbs/sys/d/apple-imac-model-a1311/6525426093.html', 'has_map': True, 'price': u'$180', 'geotag': None, 'where': u'BOSTON', 'id': u'6525426093', 'datetime': u'2018-03-12 19:57'} {'name': u'Apple iMac 5.1 Model A1208 17" All-in-one', 'has_image': True, 'url': u'https://boston.craigslist.org/gbs/sys/d/apple-imac-51-model-aall-in/6525156610.html', 'has_map': True, 'price': u'$80', 'geotag': None, 'where': u'HYDE PARK', 'id': u'6525156610', 'datetime': u'2018-03-12 13:43'} {'name': u'imac computer 20 inch', 'has_image': True, 'url': u'https://boston.craigslist.org/gbs/sys/d/imac-computer-20-inch/6488426996.html', 'has_map': True, 'price': u'$210', 'geotag': None, 'where': u'Medford', 'id': u'6488426996', 'datetime': u'2018-03-08 11:17'} {'name': u'Apple Magic Mouse &amp; Keyboard Set', 'has_image': True, 'url': u'https://boston.craigslist.org/gbs/sys/d/apple-magic-mouse-keyboard-set/6521325579.html', 'has_map': True, 'price': u'$80', 'geotag': None, 'where': u'Malden', 'id': u'6521325579', …
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85497593
has answer: http://stackoverflow.com/a/49247010

http://stackoverflow.com/q/49180822
has comment: http://stackoverflow.com/comment/85369937
has answer: http://stackoverflow.com/a/49184580
upvote count: 2
has comment: http://stackoverflow.com/comment/85367527
has title: Missing textual labels along x-axis when using Matplotlib (line-plot) with data from a Pandas dataframe
tagged with: matplotlib
tagged with: python
has body: I am trying to plot data from a Pandas dataframe that is created by importing data from a CSV. However in the plot not every label is displayed along the x-axis, the plot only shows 5 labels along the x-axis. I have a total of 22 textbased labels, which are all supposed to be shown along the x-axis as tickmarks/labels. These labels correspond to the entries in the column in the dataframe with the name Category. For each Line in the Line column of the dataframe a separate line in the plot is created. And the Amount columns in the dataframe contains the y-values. I am sure there is a easy tweak for this, trying ax.set_xticks(np.arange(len(21)) and plt.xticks( arange(21) ) did not function, maybe because the labels are textbased, not numbers? EDIT 2 I had some trouble with the initial code after changing computer with another software setup. Now I got another version of the code and CSV that I got to run without problems that actually plots a graph. Now back to the initial problem, as can be seen from the attached picture only a few of the categories (gts, jma, yja, lre, fgg) are displayed as labels along the x-axis (I want all 22 categories to be displayed along the x-axis in full text): Here is the code that I used for plotting that doesn't display all x-labels: import pandas as pd import matplotlib.pyplot as plt df=pd.read_csv("import.csv", names=["Category", "Line", "Amount"], encoding="iso-8859-1") fig, ax = plt.subplots(1,1); df.groupby("Category").plot(x="Line", y="Amount", ax=ax) plt.legend([v[0] for v in df.groupby('Category')['Category']], bbox_to_anchor=(1.1, 0.5)) plt.xlabel('Category') plt.ylabel('Amount') for line in ax.lines: line.set_linewidth(0.5) The CSV contents look as follows, I didn't post the whole file as there are many lines. I believe this should be enough to reproduce the problem (of course I can put more if the plot doesn't work without). The first column is the Line-column, the second column corresponds to the Category-column and the third …
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85369463
has comment: http://stackoverflow.com/comment/85370055
linked to: http://stackoverflow.com/q/20109391
answer count: 1
score: 1
downvote count: 1
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/49184580

http://stackoverflow.com/q/49168090
has answer: http://stackoverflow.com/a/49168116
tagged with: list
score: 0
has answer: http://stackoverflow.com/a/49169232
answer count: 2
has body: I tried the below code to write a list to csv file, but it always shows the error: a bytes-like object is required, not 'str' Below is the code: import csv a=['a','b','c'] with open(r"result.csv",'wb') as resultFile: writer = csv.writer(resultFile, lineterminator='\n') for i in a: writer.writerows(i)
has comment: http://stackoverflow.com/comment/85341399
type: Question
has title: how to write a list into csv file
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/34283178
tagged with: python

http://stackoverflow.com/comment/85293773
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49143455
has text: This solved it, many thanks! Seems pretty basic now but i didn't know about AJAX at all, it all kind of makes sense now. For the record: 1. I created a view for '/c_value' so that it 'my_site/c_value' answered a JSON with the relevant data from the server 2. Installed jQuery and then used AJAX to get the previously said relevant info from '/c_value' 3. Insterted this AJAX module into the function from the timer i specified before with setInterval Thanks again!
type: Comment

http://stackoverflow.com/q/49205577
upvote count: 0
has comment: http://stackoverflow.com/comment/85416356
accepted answer: http://stackoverflow.com/a/49205614
has title: I'm trying to do simple multiplication in order to afterwards place it in a variable
tagged with: python
has comment: http://stackoverflow.com/comment/85433231
answer count: 1
has comment: http://stackoverflow.com/comment/85416417
has comment: http://stackoverflow.com/comment/85433257
type: Question
has body: code: if item_id == 1: price = int(500) Quantity = int(input("How much do you want?")) total = Quantity * price if total &lt; money: print("You have successfully bought this item.") money - total Just saying, if this helps, I use repl.it, an online code environment.
type: AnsweredQuestion
tagged with: math
has comment: http://stackoverflow.com/comment/85416388
downvote count: 1
has answer: http://stackoverflow.com/a/49205614
has comment: http://stackoverflow.com/comment/85416437
score: -1
favorite count: 0
has comment: http://stackoverflow.com/comment/85433207
has comment: http://stackoverflow.com/comment/85416401
has comment: http://stackoverflow.com/comment/85416405

http://stackoverflow.com/comment/112394172
has text: OP's question was for Python.
score: 4
type: AnswerComment
comment on: http://stackoverflow.com/a/63559936
type: Comment

http://stackoverflow.com/a/49201945
type: Answer
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/49201897
downvote count: 0
has body: You can do: result = sum(v["amount"] for v in school.values())

http://stackoverflow.com/q/49187041
type: Question
tagged with: python-3.x
has answer: http://stackoverflow.com/a/49187157
answer count: 2
has title: Convert Time part from DateTime in Seconds
upvote count: 2
has comment: http://stackoverflow.com/comment/85379468
downvote count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/49187221
linked to: http://stackoverflow.com/q/48129251
linked to: http://stackoverflow.com/q/19681703
has answer: http://stackoverflow.com/a/49187221
type: AnsweredQuestion
score: 2
tagged with: pandas
has body: I am new in python. I have a column of datatime data. Now I want to create a new column with only time part of datetime in seconds. my first row data is 2018-08-03 10:53:00 and I want to convert the 10:53:00 in seconds e.g 39180 want to store in new column. My functionality is get the mean time from given datetime object. date can vary but I want mean time only.
has comment: http://stackoverflow.com/comment/85379612
accepted answer: http://stackoverflow.com/a/49187157
favorite count: 0

http://stackoverflow.com/a/49228195
type: Answer
has comment: http://stackoverflow.com/comment/85460086
has comment: http://stackoverflow.com/comment/85461487
upvote count: 0
downvote count: 2
has body: np.dot(np.array([[1,2]]) is matrix 2D https://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html
answers question: http://stackoverflow.com/q/49228144
score: -2

http://stackoverflow.com/q/49216635
tagged with: python-3.x
answer count: 2
possible better answer: http://stackoverflow.com/a/49216728
upvote count: 0
has comment: http://stackoverflow.com/comment/85437321
has comment: http://stackoverflow.com/comment/85437787
has comment: http://stackoverflow.com/comment/85460355
tagged with: python
has body: Sorry for this naive question. I'm trying to make this code a bit shorter, since it seems cumbersome to write this entire line out. Are there any ways to shorten the if statement? if data.char == "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9": data.board[row][col] = int(data.char)
has comment: http://stackoverflow.com/comment/85437315
downvote count: 6
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49216728
accepted answer: http://stackoverflow.com/a/49218042
has comment: http://stackoverflow.com/comment/85437305
has answer: http://stackoverflow.com/a/49218042
score: -6
has title: Shortening the following if statement?
favorite count: 0
type: Question

http://stackoverflow.com/comment/118244146
has text: I wonder why people continue to use AWS after these crapy setups.
score: 1
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49175969

http://stackoverflow.com/comment/85424950
has text: Can you share your current code, current and desired output?
type: QuestionComment
comment on: http://stackoverflow.com/q/49209765
score: 1
type: Comment

http://stackoverflow.com/comment/85501483
score: 0
comment on: http://stackoverflow.com/q/49248799
has text: For example: let searchQueryFK be: searchQueryFK = "https://www.flipkart.com/search?q="+str("58D300DX%20Panasonic"). I should get the print of 57,000. However, I am getting 8,999. In some other instance of the code run, I get some other number.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85251632
has text: Yes, it is a loop - there is a bunch of other code but everything else seems fine. It also isn't written very efficiently yet so I plan to fix some of that but just need help figuring out why it is overwriting the sheets or why it isn't writing the data in the second code.
comment on: http://stackoverflow.com/q/49123132
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49144541
tagged with: pentaho
has body: I'm trying to pivot my measure column to have its values become fields. Meaning net_revenue and vic should become their own fields. In the picture below, the Input is on the left, and Desired Output is on the right: I'm aware that measure has duplicate keys (e.g., net_revenue appears more than once), but date_budget, which I'm also indexing on, is different for that block of data. date_budget does repeat, but only when measure has changed, so we never have truly duplicate rows for the indexed columns. Question: In Pentaho CPython script, when I look at output from the script, I get back only my indexed columns, but not the pivoted columns net_revenue and vic. Why is this? Script: import pandas as pd budget['monthly_budget_phasing'] = pd.to_numeric(budget['monthly_budget_phasing'], errors='coerce') # Perform the pivot. budget = pd.pivot_table(budget, values='monthly_budget_phasing', index=['country', 'customer', 'date_budget'], columns='measure' ) budget.reset_index(inplace=True) result_df = budget Sample Dataframe: d = { 'country': ['us', 'us', 'us', 'us', 'us', 'us', 'us', 'us', 'us', 'us', 'us', 'us'], 'customer': ['customer1', 'customer1', 'customer1', 'customer1', 'customer1', 'customer1', 'customer2', 'customer2', 'customer2', 'customer2', 'customer2', 'customer2',], 'measure': ['net_revenue', 'net_revenue', 'net_revenue', 'vic', 'vic', 'vic', 'net_revenue', 'net_revenue', 'net_revenue', 'vic', 'vic', 'vic'], 'date_budget': ['1/1/2018', '2/1/2018', '3/1/2018', '1/1/2018', '2/1/2018', '3/1/2018', '1/1/2018', '2/1/2018', '3/1/2018', '1/1/2018', '2/1/2018', '3/1/2018'], 'monthly_budget_phasing': ['$55', '$23', '$42', '$29', '$35', '$98', '$87', '$77', '$34', '$90', '$75', '$12'] } df = pd.DataFrame(data=d) Worked in Pandas with aggfunc='first', but doesn't work in Pentaho. Pentaho is still outputting only country, customer, measure. Pandas output from terminal: country customer date_budget measure monthly_budget_phasing 0 us customer1 1/1/2018 net_revenue $55 1 us…
tagged with: python
has answer: http://stackoverflow.com/a/49175380
possible better answer: http://stackoverflow.com/a/49175380
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49145391
answer count: 2
has comment: http://stackoverflow.com/comment/85295764
accepted answer: http://stackoverflow.com/a/49145391
downvote count: 0
has title: Using pivot table returns only indexed columns, omits pivoted columns
tagged with: pandas
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/85296061
has comment: http://stackoverflow.com/comment/85296325
has comment: http://stackoverflow.com/comment/85295297
has comment: http://stackoverflow.com/comment/85316558
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85294283
has comment: http://stackoverflow.com/comment/85296137
has comment: http://stackoverflow.com/comment/85295433
has comment: http://stackoverflow.com/comment/85294831
has comment: http://stackoverflow.com/comment/85296939
has comment: http://stackoverflow.com/comment/85316310

http://stackoverflow.com/q/49223985
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78558535
tagged with: pyaudio
has answer: http://stackoverflow.com/a/70348894
tagged with: bash
has title: Errors installing PyAudio "Failed Building Wheel for PyAudio"
has answer: http://stackoverflow.com/a/57478637
has answer: http://stackoverflow.com/a/65437687
answer count: 5
favorite count: 0
type: Question
upvote count: 12
score: 12
has answer: http://stackoverflow.com/a/55788901
has body: I have been having trouble finding a fix for getting PyAudio installed on my machine. I have tried a few different solutions and i do have the prerequisite library "portaudio" installed using homebrew. I have also looked for solutions to the gcc error that appears at the bottom of the output and to which solutions only generated a different error that read "Error: command ‘clang’ failed with exit status 1". I feel at this point it is some lack of understanding of the implications of these error messages due to a lack of experience in python that keeps me from understanding a resolution. Any help is greatly appreciated. Thank you. MacBook-Pro-2:~ MyName$ pip install pyaudio Collecting pyaudio Using cached PyAudio-0.2.11.tar.gz Building wheels for collected packages: pyaudio Running setup.py bdist_wheel for pyaudio ... error Complete output from command /Users/MyName/anaconda3/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/l8/g1463xmj059g0qmss57qr3bh0000gp/T/pip-build-r_jfrp4_/pyaudio/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /var/folders/l8/g1463xmj059g0qmss57qr3bh0000gp/T/tmpxdj3hlo2pip-wheel- --python-tag cp36: running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.7-x86_64-3.6 copying src/pyaudio.py -&gt; build/lib.macosx-10.7-x86_64-3.6 running build_ext building '_portaudio' extension creating build/temp.macosx-10.7-x86_64-3.6 creating build/temp.macosx-10.7-x86_64-3.6/src gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Users/MyName/anaconda3/include -arch x86_64 -I/Users/MyName/anaconda3/include -arch x86_64 -DMACOSX=1 -I/Users/MyName/anaconda3/include/python3.6m -c src/_portaudiomodule.c -o build/temp.macosx-10.7-x86_64-3.6/src/_portaudiomodule.o In file included from src/_portaudiomodule.c:33: In file included from /usr…
downvote count: 0
tagged with: pip

http://stackoverflow.com/a/49259072
score: 1
answers question: http://stackoverflow.com/q/49258986
has comment: http://stackoverflow.com/comment/85521227
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85521266
has body: {None, False} is a set. Sets can only contain hashable objects, and therefore you can only test for membership of hashable objects. Lists are not hashable. Instead, you could use a tuple to perform the same sort of membership comparison. Tuple elements do not need to be hashable. x not in (None, False)
upvote count: 1

http://stackoverflow.com/a/49434405
type: Answer
answers question: http://stackoverflow.com/q/49266939
score: 0
has body: It could reduce time cost around half by changing the follows for line in data_lines: data_file.write(line) into: data_file.write('\n'.join(data_lines)) Here is my test run range(0, 1000000) elapsed time 0:00:04.653065 elapsed time 0:00:02.471547 2.471547 / 4.653065 = 53 % However if 10 times the above range, there is no much difference.
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85873353

http://stackoverflow.com/comment/85275718
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49135354
score: 0
has text: @Jean-FrançoisFabre you're right, I hadn't thought of that.

http://stackoverflow.com/a/49209251
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49209128
score: 3
upvote count: 3
has body: According to the documentation tf_nn.top_k returns both values and indices of the sorted tensor, so you can simply use two variables, one for the values and one for the indices a_sorted_val, a_sorted_ind = tf.nn.top_k(a, 2) a_sorted_ind is the fuction expressed as a tensor Example: import tensorflow as tf import numpy as np with tf.Session(): a = tf.convert_to_tensor([[4, 3, 2, 1], [5, 6, 7, 8]]) a_sort_val, a_sort_ind = tf.nn.top_k(a, 4) values = a_sort_val.eval() indices = a_sort_ind.eval() unsorted_a = a.eval() print(unsorted_a) print(values) print(indices) type(a_sort_ind) [[4 3 2 1] &lt;-- unsorted [5 6 7 8]] [[4 3 2 1] &lt;-- sorted tensor [8 7 6 5]] [[0 1 2 3] &lt;-- indices of sorted tensor [3 2 1 0]] tensorflow.python.framework.ops.Tensor

http://stackoverflow.com/q/49132761
tagged with: dataframe
tagged with: python
has title: Drop all rows in a group if none of the rows match a specific condition
has comment: http://stackoverflow.com/comment/103906492
has comment: http://stackoverflow.com/comment/85270462
favorite count: 0
type: Question
has body: Im using a groupby on a name variable, I want to drop a subset of rows based on a string variable How do I drop subset of rows if there is not a particular string present in that group? user-id time event 0 AMsySZa--NczTTJGpJvNQTNri4nh 28/06/2016 11:18 CONVERSION 1 AMsySZa--NczTTJGpJvNQTNri4nh 28/06/2016 10:40 Organic Search 2 AMsySZa--NczTTJGpJvNQTNri4nh 26/06/2016 10:06 Organic Search 3 AMsySZa--NczTTJGpJvNQTNri4nh 07/05/2016 19:27 Display 4 AMsySZa-05iZ7gKLfZQ3_kw8l-mO 16/06/2016 09:05 CONVERSION 5 AMsySZa-05iZ7gKLfZQ3_kw8l-mO 21/06/2016 09:10 CONVERSION 6 AMsySZa-15QiL8a5kcw9LvAtBLiE 29/06/2016 20:35 Display 7 AMsySZa-15QiL8a5kcw9LvAtBLiE 27/05/2016 06:46 Display 8 AMsySZa-15QiL8a5kcw9LvAtBLiE 15/05/2016 00:17 Display 9 AMsySZa-15QiL8a5kcw9LvAtBLiE 15/05/2016 00:17 Display I want to eliminate any subsets that dont have the word "conversion". My expected output would be: user-id time event 0 AMsySZa--NczTTJGpJvNQTNri4nh 28/06/2016 11:18 CONVERSION 1 AMsySZa--NczTTJGpJvNQTNri4nh 28/06/2016 10:40 Organic Search 2 AMsySZa--NczTTJGpJvNQTNri4nh 26/06/2016 10:06 Organic Search 3 AMsySZa--NczTTJGpJvNQTNri4nh 07/05/2016 19:27 Display 4 AMsySZa-05iZ7gKLfZQ3_kw8l-mO 16/06/2016 09:05 CONVERSION 5 AMsySZa-05iZ7gKLfZQ3_kw8l-mO 21/06/2016 09:10 CONVERSION
answer count: 0
type: UnansweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/85270500
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/99341718
tagged with: pandas-groupby
tagged with: pandas
tagged with: group-by

firefox
type: Tag
tag name: firefox
tags question: http://stackoverflow.com/q/49203647
tags question: http://stackoverflow.com/q/49244121
tags question: http://stackoverflow.com/q/49141621

http://stackoverflow.com/q/49202274
score: 0
has comment: http://stackoverflow.com/comment/85413306
answer count: 0
has title: Kivy: EventDispatcher updated value to Label in Python
has body: I was hoping someone might be able to help me on one part of my Kivy/Python script I am hung up on. I am sure there is a quick solution to an experienced Kivy user. I have looked into other posts (Kivy Update Dynamic Label Text) but did not work for me, I am thinking because they are with older versions of Kivy (v1.7 and I am using v1.10). I have a regularly scheduled function callback for my_fun as may be seen in the code. The details of the for loop are irrelevant, but inside the my_fun function, ins.a takes on the third index value of my_Array, calling on the 'on_a' function as normal when the value is updated. Now, I need the label 'labelA1var' text to update with this value (instead of x1, currently just there as a place holder) Thank you in advance! import kivy kivy.require('1.10.0') from kivy.app import App from kivy.uix.button import Label from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.floatlayout import FloatLayout from kivy.graphics import Color from kivy.graphics import vertex_instructions from kivy.graphics.vertex_instructions import RoundedRectangle, Line from kivy.properties import NumericProperty, StringProperty from kivy.config import Config from kivy.clock import Clock from kivy.event import EventDispatcher Config.exit_on_escape = 1 class MainClass(FloatLayout): layout = FloatLayout(size=Window.size,pos=Window.center) x1 = 100 #Position all widgets using values y1 = 100 #Define Labels (left just one label for my example) labelA1var = Label(text='%d V' %(x1),color = (0,0,0,1),font_size = 20, pos = (-250 +x1, -26 +y1)) #Add Labels to Screen layout.add_widget(labelA1var) Window.add_widget(layout) def my_fun(dt): x = 0 global my_Array my_Array = [] print("My Function Running") read = [0x00, 0x00, 0x42, 0x55, 0x00, 0x00, 0x42, 0x55, 0x00, 0x00, 0x42, 0x55, 0x00, 0x00, 0x42, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00…
type: Question
tagged with: python
type: UnansweredQuestion
tagged with: kivy
linked to: http://stackoverflow.com/q/43877241
has comment: http://stackoverflow.com/comment/85411333

http://stackoverflow.com/comment/85446664
type: QuestionComment
type: Comment
score: 2
has text: Add 'import math' to the top of your script
comment on: http://stackoverflow.com/q/49221578

http://stackoverflow.com/comment/85477321
score: 0
type: Comment
has text: Hi Jean-Paul and thank you for your crisp explaination. Follow up question, do you think everything in the loop `for u in range(0,n):` could be parallizable in one step? Could it cause problems with the other for loops within? I know I need to edit the line `fout_.write` for this.
type: AnswerComment
comment on: http://stackoverflow.com/a/49236844

http://stackoverflow.com/q/49236694
tagged with: spotify
answer count: 1
has body: I'm interacting with the Spotify Web API for a django project that allows users to upload their playlists for them to be ranked according to certain parameters, namely audio features spotify assigns to all tracks. I'm using the Spotipy library to query the spotify API with python. It's lightning fast for user and playlist data, but following the Spotipy tutorials on how to get tracks from a playlist, I'm finding the response is extremely slow. The wait time for tracks is about proportional to the length of the playlist in tracks.. I'm thinking it has something to do with an inefficiency in how the spotipy library packages up and sends requests. Has anyone ever come across a similar bottleneck with regards to getting tracks and speed?
type: Question
has answer: http://stackoverflow.com/a/49249065
accepted answer: http://stackoverflow.com/a/49249065
has comment: http://stackoverflow.com/comment/85503070
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 0
tagged with: spotipy
has title: Getting tracks from a playlist using Spotipy is slow

http://stackoverflow.com/comment/85459189
type: QuestionComment
has text: @AGNGazer that's changing the colorspace from RGB, to BGR.
type: Comment
comment on: http://stackoverflow.com/q/49227098
score: 0

http://stackoverflow.com/comment/86532412
has text: It's hard to debug this error without more information. What versions of pykafka/kafka are you using? The interesting thing is that the metadata request is succeeding, but the group coordinator request is failing. Make sure that the machine you're running this code from has ssh access to each of the brokers in your kafka cluster.
comment on: http://stackoverflow.com/q/49268963
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85511918
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/166749/discussion-between-n-ivanov-and-rgfvfk-iff).
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49254041

http://stackoverflow.com/comment/85447052
type: QuestionComment
has text: try this: `col.insert_many(df.to_dict('r'))`
score: 1
comment on: http://stackoverflow.com/q/49221550
type: Comment

http://stackoverflow.com/comment/85537795
score: 0
type: Comment
has text: How sure are you that the problem isn't the unescaped ampersand?
comment on: http://stackoverflow.com/q/49267203
type: QuestionComment

http://stackoverflow.com/a/49183101
accepted answer of: http://stackoverflow.com/q/49182502
score: 83
answers question: http://stackoverflow.com/q/49182502
type: Answer
has body: Yep, the shortcut (Ctrl + M + L) works, other option is use the bar menu, at tool -&gt; preference -&gt; show line numbers Update: new path: Tools -&gt; Settings -&gt; Editor -&gt; show line numbers
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85580501
downvote count: 0
upvote count: 83

http://stackoverflow.com/a/49222612
type: Answer
has comment: http://stackoverflow.com/comment/85449432
score: 1
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: Here the last function call is passing a value at index midpoint+1 instead of tuple . Errors Explained IndexError: tuple index out of range , this occurs when len of tuple is 1 and midpoint+1 is 1 which is out of range as there is only one element TypeError: object of type 'int' has no len() , thats when int is passed in last line as first arguement to isMemberR def isMemberR(aseq, target): if len(aseq) == 0: return False else: midpoint = len(aseq) // 2 if aseq[midpoint] == target: return True else: if target &lt; aseq[midpoint]: return isMemberR(aseq[:midpoint], target) else: return isMemberR(aseq[midpoint+1:], target)
accepted answer of: http://stackoverflow.com/q/49222525
answers question: http://stackoverflow.com/q/49222525

http://stackoverflow.com/q/49267877
tagged with: google-cloud-platform
score: 7
answer count: 1
upvote count: 7
favorite count: 0
type: Question
has body: Django v1.11 Postgresql v9.6 Currently, I use 2 Google CloudSQL databases, one for development and one for production. Whenever I make changes to my models, I run python manage.py migrate to update the tables in the development database. This migration does not affect the production database, however. Now, whenever I git push changes to my Django project, TravisCI automatically runs tests and deploys the code to Google App Engine. Currently, it runs on GAE flexible environment (so I can use Python 3.5) What I want to have is for Travis or GAE to automatically run python manage.py migrate on the production database before runserver. However, I can't figure out how to run custom commands during a deploy. I've tried looking around GAE and Travis documentation and adding scripts to .travis.yml and app.yaml, but to no avail. As of now, anytime there is a model change, I have to migrate the production database locally in a very hacky way. Ideally, GAE will migrate at the beginning of every deploy.
type: UnansweredQuestion
tagged with: google-app-engine
downvote count: 0
linked to: http://stackoverflow.com/q/33703325
tagged with: django
tagged with: python
tagged with: travis-ci
has title: Django on GAE - How to automatically 'migrate' on deploy?
has answer: http://stackoverflow.com/a/59208824

http://stackoverflow.com/a/49122221
type: Answer
downvote count: 0
upvote count: 1
has body: I like the idea of using replace first then finding the values. keywords.assign( values= keywords.keywords.replace(labels, regex=True) .str.findall(f'({"|".join(labels.values())})') .str.join(' | ') ) keywords values 0 cheap shoes budget 1 luxury shoes expensive 2 cheap hiking shoes budget | sport
score: 1
answers question: http://stackoverflow.com/q/49121526

http://stackoverflow.com/a/49265142
answers question: http://stackoverflow.com/q/49263903
has comment: http://stackoverflow.com/comment/85534309
type: Answer
upvote count: 2
score: 2
downvote count: 0
type: AcceptedAnswer
has body: Here's the approach as already suggested in the comment: def orient_my_str(line, preprocessor): my_output = '' for item in preprocessor(line): my_output += item print(my_output) return my_output As I mentioned, you can pass a function as parameter. In order to call it, you do this: line_rev = orient_my_str(line_list, preprocessor=reversed) line_fwd = orient_my_str(line_list, preprocessor=lambda x: x) You could also use a default parameter for preprocessor, if you don't like passing the lambda function explicitly. In summary, the important point is that there's no need to pass the name of a function around in order to then look up that function and call it. Just pass the function itself as parameter.
accepted answer of: http://stackoverflow.com/q/49263903
has comment: http://stackoverflow.com/comment/85535693

http://stackoverflow.com/comment/85374839
score: 0
comment on: http://stackoverflow.com/a/49184469
type: Comment
has text: I'm completely new at this. Cantidad1 is supposed to be a simple number. How is cantidad1.set(...) used?
type: AnswerComment

http://stackoverflow.com/a/49216630
type: Answer
answers question: http://stackoverflow.com/q/49216609
has body: dict comprehension: data1 = {m.get(k, k): m.get(v, v) for k, v in data.items()} Note that {4: 1, 4: 6} in your example is a single element.
upvote count: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49216609
score: 2

http://stackoverflow.com/comment/85532878
has text: Sorry for the misunderstanding. I need a pyplot graph embedded in my pygamewindow therefore I use the non-GUI backend. Now I need in addition to the embedded graph a new graph in a seperate interactive GUI. Therefore the question if it is possible to use two backends in one programm.
type: Comment
comment on: http://stackoverflow.com/q/49247396
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85563728
score: 0
comment on: http://stackoverflow.com/a/49270361
type: Comment
has text: @CarrieLin yes you could
type: AnswerComment

http://stackoverflow.com/comment/85476384
score: 0
has text: @Rahul \\reports is a network folder
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49236513

http://stackoverflow.com/q/49124574
has answer: http://stackoverflow.com/a/49125118
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49124740
has answer: http://stackoverflow.com/a/49124690
possible better answer: http://stackoverflow.com/a/49124969
score: 0
has answer: http://stackoverflow.com/a/49124969
has title: How to add values in a list successively using list comprehension?
type: Question
has comment: http://stackoverflow.com/comment/85254050
answer count: 5
has answer: http://stackoverflow.com/a/49124769
tagged with: python
has comment: http://stackoverflow.com/comment/85254076
tagged with: list-comprehension
accepted answer: http://stackoverflow.com/a/49124690
has body: I want to add values in a list successively. is there any way to do it by using list comprehension? input_list = [1,2,3,4,5,6] expected_list = [1,3,6,10,15,21] this can be done by this function def add_list(input_list): required_list =[input_list[0]] for item in range(1,len(input_list)): required_list.append(required_list[-1] + input_list[item]) return (required_list)

http://stackoverflow.com/comment/131264573
has text: Good catch! I originally answered this question after searching for a way to solve two issues: first I was using a generator (so using `len()` was not relevant and total was `None` as you mentioned), and second I iterated over batches and wanted to update the total amount of items processed (that is, update the progress bar with the number of items inside the currently processed batch, with a total matching the total number of items, not batches). I guess I didn't thoroughly read the question and just assumed it was similar to what I was looking for since all the main keywords matched :)
comment on: http://stackoverflow.com/a/70849161
type: Comment
type: AnswerComment
score: 1

http://stackoverflow.com/q/49209139
has body: I was trying to do my project in full screen and i used full screen but sometimes the display comes for 1 second then it disappears and i tried it with no full screen and it works but it doesn't in full screen and my code is: import pygame from pygame.locals import* pygame.init() screen=pygame.display.set_mode((1360,768),pygame.FULLSCREEN,pygame.RESIZABLE) pygame.display.init()
answer count: 1
has comment: http://stackoverflow.com/comment/85423159
has answer: http://stackoverflow.com/a/49209325
tagged with: pygame
type: Question
has comment: http://stackoverflow.com/comment/85422853
type: UnansweredQuestion
tagged with: python
has title: pygame.FULLSCREEN makes the display disappear
tagged with: fullscreen
score: 0

http://stackoverflow.com/comment/85344396
type: QuestionComment
score: 0
has text: Fix the indentation if you want help. Indentation in Python is critical for the correct interpretation of code. We are not computers but we don't want to waste our time with unreadable code.
comment on: http://stackoverflow.com/q/49168542
type: Comment

http://stackoverflow.com/q/49186392
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/85378352
has body: Why does this fail in this way: import numpy as np cmp(u"Never", np.int64(500)) #UnicodeDecodeError: 'ascii' codec can't decode byte 0xf4 in position 0: ordinal not in range(128) while this succeeds: cmp(u"Never", int(np.int64(500))) I ran across this while trying to group a pandas dataframe containing mixed types. (python 2.7)
has comment: http://stackoverflow.com/comment/85378333
has title: Why does cmp(unicode, np.int64) fails with UnicodeDecodeError?
score: 3
answer count: 0
has comment: http://stackoverflow.com/comment/85378297
upvote count: 3
has comment: http://stackoverflow.com/comment/86097841
downvote count: 0
has comment: http://stackoverflow.com/comment/85378244
favorite count: 0
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/85378504

http://stackoverflow.com/comment/85303563
type: QuestionComment
comment on: http://stackoverflow.com/q/49149278
score: 0
has text: Sorry, but that's not how these models work. It is assumed that the train and test samples are independently and identically distributed based on some unknown distribution, and the MLP is only learning this distribution. If you are stuffing invalid inputs down its throat, you shouldn't expect it to know because it assumes you know what you're doing. I would recommend you filter those invalid values out in advance before passing it to predict.
type: Comment

http://stackoverflow.com/q/49248022
has comment: http://stackoverflow.com/comment/85516929
tagged with: javascript
upvote count: 1
has comment: http://stackoverflow.com/comment/85603481
favorite count: 0
tagged with: ajax
has body: In javascript I am POSTing with ajax and I need to get a reply from my Python program. The following code shows the javascript, but how does I produce the desired responseText from a GET on the Python side? In this example I am want a Yes or No reply to a question for the user as to whether to change the name provided or not. I understand how to receive the name and value in the python POST, but I don't know how to produce the response in the associated python GET. function changeName(name,value){ var json = '[{'; json += '"name":"'+name+'",' json += '"value":"'+value+'"}]' loadDoc(json,"edit") } function loadDoc(data,url) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 &amp;&amp; this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("POST", ("/"+url), true); xhttp.setRequestHeader("Content-type", "text"); #or something xhttp.send(data); } My typical response in Python GETs follows one of the following 2 patterns, but neither seems to allow me to reply in this case. self.response.out.write(template.render( template_values)) return webapp2.redirect("/templatename/%s" % variable) (No PHP or jquery, please.)
score: 1
has comment: http://stackoverflow.com/comment/85527964
tagged with: python
has comment: http://stackoverflow.com/comment/85608558
type: Question
answer count: 0
has title: producing a GET response to an ajax POST
has comment: http://stackoverflow.com/comment/85622291
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85511851
downvote count: 0

http://stackoverflow.com/a/49269641
answers question: http://stackoverflow.com/q/49269593
type: AcceptedAnswer
has body: Using lambda: df['result'] = df['text'].apply(lambda row: True if ('paid' in row) and ('volunteer' not in row) else False)
accepted answer of: http://stackoverflow.com/q/49269593
score: 0
type: Answer

http://stackoverflow.com/a/49401379
has body: Instead of using re.sub you can split it! def do_something_with_str(string): # do something with string here. # for example let's wrap the string with "@" symbol if it's not empty return f"@{string}" if string else string def get_replaced_list(string, words): result = [(string, True), ] # we take each word we want to replace for w in words: new_result = [] # Getting each word in old result for r in result: # Now we split every string in results using our word. split_list = list((x, True) for x in r[0].split(w)) if r[1] else list([r, ]) # If we replace successfully - add all the strings if len(split_list) &gt; 1: # This one would be for [text, replaced, text, replaced...] sub_result = [] ws = [(w, False), ] * (len(split_list) - 1) for x, replaced in zip(split_list, ws): sub_result.append(x) sub_result.append(replaced) sub_result.append(split_list[-1]) # Add to new result new_result.extend(sub_result) # If not - just add it to results else: new_result.extend(split_list) result = new_result return result if __name__ == '__main__': initial_string = 'acbbcbbcacbbcbbcacbbcbbca' words_to_replace = ('a', 'c') replaced_list = get_replaced_list(initial_string, words_to_replace) modified_list = [(do_something_with_str(x[0]), True) if x[1] else x for x in replaced_list] final_string = ''.join([x[0] for x in modified_list]) Here's variables values of the example above: initial_string = 'acbbcbbcacbbcbbcacbbcbbca' words_to_replace = ('a', 'c') replaced_list = [('', True), ('a', False), ('', True), ('c', False), ('bb', True), ('c', False), ('bb', True), ('c', False), ('', True), ('a', False), ('', True), ('c', False), ('bb', True), ('c', False), ('bb', True), ('c', False), ('', True), ('a', False), ('', True), ('c', False), ('bb', True), ('c', False), ('bb', True), ('c', False), ('', True), ('a', False), ('', True)] modified_list = [('', True), ('a', False), ('', True), ('c', False), ('@bb', True), ('c', False), ('@bb', True), ('c', False), ('', True), ('a', False), ('', True), ('…
type: Answer
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49272973

http://stackoverflow.com/comment/85304062
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49149218
has text: @jpp unfortunately it does not works
type: Comment

http://stackoverflow.com/a/59869746
type: Answer
has body: sudo yum install openssl-devel for Red Hat and CentOS, etc.
score: 0
answers question: http://stackoverflow.com/q/49200056

http://stackoverflow.com/q/49198387
tagged with: indexing
type: AnsweredQuestion
score: 2
answer count: 3
downvote count: 0
tagged with: pandas
linked to: http://stackoverflow.com/q/41111052
has title: find the last value and the corresponding column name in a dataframe
accepted answer: http://stackoverflow.com/a/49198707
favorite count: 0
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/49198444
has body: In the following dataframe, I want to find out what is the last value in each row, and also the column name that contains the last value. df ID c1 c4 c3 c2 c8 c7 1 1 2 2 1 NaN NaN 2 1 2 1 NaN NaN NaN 3 1 1 NaN NaN 2 1 Expected output ID Colname lastValue 1 c2 1 2 c3 1 3 c7 1 My code can only find the last value df['lastValue'] = df.ffill(axis = 1).iloc[:, -1] How can I locate the colname as well? Thanks!
has answer: http://stackoverflow.com/a/49198685
has answer: http://stackoverflow.com/a/49198444
tagged with: python
has answer: http://stackoverflow.com/a/49198707
linked to: http://stackoverflow.com/q/49164134

http://stackoverflow.com/q/49132728
accepted answer: http://stackoverflow.com/a/49133079
has body: I am trying to create a list with each IP address, returned from the following command. Im not entirely sure how to achieve this. Seems subprocess equals None. import subprocess ips = list() def bash_command(cmd): subprocess.Popen(['/bin/bash', '-c', cmd]) ips = bash_command("netstat -tuna tcp | grep 9876 | grep -v 0.0.0.0 | awk '{ print $5}' | cut -d':' -f1") print(ips)
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49133079
tagged with: python
has title: Python subprocess return output into a list
score: 4
upvote count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/64980835
answer count: 2
has answer: http://stackoverflow.com/a/64980835
downvote count: 0

http://stackoverflow.com/comment/85427962
type: AnswerComment
comment on: http://stackoverflow.com/a/49205595
type: Comment
has text: After the pd.concat line add df = df"Placement# Name" "Date" "Impressions" "Clicks" "CTR" "Conversion" "eCPA" "Spend"
score: 0

http://stackoverflow.com/a/49217921
score: 0
answers question: http://stackoverflow.com/q/49217800
has body: Here is a solution using Beautiful Soup.. html = """ لینک های دانلود راهنمای دانلود حجم: 5.06 گیگابایت دانلود - بخش اول دانلود - بخش دوم دانلود - بخش سوم دانلود - بخش چهارم دانلود - بخش پنجم دانلود - بخش ششم """ from bs4 import BeautifulSoup import requests import re import random import types soup = BeautifulSoup(html, 'html.parser') list_links = [] # Create empty list for a in soup.findAll(href=True): # find links list_links.append(a) #append to the list def return_links(list_, num): """ Takes in a list and returns n amount of items in a list """ links_list = [] for i in range(num): try: r = list_.pop(random.randint(0, len(list_))) links_list.append(r) except IndexError: return links_list return links_list list_of_links = return_links(list_links, 4) for i in list_of_links: print(i) Returns: دانلود دانلود دانلود دانلود
type: Answer

http://stackoverflow.com/a/49157506
has comment: http://stackoverflow.com/comment/85323080
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49157396
has comment: http://stackoverflow.com/comment/85365952
has comment: http://stackoverflow.com/comment/85356415
downvote count: 0
score: 1
type: Answer
has comment: http://stackoverflow.com/comment/85320730
has comment: http://stackoverflow.com/comment/85343674
answers question: http://stackoverflow.com/q/49157396
has body: As long as you are using InnoDB tables you might find the advice on this page useful. Most databases have facilities for bulk insert, and MySQL is no exception. If you find your insertions slow, make sure that you don't have autocommit set, as this forces a transaction around each individual operation.

http://stackoverflow.com/comment/85256759
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49126007
has text: Try switching activation to `sigmoid`. When you use `softmax` you add a spurious condition to your output - mainly - coordinates summing up to `1`.
type: Comment

http://stackoverflow.com/comment/85331129
has text: I think you might be over thinking this. Just call `response = requests.get(...)` in your `my_check` function, or call it first and pass the result to your function: `my_check(response)`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49159557
type: QuestionComment

http://stackoverflow.com/q/49238188
type: UnansweredQuestion
tagged with: arima
tagged with: python
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/117711427
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/114460377
has answer: http://stackoverflow.com/a/50933886
has answer: http://stackoverflow.com/a/64584427
has comment: http://stackoverflow.com/comment/85491371
has body: I'm trying to use statsmodels' ARIMA to forecast a time series. I'm using sklearn's TimeSeriesSplit to evaluate my models. Unfortunately, when I forecast the next fold of data (which has true value Y_test), I get a constant prediction: if is_arima: Y_train = Y_train.astype(float) # build basic ARIMA model arima_model = ARIMA(Y_train, order=(2,0,1)) # fit it, using exogenous variables arima_results = arima_model.fit() # predict next len(test) values, using exogenous variables (X_test) preds = arima_results.forecast(steps=len(Y_test))[0] print(preds) Which gives me: 115.65096239 120.89113477 121.52020239 121.59572014 121.60478583 121.60587414 121.60600479 121.60602047 121.60602235 121.60602258 121.6060226 121.60602261 121.60602261 121.60602261 121.60602261 121.60602261 121.60602261 121.6060226 121.6060226 121.6060226 121.6060226 121.6060226 121.6060226 121.6060226 121.6060226 121.6060226 121.6060226 121.6060226 121.6060226 121.6060226... This makes me think my ARIMA isn't using the prediction at time t for its prediction at time t+1? I understand the output isn't perfectly constant but my dataset shows large variation, so this is mildly concerning. Any idea what's going on? Thanks!
favorite count: 0
type: Question
has title: Statsmodels ARIMA: Constant Value for Each Forecast
tagged with: statsmodels

http://stackoverflow.com/q/49269755
has comment: http://stackoverflow.com/comment/96773957
linked to: http://stackoverflow.com/q/47122065
upvote count: 3
has answer: http://stackoverflow.com/a/59206969
downvote count: 0
has body: I have a simple ellipse (red) and I want to rotate the ellipse. The following code only return flatten ellipse (blue) but it does not rotate: import tkinter as tk import numpy as np import math def rotate(points, angle): new_points = list(points) rad = angle * (math.pi/180) cos_val = math.cos(rad) sin_val = math.sin(rad) for coords in new_points: x_val = coords[0] y_val = coords[1] coords[0] = x_val * cos_val - y_val * sin_val coords[1] = x_val * sin_val + y_val * cos_val return new_points window = tk.Tk() window.geometry("500x300") canvas = tk.Canvas(window, height=300, width=500) canvas.grid(row=0, column=0, sticky='w') # draw ellipse size=80 x0,y0=100,100 width,height=0.25*size,0.5*size x1,y1=x0+width,y0+height xc=x0+width/2 yc=y0+height/2 ellipse = canvas.create_oval([x0, y0, x1,y1],fill='blue') #draw rotated ellipse coord1=canvas.coords(ellipse) points=[[coord1[0],coord1[1]],[coord1[2],coord1[3]]] point2=rotate(points,30) coord2 = [item for sublist in point2 for item in sublist] ellipse2 = canvas.create_oval(coord2,fill='red') window.mainloop () Here is the result: The red ellipse supposed to be rotated by 30 degree but instead of rotated, it just get flattened. Question: How to rotate the ellipse in tkinter canvas? Notes: I am using python 3.6 I checked stackoverflow on similar question and it has no correct answer. unlike polygon that we can simply rotate each vertices, ellipse has no vertex.
tagged with: ellipse
favorite count: 0
type: Question
tagged with: rotation
tagged with: tkinter
type: UnansweredQuestion
tagged with: python
has title: How to rotate ellipse in tkinter canvas?
has answer: http://stackoverflow.com/a/49290111
score: 3
answer count: 2

http://stackoverflow.com/q/49201570
has title: Choosing right structuring element
has body: I am creating an program to automatically separate the solar cells of from a pv module for which i first thresholded the image using adaptive threshold to obtain the following image After which i intend to remove the the black pixels within the cell boundries by using dilation for which i have used a elliptical structuring element of size (10,10) and have obtained the following image As you can see there are still some black pixels left, now if i increase the size of the structuring element i lose the cell boundaries I have tried the other structuring elements available such as cross and rectangular without any success hence i would need to define a custom kernel and don't have an idea about how do i go about defining one. import numpy as np import cv2 img=cv2.imread('result2.jpg',0) th1 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\ cv2.THRESH_BINARY,25,-2) kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(15,15)) closing = cv2.morphologyEx(th1, cv2.MORPH_CLOSE, kernel) cv2.imwrite('closing.jpg',closing) cv2.imwrite('threshold.jpg',th1) cv2.waitKey(0) cv2.destroyAllWindows() Original image before thresholding
accepted answer: http://stackoverflow.com/a/49206132
tagged with: python
has answer: http://stackoverflow.com/a/49206132
type: AnsweredQuestion
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/85416110
tagged with: image-morphology
answer count: 1
downvote count: 0
tagged with: image-processing
favorite count: 0
type: Question
tagged with: opencv

http://stackoverflow.com/a/49243729
has comment: http://stackoverflow.com/comment/85491364
has body: From the documentation: Almost all module functions depend on the basic function random(), which generates a random float uniformly in the semi-open range [0.0, 1.0). Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes. So there shouldn't be any real difference in results. However, I would disagree that random.choice() is inferior to randint(), in fact, random choice is actually faster at generating random numbers. When you look at the source code: def randint(self, a, b): return self.randrange(a, b+1) def randrange(self, start, stop=None, step=1, _int=int, _maxwidth=1L&lt;&lt;BPF): istart = _int(start) if istart != start: # not executed if stop is None: # not executed istop = _int(stop) if istop != stop: # not executed width = istop - istart if step == 1 and width &gt; 0: if width &gt;= _maxwidth: # not executed return _int(istart + _int(self.random()*width)) And for choice(): def choice(self, seq): return seq[int(self.random() * len(seq))] You can see that randint() has the additional overhead of using randrange() EDIT As @abarnert has noted in the comments, there really is almost no performance difference here, and randint(1,6) is a clear and intuitive way of representing a dice roll I ran both for 10000 rolls, and didn't see any skewing, so there is a chance your input samples were just too small: And here is a distribution for rolling one dice twice, it is also very uniform: I borrowed pieces of this from these two helpful answers: Performance of choice vs randint Is Pythons random.randint statistically random?, which are helpful for further reading.
has comment: http://stackoverflow.com/comment/124272074
has comment: http://stackoverflow.com/comment/85491407
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49243597
downvote count: 0
type: Answer
score: 6
accepted answer of: http://stackoverflow.com/q/49243597
upvote count: 6
has comment: http://stackoverflow.com/comment/85491384

pca
tag name: pca
type: Tag
tags question: http://stackoverflow.com/q/49196650

http://stackoverflow.com/comment/85618374
score: 1
type: Comment
has text: I have no idea where to use formset.save >.< Tried different ways and places, but no success. Anyway, this is beyond my question. I'll keep trying... Thank you so so much @andilabs.
type: AnswerComment
comment on: http://stackoverflow.com/a/49159889

http://stackoverflow.com/q/49126955
favorite count: 0
type: Question
tagged with: opencv
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/49131331
accepted answer: http://stackoverflow.com/a/49131331
tagged with: python
tagged with: image-processing
has comment: http://stackoverflow.com/comment/85258706
linked to: http://stackoverflow.com/q/41418586
tagged with: imagemagick
has title: Remove all empty space from image
downvote count: 0
answer count: 1
has body: I need to remove all white-spaces from image but I don't know how to do it.. I am using trim functionality to trim white spaces from border but still white-spaces are present in middle of image I am attaching my original image from which I want to remove white-spaces my code from PIL import Image, ImageChops import numpy def trim(im): bg = Image.new(im.mode, im.size, im.getpixel((0, 0))) diff = ImageChops.difference(im, bg) diff = ImageChops.add(diff, diff, 2.0, -100) box = diff.getbbox() if box: im.crop(box).save("trim_pil.png") im = Image.open("/home/einfochips/Documents/imagecomparsion/kroger_image_comparison/SnapshotImages/screenshot_Hide.png") im = trim(im) but this code only remove space from borders, I need to remove spaces from middle also. Please help if possible, it would be very good if I got all five images in different PNG file.
has comment: http://stackoverflow.com/comment/85258524

http://stackoverflow.com/a/49263586
downvote count: 0
has comment: http://stackoverflow.com/comment/135467527
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49263437
upvote count: 19
score: 19
has body: Look at idxmax df.loc[df.groupby('YearReleased')['count'].idxmax()] Out[445]: id YearReleased Artist count 1 169 2015 Rihanna 3 4 172 2016 Rihanna 3 7 175 2017 EdSheeran 2
answers question: http://stackoverflow.com/q/49263437
has comment: http://stackoverflow.com/comment/85531156
type: Answer

http://stackoverflow.com/q/49194423
has title: Add column to several files, combine in one file and sort it
has body: I am new to the Python world, and I am fighting with basic operations. I have a huge amount of files named inlet_10_00_00.csv, inlet_10_00_01.csv, inlet_10_00_02.csv, etc. corresponding to different time inlet_Hour_minute_sec. The content looks like: x, y, z, temperature, pressure, u, v, w, k , omega 0, 0, 0, 295, 100001, ... 0, 1, 1, 296, 100002, ... ... I would like to do the next 2 operations: 1/ Add a t column to each file with value 0 for inlet_10_00_00, value 1 for inlet_10_00_01, etc. Adding a column t for a single file was quite easy with cols tools. But how can I add it to all files? data=pd.read_csv('C:/myPath/inlet_10_00_00.csv',sep=',',skiprows=7) data["t (s)"]="0" cols=list(data.columns.values) cols= cols[0:3]+ cols[-1:] + cols[3:10] cols newdata=data[cols] newdata.to_csv('out.csv', index=False) 2/ I want to combine all these files in one file and sort it by the t variable. I should end up with such format: x, y, z, t, temperature,pressure, u, v, w, k , omega 0, 0, 0, 0, 295,100001, .... this part comes from inlet_10_00_00.csv 0, 1, 1, 0, 296,100002, ... 0, 0, 0, 1, 292,100008, ... this part comes from inlet_10_00_01.csv 0, 1, 1, 1, 294,100012, ... Any ideas, how to proceed?
answer count: 1
has answer: http://stackoverflow.com/a/49194862
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85394311
tagged with: python
tagged with: sorting
score: 0
tagged with: pandas

http://stackoverflow.com/a/49280152
has comment: http://stackoverflow.com/comment/85565779
has comment: http://stackoverflow.com/comment/85719231
has comment: http://stackoverflow.com/comment/85765217
has comment: http://stackoverflow.com/comment/85570729
type: Answer
has comment: http://stackoverflow.com/comment/85565643
score: 0
has comment: http://stackoverflow.com/comment/85570892
has comment: http://stackoverflow.com/comment/85983398
has comment: http://stackoverflow.com/comment/85610601
has comment: http://stackoverflow.com/comment/85565602
has body: You may still be loading the whole input file when reading. You can try something along the lines below for an example of reading a file incrementally. This stackoverflow question also provides a little more context than the snippet below. You can also specify a target element in iterparse(), so that you can dump the whole target element at once. for event, elem in etree.iterparse(in_file, events=('start', 'end',)): if event == 'start': start_tag(elem.tag, {}, elem.text) elif event == 'end': end_tag(elem.tag) # It's safe to call clear() here because no descendants will be accessed elem.clear() # Also eliminate now-empty references from the root node to elem while elem.getprevious() is not None: del elem.getparent()[0]
has comment: http://stackoverflow.com/comment/85729667
has comment: http://stackoverflow.com/comment/85570442
answers question: http://stackoverflow.com/q/49255477
has comment: http://stackoverflow.com/comment/85986764
has comment: http://stackoverflow.com/comment/85873452
has comment: http://stackoverflow.com/comment/85869862

http://stackoverflow.com/a/49123166
score: 0
has comment: http://stackoverflow.com/comment/85268480
answers question: http://stackoverflow.com/q/49123098
has body: If you want to use Tweepy's StreamListener to filter tweets by just a keyword like trump or clinton, I think you're better off overriding the on_data method instead. You should receive the data like you're expecting then. I'd double check this but it seems like their docs are down?
type: Answer

http://stackoverflow.com/a/49121588
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49121561
has body: The warning is telling you that by the time you get to this line: self.output_console ("ttl value %d =&gt; %s"%(resp.getlayer(IP).ttl)+ os) The name os may not be bound to any object yet. That will be a crash with NameError. It's probably because you used os as the name in one branch, and then os1 as the name in the other branch. By the way, the canonical method to check whether Linux or Windows is this: &gt;&gt;&gt; import platform &gt;&gt;&gt; platform.system() 'Linux'
type: Answer
has comment: http://stackoverflow.com/comment/85248857

http://stackoverflow.com/a/49188826
upvote count: 4
score: 4
accepted answer of: http://stackoverflow.com/q/49181512
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85383165
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49181512
has comment: http://stackoverflow.com/comment/85384346
has body: bot.send_message(chat_id, 'Enter No.', reply_markup=ForceReply())

http://stackoverflow.com/q/49148668
has answer: http://stackoverflow.com/a/49148845
has answer: http://stackoverflow.com/a/49148986
tagged with: http://stackoverflow.com/tag/json
tagged with: python
score: -1
has title: python : Iterate through the list values and get the key in json
answer count: 3
tagged with: for-loop
upvote count: 0
possible better answer: http://stackoverflow.com/a/49148791
has answer: http://stackoverflow.com/a/49148791
downvote count: 1
has body: I have the below json: { "repo_url":"git@github.plugin.git", "latest_commit":"bfe7bxxxx", "old_commit":"a4ccbyyy", "region": { "A":["us-south","us-east"], "B":["au-syd","germany"] } } I need to get the key value A if I provide us-east or us-south as input. Similarly I need to get B if I provide au-syd or germany as input. How do I loop through this json construct. I have tried below code as a starting point output_json = json.load(open(file)) print output_json["region"] for majorkey, subdict in output_json["region"]: print subdict But that throws below error for majorkey, subdict in output_json["region"]: ValueError: too many values to unpack
favorite count: 0
accepted answer: http://stackoverflow.com/a/49148845
type: Question
has comment: http://stackoverflow.com/comment/85301784
type: AnsweredQuestion

http://stackoverflow.com/comment/85412212
comment on: http://stackoverflow.com/q/49203359
has text: @Organis He's pretty clearly on WIndows, given that he's talking about using WIndows' Test Scheduler, so he doesn't have `os.fork`.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/68574224
upvote count: 2
downvote count: 2
answers question: http://stackoverflow.com/q/49252880
score: 0
type: Answer
has body: I found that sometimes the webpage is not fully loaded and the answer is as simple as adding a time.sleep(2).

http://stackoverflow.com/a/49125087
accepted answer of: http://stackoverflow.com/q/49122916
score: 0
answers question: http://stackoverflow.com/q/49122916
type: Answer
has body: Hit the pip list command on pycharm's terminal and see whether xlwt available there or not. If not install it again.You are using python 2.7 so, see the version of xlwt you are using is compatible with this python or not. Edited: If you want to run your project with start button then go to `edit configuration by clicking on drop-down button beside the start and set the python interpreter there. Apart from that, you need to see from .ProductService import ProductService (try writing full path instead of just typing .productService) and from method import ProductServicePO,send_email, SaveImg, create_excel_file import line in views.py and ProductService.py respectively.
type: AcceptedAnswer

http://stackoverflow.com/comment/86971852
comment on: http://stackoverflow.com/a/49148100
has text: @CIsForCookies `getpass` can't do that (as it seems to be hard to do that cross-platform). on *nix you could use [`curses`](https://docs.python.org/3/howto/curses.html#user-input). but security-wise this is not a good idea: you are giving away the password-length.
score: 1
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85291846
type: QuestionComment
comment on: http://stackoverflow.com/q/49143128
has text: because you didn't apply `.strftime("%H:%M:%S")` the second time
type: Comment
score: 0

http://stackoverflow.com/a/49175436
score: 0
has comment: http://stackoverflow.com/comment/85379714
has comment: http://stackoverflow.com/comment/85359069
has comment: http://stackoverflow.com/comment/85358834
has comment: http://stackoverflow.com/comment/85463545
has comment: http://stackoverflow.com/comment/85384605
has body: The function that starts the work done on your variables with a button click should be separated from the function that works. The base block for this type of problem would be something like this: def StarterFunction(self): WorkThread = threading.Thread(target=self.WorkerFunction, args=(tuple, of, arguments)) WorkThread.start() while WorkThread.is_alive(): QApplication.processEvents() # This keeps the GUI responsive. WorkThread.join() def WorkerFunction(self): # do some work with variables And for your specific problem, you want the button that started all to update the variables while the work function is running if I understood correctly? Then you can do that: def StarterFunction(self): self.ui.button.clicked.disconnect(self.StarterFunction) self.ui.button.clicked.connect(self.UpdateMyVariables) WorkThread = threading.Thread(target=self.WorkerFunction, args=(tuple, of, arguments)) WorkThread.start() while WorkThread .is_alive(): QApplication.processEvents() # This keeps the GUI responsive. WorkThread.join() self.ui.button.clicked.connect(self.StarterFunction) self.ui.button.clicked.disconnect(self.UpdateMyVariables) def WorkerFunction(self): # do some work with variables def UpdateMyVariables(self): # read inputs from the GUI self.MyVariable1 = self.ui.lineIterations.text() self.MyVariable2 = self.ui.lineTimeout.text() That last part requires you to declare the variables processed in WorkFunction() as attributes of the GUI class in the __init__ so that they can be accessed and modified both by WorkFunction() and UpdateMyVariables().
answers question: http://stackoverflow.com/q/49168440
has comment: http://stackoverflow.com/comment/85817837
type: Answer

http://stackoverflow.com/comment/85454778
has text: Hmm, didn't know that, will update the answer. Thanks for the info!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49225425

http://stackoverflow.com/comment/85535575
type: AnswerComment
comment on: http://stackoverflow.com/a/49266045
has text: I forgot about `retbins` This element of the answer is better than mine. Though I do like my implementation better. IMO, accept this answer but I'll leave mine for reference.
score: 1
type: Comment

http://stackoverflow.com/comment/85353050
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49173710
has text: I have not yet finalised my graph choice as it needs to be able to do what I want. The example you linked seems to be doing exactly that so I will have a look at Bokeh, thank you.

http://stackoverflow.com/q/49177491
tagged with: amazon-web-services
accepted answer: http://stackoverflow.com/a/49177744
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85360412
possible better answer: http://stackoverflow.com/a/52977274
has title: Where is the API documentation for boto3 resources?
tagged with: python
has answer: http://stackoverflow.com/a/49177744
favorite count: 0
type: Question
has body: I have learned that boto3 offers two levels of abstraction: a low-level API called client that is a thin wrapper around the AWS HTTP API, and a high-level client called resource that offers real Python objects. My question is, where is the API documentation for the resource API? I found this: https://boto3.readthedocs.io/en/stable/reference/services/ec2.html#client But that describes the client API, and there's not a 1-to-1 mapping to the resource API. For example, enumerating instances is called describe_instances() on the client object, and it is called instances.all() on the resource object. Next I found this: http://boto3.readthedocs.io/en/stable/reference/core/resources.html?highlight=resource This describes a set of base classes and factory methods, but it doesn't describe the API for a specific service like EC2. At runtime, I printed out an object of interest and found that it is a boto3.resources.factory.ec2.ServiceResource, but searching the boto3 documentation doesn't show me any human-readable documentation for this resource. Is there an API document that explains what all of the different Python classes are, and what properties/methods they have? I can print this out at runtime, e.g. print(dir(ec2)) but this is a pretty tedious way to discover the API.
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/52977274
upvote count: 11
score: 11
tagged with: boto3

http://stackoverflow.com/comment/85378822
type: QuestionComment
has text: Xarray does not currently support indexing using nearest neighbor lookups on multi-dimensional coordinates: https://github.com/pydata/xarray/issues/475#issuecomment-125349079
type: Comment
comment on: http://stackoverflow.com/q/49177716
score: 0

http://stackoverflow.com/a/50209018
type: Answer
score: 4
has body: well i found that the answer is rather simple all we need to do is add the code below.. mod = SourceModule(""" __global__ void multiply_them(float *dest, float *a, float *b) { const int i = threadIdx.x; dest[i] = a[i] * b[i]; } """,options=['--maxrregcount=20'])
upvote count: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49176027
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49176027

http://stackoverflow.com/comment/85424092
type: Comment
comment on: http://stackoverflow.com/a/49209745
score: 0
type: AnswerComment
has text: Can you please provide us with good input data. for example what does `business.css('a.email-business::attr(href)').extract()` return exactly? Is it a string? Without it we cannot answer the question to any more extend. Please put the information in you original question

http://stackoverflow.com/a/49241256
has comment: http://stackoverflow.com/comment/85533164
has comment: http://stackoverflow.com/comment/85508053
has body: The requests library may be what you're looking for. You'd need the URL to pass in to requests.get import requests r = requests.get('http://google.com') r.raise_for_status() # Will error out if there's an issue with the get request print(r.content) outputs Google <scr...
type: Answer
answers question: http://stackoverflow.com/q/49241079
has comment: http://stackoverflow.com/comment/85486734
score: 0

http://stackoverflow.com/a/49284451
accepted answer of: http://stackoverflow.com/q/49257981
has comment: http://stackoverflow.com/comment/86413629
has body: You need to extend the model sale.order and add a new field, in your case call it maybe start_date, but make sure it does not already exist on sale.order. You can see an example of how to define such a field in the original Odoo v8 repo here. You can then set a default value for that field, see for example here. If I recall correctly, the Add to cart button triggers the controller at the route '/shop/cart/cart_update', so you will have to extend the method cart_update and update the sale order according to your needs. I would suggest you extend the method, do a super call as it is for example done here (this is just an example in case you have never done this, of course you need to adjust it) and save the return value for super in a variable, e.g. res = super(...). After the super you change the sale order (you need to fetch it somehow, either you check if the sale order is already available in res.qcontext (probably will not since the parent returns a redirect), or you fetch it via request.website.sale_get_order() which can be seen here. After you update the sale order, you finally return res. Something along these lines should do it: @http.route() def cart_update(self, product_id, add_qty=1, set_qty=0, **kw): res = super(WebsiteSale, self).cart_update(product_id, add_qty, set_qty, **kw) order = request.website.sale_get_order() # update your order now # ... # finally return return res
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/49257981
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85592711

http://stackoverflow.com/q/49238981
type: Question
has answer: http://stackoverflow.com/a/49241257
tagged with: memory-management
has title: RAM is not freed after a Python function is invoked
has comment: http://stackoverflow.com/comment/85481572
tagged with: heap-memory
tagged with: memory-leaks
has comment: http://stackoverflow.com/comment/85484505
tagged with: python
accepted answer: http://stackoverflow.com/a/49241257
has body: I'm using an in-house Python library for scientific computing. I need to consecutively copy an object, modify it, and then delete it. The object is huge which causes my machine to run out of memory after a few cycles. The first problem is that I use python's del to delete the object, which apparently only dereferences the object, rather than freeing up RAM. The second problem is that even when I encapsulate the whole process in a function, after the function is invoked, the RAM is still not freed up. Here's a code snippet to better explain the issue. ws = op.core.Workspace() net = op.network.Cubic(shape=[100,100,100], spacing=1e-6) proj = net.project def f(): for i in range(5): clone = ws.copy_project(proj) result = do_something_with(clone) del clone f() gc.collect() &gt;&gt;&gt; ws {'sim_01': [&lt;openpnm.network.Cubic object at 0x7fed1c417780&gt;], 'sim_02': [&lt;openpnm.network.Cubic object at 0x7fed1c417888&gt;], 'sim_03': [&lt;openpnm.network.Cubic object at 0x7fed1c417938&gt;], 'sim_04': [&lt;openpnm.network.Cubic object at 0x7fed1c417990&gt;], 'sim_05': [&lt;openpnm.network.Cubic object at 0x7fed1c4179e8&gt;], 'sim_06': [&lt;openpnm.network.Cubic object at 0x7fed1c417a40&gt;]} My question is how do I completely delete a Python object? Thanks! PS. In the code snippet, each time ws.copy_project is called, a copy of proj is stored in ws dictionary.
type: AnsweredQuestion
score: 0
answer count: 1
tagged with: memory

http://stackoverflow.com/q/49191254
answer count: 1
has title: Python loop output
downvote count: 1
has comment: http://stackoverflow.com/comment/85388357
favorite count: 0
has comment: http://stackoverflow.com/comment/85389767
type: Question
has answer: http://stackoverflow.com/a/49192852
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85390362
type: UnansweredQuestion
has body: I have tried looping into a column, there are three different values which should be filled in the columns but only one value is getting filled. for i in df_j['token']: if i in ["AK","BK","BW","AC","AK","AR","BA"]: df_j['check']='1_Check' elif i in ["AW","AA"]: df_j['check']='STP' elif i in ["MD","MW","MK","NW","NK","ND","PW","PK"]: df_j['check']='Normal' Above is the code and value which is coming is "normal' in all rows.
tagged with: python
score: -1
has comment: http://stackoverflow.com/comment/85387947
linked to: http://stackoverflow.com/q/21702342
tagged with: pandas
upvote count: 0

http://stackoverflow.com/comment/85384963
comment on: http://stackoverflow.com/q/49189836
score: 0
has text: Thanks jarlh for the answer. I use a group by for date. What else would I need to group? The error I get, Giacomo, is ProgrammingError: (psycopg2.ProgrammingError) aggregate function calls cannot be nested LINE 1: ...i.metricb != 0) THEN (1000 * sum(i...
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85389137
has text: Thank you, I'm new in programming, so my question may be very simple for you!
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49191943
type: Comment

http://stackoverflow.com/comment/86115825
type: QuestionComment
has text: Question answered in LightGBM github : [link](https://github.com/Microsoft/LightGBM/issues/1279)
comment on: http://stackoverflow.com/q/49253698
score: 0
type: Comment

passwords
tags question: http://stackoverflow.com/q/49127554
tags question: http://stackoverflow.com/q/49148036
tags question: http://stackoverflow.com/q/49164907
tags question: http://stackoverflow.com/q/49230960
type: Tag
tags question: http://stackoverflow.com/q/49216840
tag name: passwords

http://stackoverflow.com/q/49139188
has body: I have this output result from Google Cloud Natural Language API (took me quite a while to produce it so I don't want to go with the solution in How can I JSON serialize an object from google&#39;s natural language API? (No __dict__ attribute) ) Mentions: Name: "Trump" Begin Offset : 0 Content : Trump Magnitude : 0.0 Sentiment : 0.0 Type : 2 Salience: 0.6038374900817871 Sentiment: Mentions: Name: "hand" Begin Offset : 19 Content : hand Magnitude : 0.0 Sentiment : 0.0 Type : 2 Salience: 0.20075689256191254 Sentiment: Mentions: Name: "water boarding" Begin Offset : 39 Content : water boarding Magnitude : 0.0 Sentiment : 0.0 Type : 2 Salience: 0.13010266423225403 Sentiment: Mentions: Name: "some" Begin Offset : 58 Content : some Magnitude : 0.0 Sentiment : 0.0 Type : 2 Salience: 0.04501711577177048 Sentiment: Mentions: Name: "GOPDebate" Begin Offset : 65 Content : GOPDebate Magnitude : 0.0 Sentiment : 0.0 Type : 1 Salience: 0.020285848528146744 Sentiment: I want to find the Magnitude and Sentiment for a set of candidate names (Donald Trump, Hillary Clinton, Bernie Sanders and Ted Cruz--or a set of similar name like only trump/hillary/clinton/cruz/bernie/sanders/@realdonaldtrump). At first I didn't realize that output files are not json. Indeed I am not sure what the format is. I was told it is perhaps malformatted YAML. Is there a way to convert these files to json? As I said, I have processed lots of files and it is not practical for me to modify the protobuf and create json at this point. The part of code from Google Cloud NLP tutorial that does this is: # [START def_entity_sentiment_text] def entity_sentiment_text(text): """Detects entity sentiment in the provided text.""" client = language.LanguageServiceClient() if isinstance(text, six.binary_type): text = text.decode('utf-8') document = types.Document( content=text.encode('utf-8'), type=enums.Document.Type.PLAIN_TEXT) # Detect and send native Python encoding to receive correct word offsets. encoding = enums.Encod…
type: Question
has answer: http://stackoverflow.com/a/63058554
upvote count: 2
linked to: http://stackoverflow.com/q/45684158
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85284763
downvote count: 0
tagged with: python
favorite count: 0
linked to: http://stackoverflow.com/q/64470470
has title: converting Google Cloud NLP API entity sentiment output to JSON
tagged with: google-cloud-nl
score: 2
has comment: http://stackoverflow.com/comment/85283937
has comment: http://stackoverflow.com/comment/85284365
has comment: http://stackoverflow.com/comment/85284275
tagged with: google-cloud-platform
tagged with: yaml
tagged with: http://stackoverflow.com/tag/json
answer count: 1

http://stackoverflow.com/comment/99021872
comment on: http://stackoverflow.com/a/49239335
has text: @javadba. Because that is what pandas is for. It's simply not part of the niche that numpy is filling to the best of its ability.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85480816
score: 0
type: Comment
type: QuestionComment
has text: The question should be "Why does the first program set the local `a` variable while the second program set the second?" But if you `import test1` I don't think you can directly `printa()`. Also there is [tag:python-2.7].
comment on: http://stackoverflow.com/q/49238607

http://stackoverflow.com/q/49258019
has comment: http://stackoverflow.com/comment/85519546
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85524109
tagged with: raycasting
has body: I'm sorry for making the title vague but I honestly have no idea how to describe what its showing. My code is almost a direct port of the example code on www.lodev.org/cgtutor/raycasting.html My full code is at https://pastebin.com/tK1CNFps This here is the main part of the program. zde = 0.0000001 #Add to prvent division by zero res = 2 HEIGHT = 600 WIDTH = 1000 xPos = 10.0 yPos = 5.0 xDir = -1 yDir = 0 xPlane = 0 yPlane = 0.66 for column in range(0,WIDTH,res): xCamera = 2 * column / float(WIDTH) - 1.0 xRayDir = xDir + xPlane * xCamera yRayDir = yDir + yPlane * xCamera xMap = int(xPos) yMap = int(yPos) xSideDistance = 0.0 ySideDistance = 0.0 perpWallDistance = 0.0 xDeltaDistance = abs(1/(xRayDir + zde)) yDeltaDistance = abs(1/(yRayDir + zde)) xStep = 0 yStep = 0 hit = False side = 0 if (xRayDir &lt; 0): xStep = -1 xSideDistance = (xPos - xMap) * xDeltaDistance else: xStep = -1 xSideDistance = (xMap + 1.0 - xPos) * xDeltaDistance if (xRayDir &lt; 0): yStep = -1 ySideDistance = (yPos - yMap) * yDeltaDistance else: yStep = 1; ySideDistance = (yMap + 1.0 - yPos) * yDeltaDistance hit = False while not hit: if (xSideDistance &lt; ySideDistance): xSideDistance += xDeltaDistance xMap += xStep side = 'x' else: ySideDistance += yDeltaDistance yMap += yStep side = 'y' if worldMap[xMap][yMap] != 0 : hit = True if (side == 0): perpWallDist = (xMap - xPos + (1 - xStep) / 2) / (xRayDir + zde) else: perpWallDist = (yMap - yPos + (1 - yStep) / 2) / (yRayDir + zde) lineHeight = int(HEIGHT / (perpWallDist + zde)) drawStart = -lineHeight / 2 + HEIGHT / 2 if (drawStart &lt; 0): drawStart = 0 drawEnd = lineHeight / 2 + HEIGHT / 2 if (drawEnd &gt;= HEIGHT): drawEnd = HEIGHT - 1 wallcolours = [ [255,255,255], [150,0,0], [0,150,0], [0,0,150] ] colour = wallcolours[worldMap[xMap][yMap]] if side == 'y': colour = [i/2 for i in colour] pygame.draw.line(screen, colour, (column,drawStart), (column, drawEnd), res) Screenshots of mine: https://i.sstatic.net/U6PIh.jpg Screenshots of a similar, work…
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49262633
accepted answer: http://stackoverflow.com/a/49262633
upvote count: 1
has comment: http://stackoverflow.com/comment/85519550
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85522233
has title: How can I start work on debugging my Python Raycaster?
score: 1
tagged with: python
tagged with: pygame

http://stackoverflow.com/comment/85341702
comment on: http://stackoverflow.com/a/49158042
has text: That is not working, the two last columns are out of screen (to the right). Instead of calling `self.moveSplitter`, I call `self.split_H1.setSizes([100000,100000,100000])`, `self.split_H2.setSizes([100000,100000,100000])`, `self.split_H3.setSizes([100000,100000,100000])`. That's working. However, I should use sys.maxsize to get the int max value but if I do so, I get a weird message: TypeError: index 0 has type 'int' but 'int' is expected
type: AnswerComment
type: Comment
score: 0

http://stackoverflow.com/q/49209846
tagged with: 3d
type: UnansweredQuestion
answer count: 1
tagged with: vtk
has answer: http://stackoverflow.com/a/49210690
score: 0
tagged with: itk
has body: I have 2D CT images in a 3D numpy of shape [512, 512, 586] (or a bunch of jpeg files saved from this array). Those images have only two pixels values: 0 or 255 what I need to do is to convert this array into a printable 3D model/mesh (STL or whatever is possible) I tried what was described in this post using simple itk. However I didn't find anything about saving the volume into a stl file is there a way to do this? (using simple itk or any other library) --EDIT-- so here is my code using VTK, however i'm having trouble to convert the numpy array to a vtk array dataImporter = vtk.vtkImageImport() data_string = ArrayDicom.tostring() dataImporter.CopyImportVoidPointer(data_string, len(data_string)) dataImporter.SetDataScalarTypeToUnsignedShort() dataImporter.SetNumberOfScalarComponents(1) dataImporter.SetDataExtent(0, heightArray-1, 0, depthArray-1, 0, widthArray-1) dataImporter.SetWholeExtent(0, heightArray-1, 0, depthArray-1, 0, widthArray-1) this code is showing a black window with nothing inside it The other code: print("converting numpy array to VTK array") CT_Data = reader.GetOutput() NP_data = numpy_support.numpy_to_vtk(ArrayDicom.ravel(), deep=True, array_type=vtk.VTK_TYPE_INT16) print("loading vtkImageData") imageVTK = vtk.vtkImageData() imageVTK.SetSpacing(CT_Data.GetSpacing()) imageVTK.SetOrigin(CT_Data.GetOrigin()) imageVTK.SetDimensions(CT_Data.GetDimensions()) imageVTK.GetPointData().SetScalars(NP_data) dmc = vtk.vtkDiscreteMarchingCubes dmc.SetInputData(imageVTK) this one is getting the error : TypeError: no overloads of SetInputData() take 0 arguments
tagged with: python
has title: stack of 2D images to 3D python
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/30237024

http://stackoverflow.com/comment/85437328
score: 0
has text: [Probably this can help](https://stackoverflow.com/questions/13315922/extract-and-substitute-substring-between-placeholders-in-string)?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49216593

http://stackoverflow.com/a/49258113
has body: Try using a global variable. At the top of your code put: total = 0 Inside your function, put: global total And then you can access total, retrieve its value, and update its value inside your function. This is because you told the function to use the variable total, that already exists outside the function. It knows not to create new local variable. Hope that helps!
answers question: http://stackoverflow.com/q/49257958
has comment: http://stackoverflow.com/comment/85519257
type: Answer
score: 0

http://stackoverflow.com/a/49200280
downvote count: 0
type: AcceptedAnswer
has body: The almighty groupby comes to the rescue - df.groupby('NAME').head(5) ID PROD QTY PRICE NAME 0 1 G 2 120 Yes 1 2 B 5 150 Yes 2 3 S 2 80 Yes 3 4 T 5 300 Yes 4 1 G -2 120 Yes 6 3 S 2 80 No 7 4 T 5 300 No 8 1 G -2 120 No 9 2 B -5 150 No 10 3 S 2 80 No
has comment: http://stackoverflow.com/comment/85405726
answers question: http://stackoverflow.com/q/49200266
type: Answer
accepted answer of: http://stackoverflow.com/q/49200266
score: 2
upvote count: 2

http://stackoverflow.com/comment/85806732
type: AnswerComment
comment on: http://stackoverflow.com/a/49370616
score: 0
has text: Thank you. I would still recommend to use serverless to avoid all the trouble.
type: Comment

http://stackoverflow.com/a/49136593
has body: No, del doesn't have anything to do with memory management or garbage collection. It only decrements something called a reference counter - every object has one. Once an object's reference counter drops to 0, that means it is no longer accessible through any variable, and will be garbage collected the next time the collector does its thing. So, in summary, calling del on an object will eventually end up in its memory being reclaimed, as long as no other variable currently refers to that object. Also see Is there a way to get the current ref count of an object in Python?
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85278243
has comment: http://stackoverflow.com/comment/85278469
accepted answer of: http://stackoverflow.com/q/49136549
has comment: http://stackoverflow.com/comment/85278169
has comment: http://stackoverflow.com/comment/85278406
answers question: http://stackoverflow.com/q/49136549
upvote count: 3
score: 3
type: Answer

http://stackoverflow.com/comment/85325195
comment on: http://stackoverflow.com/a/49159731
has text: This errors when the subprrocess errors, right? I want pytest to ignore errors when this subprocess executes. If the subprocess returns 0, I will assert an error.
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/49133562
downvote count: 0
has body: This does not always apply, but if it is part of your class logic to compare based on the length of name, you can implement the special class methods __lt__ and __eq__. class XYZ: def __init__(self, name, score): self.name = name self.score = score def __lt__(self, other): return len(self.name) &lt; len(other.name) def __eq__(self, other): return self.name == other.name and self.score == other.score The result: l = [XYZ('Anmol', 10), XYZ('Andrew', 200), XYZ('Johnson', 3000)] max(l).name # 'Johnson' Note that doing so will also specify a behaviour for comparison operators (==, &lt; and &gt;) aswell as for sorted for your class instances.
score: 3
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/49132937

http://stackoverflow.com/q/49197366
score: 2
upvote count: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/49198148
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/49198148
favorite count: 0
tagged with: fft
accepted answer: http://stackoverflow.com/a/49223310
has title: Using FFT for 3D array representation of 2D field
type: Question
has comment: http://stackoverflow.com/comment/85449074
has answer: http://stackoverflow.com/a/49223310
tagged with: python
has body: I need to obtain the fourier transform of a complex field. I'm using python. My input is a 2D snapshot of the electric field in the xy-plane. I currently have a 3D array F[x][y][z] where F[x][y][0] contains the real component and F[x][y]1 contains the complex component of the field. My current code is very simple and does this: result=np.fft.fftn(F) result=np.fft.fftshift(result) I have the following questions: 1) Does this correctly compute the fourier transform of the field, or should the field be entered as a 2D matrix with each element containing both the real and imaginary component instead? 2) I entered the complex component values of the field using the real multiple only (i.e if the complex value is 6i I entered 6), is this correct or should this be entered as a complex value instead (i.e. entered as '6j')? 3) As this is technically a 2D input field, should I use np.fft.fft2 instead? Doing this means the output is not centered in the middle. 4) The output does not look like what I'd expect the fourier transform of F to look like, and I'm unsure what I'm doing wrong. Full example code: import numpy as np import matplotlib.pyplot as plt from matplotlib import cm x, y = np.meshgrid(np.linspace(-1,1,100), np.linspace(-1,1,100)) d = np.sqrt(x*x+y*y) sigma, mu = .35, 0.0 g1 = np.exp(-( (d-mu)**2 / ( 2.0 * sigma**2 ) ) ) F=np.empty(shape=(300,300,2),dtype=complex) for x in range(0,300): for y in range(0,300): if y&lt;50 or x&lt;100 or y&gt;249 or x&gt;199: F[x][y][0]=g1[0][0] F[x][y][1]=0j elif y&lt;150: F[x][y][0]=g1[x-100][y-50] F[x][y][1]=0j else: F[x][y][0]=g1[x-100][y-150] F[x][y][1]=0j F_2D=np.empty(shape=(300,300)) for x in range(0,300): for y in range(0,300): F_2D[x][y]=np.absolute(F[x][y][0])+np.absolute(F[x][y][1]) plt.imshow(F_2D) plt.show() result=np.fft.fftn(F) result=np.fft.fftshift(result) result_2D=np.empty(shape=(300,300)) for x in range(0,300): for y in range(0,300): result_2D[x][y]=np.absolute(result[x][y][0])+np.absolute(result[x][y][1]) plt.ims…
has comment: http://stackoverflow.com/comment/85448813
tagged with: numpy

http://stackoverflow.com/comment/85461011
type: AnswerComment
comment on: http://stackoverflow.com/a/49228721
score: 0
type: Comment
has text: Hey @Shahid, I added "wait.until(EC.presence_of_element_located((By.CLASS_NAME, "exempted-detail"))) above the main for loop. That's the class where "Span" element is located. It still throws the same error.

http://stackoverflow.com/a/49271192
type: AcceptedAnswer
downvote count: 1
has body: Okay so I didn't have my DSN configured correctly. The driver I was using was SQL Server and I needed to change it to ODBC Driver 13 for SQL Server. That fixed all my problems.
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/49268589
accepted answer of: http://stackoverflow.com/q/49268589
score: 1

http://stackoverflow.com/comment/85271280
type: QuestionComment
comment on: http://stackoverflow.com/q/49132703
type: Comment
has text: A `select` tag shouldn't have a `value` attribute. Though I haven't seen your models, I'm not sure that `action.owner` and `resource.name` could ever be the same thing.
score: 2

http://stackoverflow.com/comment/85554938
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49276295
has text: you should probably use python3

http://stackoverflow.com/a/49168862
has comment: http://stackoverflow.com/comment/85342770
has comment: http://stackoverflow.com/comment/85347035
downvote count: 1
answers question: http://stackoverflow.com/q/49168695
upvote count: 0
type: Answer
score: -1
has body: I'm not able to test it right now, but I've spotted a source of error: lambda: newScreen(window2, window1) This creates a lambda function that doesn't take any arguments, hence window2 and window1 will be None, and None doesn't have a destroy() method, hence the error. Instead try: lambda window2, window1: newScreen(window2, window1)

http://stackoverflow.com/comment/85413600
comment on: http://stackoverflow.com/q/49203951
has text: Do you need to check for integers versus floats [and other non-string types]?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85383783
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49188956
has text: You should use a new private window, flask saves sessions in a cookie which is shared among window

http://stackoverflow.com/a/49227426
score: 0
has body: The naive way to do what you are trying to do is the following: state_to_abbrev = {} for i in range(len(states)): state_to_abbrev[states[i]] = abbreviations[i] You have instead a nested loop, but that's not what you want, the nested loop loops over the cartesian product of your two lists, i.e.: In [46]: for a in ('a','b'): ...: for n in (1, 2): ...: print(a, n) ...: a 1 a 2 b 1 b 2 In [47]: But really, in Python, instead of using indices, you'd use zip to iterate over two lists "in parallel": state_to_abbrev = {} for st, abbr in zip(states, abbreviations): state_to_abbrev[st] = abbr But really, you should know that the dict constructor takes an iterable of key-value pairs already, so what you really want is: state_to_abbrev = dict(zip(states, abbreviations))
answers question: http://stackoverflow.com/q/49227337
type: Answer

http://stackoverflow.com/comment/85299535
score: 0
comment on: http://stackoverflow.com/q/49147264
type: Comment
type: QuestionComment
has text: Are you using windows? If so have you try to change the code page? https://knowledgebase.progress.com/articles/Article/4677

http://stackoverflow.com/a/49234972
has comment: http://stackoverflow.com/comment/85474056
type: AcceptedAnswer
has body: First convert dict to Series and then use MultiLabelBinarizer + DataFrame constructor, last cast to boolean: d = {"word1": ["a","b","c"], "word2": ["b", "d", "e"], "word3": ["a", "f", "c"]} s = pd.Series(d) from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer() df = pd.DataFrame(mlb.fit_transform(s),columns=mlb.classes_, index=s.index).astype(bool) Another solution with str.join for joining by | what is default separator in str.get_dummies: df = s.str.join('|').str.get_dummies().astype(bool) print (df) a b c d e f word1 True True True False False False word2 False True False True True False word3 True False True False False True
accepted answer of: http://stackoverflow.com/q/49234890
answers question: http://stackoverflow.com/q/49234890
type: Answer
upvote count: 2
score: 2
downvote count: 0

http://stackoverflow.com/comment/85481261
comment on: http://stackoverflow.com/q/49238795
type: Comment
score: 4
type: QuestionComment
has text: Possible duplicate of [Index of a random item from a list](https://stackoverflow.com/questions/49236418/index-of-a-random-item-from-a-list)

http://stackoverflow.com/comment/95343295
has text: see my edit were rolled back- will leave this comment instead- as the accepted answer shows finally does not always win and I think the top summary of this answer is misleading
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49262555
type: AnswerComment

http://stackoverflow.com/q/49263739
has title: Import many txt files and name df as filename
has body: I have a folder full of txt files and I want to import each as their own df. I want to call each df the same name as the txt file. This is what I have to read in all files: import pandas as pd import glob path =r'D:\Path\to\ files' allFiles = glob.glob(path + "/*.txt") for file_ in allFiles: df = pd.read_csv(file_,index_col=None, header=0) Instead of each df being called df I would like it to be the *.txt filename.
score: 0
duplicate of: http://stackoverflow.com/q/1373164
tagged with: glob
tagged with: pandas
has answer: http://stackoverflow.com/a/49264000
type: Question
answer count: 2
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164
has comment: http://stackoverflow.com/comment/85531101
linked to: http://stackoverflow.com/q/11553721
tagged with: dataframe
tagged with: python
has answer: http://stackoverflow.com/a/49264007

flowchart
tag name: flowchart
tags question: http://stackoverflow.com/q/49145259
type: Tag

http://stackoverflow.com/q/49156075
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85320479
score: 0
tagged with: math
tagged with: python
has body: I've been having a bit of trouble understanding how this works. If I have multiple documents containing a lot of words each, and a single word that may be contained in the documents, how can I tell what the angle is between the word and these documents? For instance if docs.txt contains "This world is fake" and queries.txt contains "fake" how do I know what the angle of similarity between them is? I've found this info: "When representing a document as a vector, each vector component represents the number of times the corresponding word in the dictionary appears in the document." and "When representing a search query as a vector, each vector component represents whether the corresponding word in the dictionary appears in the search query (1 if it does and 0 otherwise)." but I don't really know how I'd make the "fake" string a vector or how to find the angle between it and the docs.txt. I'd like to code this in python but I'm pretty bad at math. If anyone has any advice that would be awesome, thank you!
has title: Python - Angle Between Search Query and Document
type: Question
has comment: http://stackoverflow.com/comment/85320278
answer count: 0
has comment: http://stackoverflow.com/comment/85317084

http://stackoverflow.com/comment/85386078
comment on: http://stackoverflow.com/q/49188811
type: QuestionComment
type: Comment
score: 0
has text: You need to give a clear problem description. This could be related to a recently introduced bug, see [this question](https://stackoverflow.com/questions/49183656/animation-freezes-after-a-number-of-frames-after-upgrading-matplotlib), but it could also be caused by something completely different. See [mcve].

http://stackoverflow.com/comment/85471917
comment on: http://stackoverflow.com/q/49232441
has text: @UbdusSamad Thank you. It is the same issue but it seems that their solution is to not print it. But whether I print it or not, the dataset doesn't work.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/51845825
downvote count: 0
has body: Use signals. user_registered signal is emitted after successful user registration. Its subscriber can do every necessary initialization: from flask_user import user_registered @user_registered.connect_via(app) def _after_user_registered_hook(sender, user, user_invite, **extra): role = Role.query.filter_by(name='Agent').one() user.roles.append(role) app.user_manager.db_adapter.commit()
has comment: http://stackoverflow.com/comment/97718206
type: Answer
answers question: http://stackoverflow.com/q/49215197
upvote count: 2
score: 2

http://stackoverflow.com/q/49224287
has comment: http://stackoverflow.com/comment/85469589
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85485540
has title: Half-bolded edges in networkx
tagged with: python
score: 0
answer count: 0
has comment: http://stackoverflow.com/comment/85452539
type: UnansweredQuestion
type: Question
has body: I'm creating a graph from a scipy sparse matrix, and I can't understand why the edges are half-bolded. from Mar11_daily_utils import * import numpy as np from scipy import sparse import matplotlib matplotlib.use('pdf') import matplotlib.pyplot as plt import networkx as nx if __name__=='__main__': bin_adj_mats_file = "../binary_adj_mats_daily.pkl" adj_orig, features = read_data('', bin_adj_mats_file, False) graph_vals = nx.from_scipy_sparse_matrix(adj_orig[adj_orig.keys()[0]], create_using=nx.DiGraph()) node_degrees = list(graph_vals.degree(graph_vals.nodes()).values()) node_degrees_use = [index for index, value in enumerate(node_degrees) if value &gt; 0.] subgraph_vals = graph_vals.subgraph(node_degrees_use) options = { 'node_color': 'black', 'node_size': 3, 'line_color': 'red', 'linewidths': 0.1, 'width': 0.1 } nx.draw(subgraph_vals, **options) plt.savefig('daily_so_graph_day_1.png') #len(subgraph_vals.node) says there are 414 nodes. It looks like this: How can I make it such that the edges are not half-bolded, but are just thin lines?

http://stackoverflow.com/comment/85541023
type: QuestionComment
comment on: http://stackoverflow.com/q/49268864
has text: Did you try a regular expression?
score: 1
type: Comment

http://stackoverflow.com/q/49226665
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49226797
score: 0
has answer: http://stackoverflow.com/a/49226797
tagged with: lxml
has title: Is Python '\u2029' an XML incompatible Unicode?
has comment: http://stackoverflow.com/comment/85457294
has body: I'm using Python 3.6.4 with lxml 4.1.1. When reading/parsing the etree, I escape 12 Unicode separator characters. The PSEP looks like this: line = line.replace('\u2029', ' %(#u2029)s ' After a lot of filtering/processing, I save the line to a new XML file with this code: seg = etree.SubElement(tuv, 'seg') seg.text = line.replace('%(#u2029)s', '\u2029') Which produces the following traceback: Traceback (most recent call last): File "C:\process-tmx\", line 267, in run seg.text = line.replace('%(#u2029)s', '\u2029') File "src\lxml\xtree.pyx", line 1033, in lxml.etree._Element.text.__set__ (src\lxml\etree.c:55075) File "src\lxml\apihelpers.pxi", line 716, in lxml.etree._setNodeText (src\lxml\etree.c:25862) File "src\lxml\apihelpers.pxi", line 704, in lxml.etree._createTextNode (src\lxml\etree.c:25725) File "src\lxml\apihelpers.pxi", line 1444, in lxml.etree._utf8(src\lxml\etree.c:32944) ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters Does this mean that '\u2029' is an XML incompatible Unicode? How do I XML escape it? Thanks
type: Question
has comment: http://stackoverflow.com/comment/85457218
tagged with: separator
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85457298

http://stackoverflow.com/q/49176619
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49176757
has body: In many of my projects, I come across the following pattern of Python loops: for idx, item in enumerate(items): # apply and accumulate state = f(state, item) # display status/log something depending on state/item/iteration side_effect(idx, state, item) Now if I want to abstract the handling of side effects, it gets complicated. For example, I want to print the first 10 items, then just dots and finally the last item: for idx, item in enumerate(items): # apply and accumulate state = f(state, item) # display status/log something depending on state/item/iteration if idx &lt; 10: print(item) elif idx == 10: print('...') if idx &gt;= 10: print(item) # in general, we cannot assume how many items there are, but # it's a bit ugly imo because item is out of scope here # if we solve this by keeping a reference to last item, it's worse imo Let's say I want to make this behavior generic for many loops. For this, I'm using a context manager around the loop, which is also called inside the loop to handle the side effects, like so: with Printer(...) as printer: for idx, item in enumerate(items): # apply and accumulate state = f(state, item) # display status/log something depending on state/item/iteration printer.do_your_thang(item) The printer keeps track of the iteration and can even act when the loop is done on __exit__, thus can still update its status at this point The problem I have with this is that it adds an indent for each loop where such a context manager is used, and the context manager is not tied to the loop. Do you have a better idea of solving this ?
tagged with: python
has title: How to manage side effects in Python loops?
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/85358904
accepted answer: http://stackoverflow.com/a/49176757
upvote count: 2
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85385023
tagged with: iteration
type: Question
tagged with: side-effects

http://stackoverflow.com/q/49175291
linked to: http://stackoverflow.com/q/14872307
has comment: http://stackoverflow.com/comment/85356448
type: AnsweredQuestion
has title: Django: Find an item in a list that is not in Database
accepted answer: http://stackoverflow.com/a/49175582
upvote count: 3
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/49175582
favorite count: 0
type: Question
has body: I have a list and I want to find whether any items in this list are not in the database. Using the object.exclude() Django function I only find which elements are in my database that are not in my list: Gene.objects.exclude(gene_name__in=self.gene_list) I am currently getting the items I have in my list that aren't in the database using this code: obj = Gene.objects.filter(gene_name__in=self.gene_list) database_genes = [o.gene_name for o in obj] genes_not_in_db = [g for g in self.gene_list if g not in database_genes] This is however rather messy - is there a better way / inbuilt Django function to do this? Thanks
score: 3
tagged with: django
tagged with: python

http://stackoverflow.com/comment/85492335
comment on: http://stackoverflow.com/a/49243787
score: 1
type: Comment
has text: Duly noted. touche.
type: AnswerComment

http://stackoverflow.com/comment/85399120
comment on: http://stackoverflow.com/q/49194895
type: QuestionComment
score: 0
has text: How will pandas know those players align to those categories? Is there a mapping data of some kind? Does Python need to crawl the internet to find these names and their league associations?
type: Comment

http://stackoverflow.com/a/64078784
answers question: http://stackoverflow.com/q/49179633
has body: Just use "utf-16" instead of "utf_8".
type: Answer
score: 0

http://stackoverflow.com/comment/85327761
score: 3
comment on: http://stackoverflow.com/q/49153714
type: Comment
type: QuestionComment
has text: @NH. Shame about the formatting of your comment. :(

http://stackoverflow.com/comment/85312755
type: Comment
comment on: http://stackoverflow.com/q/49154097
score: 0
type: QuestionComment
has text: And your code should probably not trust the client for what amount to charge, do that calculation on the backend.

http://stackoverflow.com/a/49217694
score: 0
answers question: http://stackoverflow.com/q/49217587
downvote count: 1
type: Answer
upvote count: 1
has body: Using PIL to encode the array as an image is one way to go - img_bw = np.ones([100,100], dtype=np.uint8)*255 img = Image.fromarray(img_bw) img.show() Output For black, if you just change to img_bw = np.ones([100,100], dtype=np.uint8)*0 you get -

http://stackoverflow.com/a/49227897
has comment: http://stackoverflow.com/comment/85460336
has comment: http://stackoverflow.com/comment/85460575
has comment: http://stackoverflow.com/comment/85460518
has comment: http://stackoverflow.com/comment/85459859
has comment: http://stackoverflow.com/comment/85460613
has comment: http://stackoverflow.com/comment/85460573
has comment: http://stackoverflow.com/comment/85459556
answers question: http://stackoverflow.com/q/49227864
score: 1
has body: You can get the union of both sets using the logical or operator | a = set(['a', 'b', 'c']) b = set(['c', 'd', 'e']) c = a | b print(c) {'e', 'a', 'b', 'd', 'c'} If you want the set ordered and as a list c = sorted(list(c)) print(c) ['a', 'b', 'c', 'd', 'e']
has comment: http://stackoverflow.com/comment/85460084
type: Answer
has comment: http://stackoverflow.com/comment/85459891
upvote count: 2
has comment: http://stackoverflow.com/comment/85460101
has comment: http://stackoverflow.com/comment/85459915
downvote count: 1

http://stackoverflow.com/q/49214393
has answer: http://stackoverflow.com/a/49214405
type: AnsweredQuestion
has title: How to take input even when the console app is not the focused one in Python
has body: import pyperclip text = input("Enter the text: ") y = -2 def PrintAndWait(x): global y print(text[y+2:x+1], end="") pyperclip.copy(text[y+2:x+1]) waitingForEnter = input() y = x for x in range (0,len(text)): if text[x] == "." or text[x] == "?" or text[x] == "!": PrintAndWait(x) code I made this app that takes a text and splits into sentences and sends a sentence at a time to the clipboard when there's any input from the keyboard. How can I make it so it does this but when I press a key but the console isn't focused (I mean I'm not directly writing into it)? I want to make this so I can send a larger text into a conversation one sentence at a time.
score: 0
answer count: 1
type: Question
tagged with: python-3.x
tagged with: python
accepted answer: http://stackoverflow.com/a/49214405

http://stackoverflow.com/a/49215716
type: Answer
has comment: http://stackoverflow.com/comment/85436978
score: 0
has comment: http://stackoverflow.com/comment/85436803
upvote count: 1
has body: Here is another way to get the desired result using groupby and size d1 = {'num': [23,34,89,90], 'type': ['a', 'b', 'a', 'c']} d2 = {'num': [23,34,56,90], 'type': ['a', 'b', 'a', 'c']} d3 = {'num': [56,34,71,90], 'type': ['a', 's', 'a', 'c']} df1 = pd.DataFrame(data=d1) df2 = pd.DataFrame(data=d2) df3 = pd.DataFrame(data=d3) df10 = pd.concat([df1,df2,df3], axis=0) # Using groupby with 'num' and 'type' and then using size to get the count. # resent_index(name='count') will name the size column as 'count' df20 = df10.groupby(['num','type']).size().reset_index(name='count') # getting the index with 'count' &gt;= 2 and storing those in df_out. df_out = df20[df20['count'] &gt;=2].reset_index(drop=True) print(df_out) The output looks like: num type count 0 23 a 2 1 34 b 2 2 56 a 2 3 90 c 3 For reference print(df20) num type count 0 23 a 2 1 34 b 2 2 34 s 1 3 56 a 2 4 71 a 1 5 89 a 1 6 90 c 3
downvote count: 1
answers question: http://stackoverflow.com/q/49214286

http://stackoverflow.com/a/49269172
answers question: http://stackoverflow.com/q/49268864
downvote count: 0
score: 1
upvote count: 1
type: Answer
has body: #!python2 import re mystring = "owner: uid=rocdsc,ou=People,dc=fcd,dc=test,dc=com, member: uid=absylor12,ou=people,dc=fcd,dc=test,dc=com, member: uid=amslsmith,ou=people,dc=fcd,dc=test,dc=com, member: uid=amis,ou=people,dc=fcd,dc=test,dc=com, member:, uid=null,ou=people,dc=fcd,dc=test,dc=com" # pattern definition p = 'uid=' # holds user names users = [] # split string on a space or a comma, find user id, append to list for item in re.split(' |,|', mystring): if item.startswith(p): users.append(item.replace(p, '')) print users

http://stackoverflow.com/q/49266894
answer count: 1
downvote count: 0
upvote count: 1
tagged with: tensorflow
favorite count: 0
type: Question
tagged with: tensorflow-slim
tagged with: reproducible-research
type: UnansweredQuestion
tagged with: python
has title: Writing summaries in Tensorflow leads to extra evaluation of graph
has answer: http://stackoverflow.com/a/49270329
has body: Writing summaries using Tensorflow Supervisor re-evaluates the graph which can have undesired consequences. One such consequence is changing the random state and in turn affecting reproducibility. I have written a small example to demonstrate this affect. import tensorflow as tf N = 5 SEED = 123 with tf.Graph().as_default(): tf.set_random_seed(SEED) a = tf.random_uniform([1]) with tf.Session() as sess: for i in range(N): print(sess.run([a])) # result: [0.31000066],[0.36025488],[0.9802418],[0.94300663],[0.03890145] with tf.Graph().as_default(): tf.set_random_seed(SEED) a = tf.random_uniform([1]) summary = tf.summary.scalar(name='a', tensor=a[0]) sv = tf.train.Supervisor(logdir="./tmp", summary_op=summary, save_summaries_secs=0.1) with sv.managed_session() as sess: for _ in range(N): print(sess.run(a)) # result of first run: [0.9802418],[0.94300663],[0.03890145],[0.2266953],[0.42769837] # result of second run:[0.36025488],[0.9802418],[0.94300663],[0.03890145],[0.2266953] In the example above, I define two graphs both with the same graph-level random seed. In the second graph, I write summaries using tf.train.Supervisor. Then I generate N random numbers by evaluating each graph N times. The graph with the summary writer “skips” some random numbers; so depending on when the summaries are written in relation to the global step, you get randomly different results. Another example where this affect has undesired consequences is when you use batching with Tensorflow record reader and writing summaries with the Supervisor leads to consumption of an extra batch of data per summary writing due to the extra graph evaluation. This also affects the behavior of all tools that depend on the Supervisor, such as Tensorflow-slim. Is there a conventional way to communicate to the Supervisor to collect ops and their respective summaries in the same graph evaluation? I suppose one could work around this by defining dependencies between ops and their summaries, and passing summary_op=None…
score: 1

http://stackoverflow.com/a/50297147
upvote count: 8
answers question: http://stackoverflow.com/q/49271586
type: Answer
score: 8
has body: For unittest.mock try importing items as from unittest import mock instead of from unittest.mock import patch This worked around the bug for me.
downvote count: 0

http://stackoverflow.com/comment/85489311
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49242698
type: AnswerComment
has text: Sorry, how about the case when all `cohort` values do not see an `age` of -1? I updated the question to reflect this. In this case the R code doesn't work either.

http://stackoverflow.com/comment/85440609
has text: I suggest you share this example code with us. Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
type: Comment
comment on: http://stackoverflow.com/q/49213552
type: QuestionComment
score: 0

http://stackoverflow.com/q/49240478
tagged with: datetime
tagged with: django-models
tagged with: django-serializer
type: Question
has comment: http://stackoverflow.com/comment/85593113
has comment: http://stackoverflow.com/comment/85584556
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85593064
tagged with: python
has comment: http://stackoverflow.com/comment/85593389
score: 0
has body: I want to format a datetime.datetime in the template with: but I found that the values generated by the serializer are all strings, not of their original type. When I just print them they are good; but if I want to format the date, I got empty string. My model: class TScript(models.Model): id = models.AutoField(primary_key=True) category = ForeignKey(TCategory, PROTECT, null=False, blank=False, to_field='name') # protect TScript from deletion; TScript belongs to TCategory service = ForeignKey(TService, PROTECT, null=False, blank=False, to_field='name') platform = ForeignKey(TPlatform, PROTECT, null=False, blank=False, to_field='name') command = models.CharField(max_length=1024, blank=False, null=False) machine = models.CharField(max_length=64, blank=False, null=False) username = models.CharField(max_length=150, blank=False, null=False) # now save as string to avoid problem interval = models.IntegerField(blank=False, null=False) # seconds timeout = models.IntegerField(blank=False, null=False) # seconds status = models.IntegerField(blank=False, null=False) out = models.CharField(max_length=1024, blank=True, null=True) error = models.CharField(max_length=512, blank=True, null=True) description = models.CharField(max_length=256, blank=True, null=True) lastrundate = models.DateTimeField(null=True) insertDate = models.DateTimeField(auto_now_add=True) My serializer: class TScriptSerializer(serializers.ModelSerializer): lastrundate = serializers.DateTimeField() # I changed here but not working class Meta: model = TScript fields = ['id', 'category', 'service', 'platform', 'command', 'machine', 'username', 'interval', 'out', 'error', 'timeout', 'status', 'description', 'lastrundate', 'insertDate'] My view methods: @login_required @csrf_protect def scriptsList(request): logger.info("SCRIPTSLIST Start HTML") try: scripts=operationsDB.getScripts() return render(request, 'tablescripts.html', {"scripts":scripts}) ex…
answer count: 0
has comment: http://stackoverflow.com/comment/85592747
has title: django serializer - how to pass datetime from DB to view - 'argument must be 9-item sequence, not datetime.datetime'

http://stackoverflow.com/comment/113817629
type: AnswerComment
score: 1
type: Comment
comment on: http://stackoverflow.com/a/54717411
has text: If you want to suggest moving to an API, one which is commercial by the way, you should also detail why the user should consider this API, which are its potential benefits and why they outweigh any alternative implementations. Not everyone is willing to pay money for an API just to extract this information.

http://stackoverflow.com/comment/85356044
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49175373
has text: @PatrickHaugh Please post your comment as an answer so it can be properly evaluated. Comments are for clarifications.

http://stackoverflow.com/q/49221817
tagged with: docstring
has title: Calling docstrings from module
has comment: http://stackoverflow.com/comment/85447420
has comment: http://stackoverflow.com/comment/85447704
has comment: http://stackoverflow.com/comment/85447445
has comment: http://stackoverflow.com/comment/85447408
downvote count: 0
has comment: http://stackoverflow.com/comment/85447503
has comment: http://stackoverflow.com/comment/85447144
has comment: http://stackoverflow.com/comment/85447525
score: 1
upvote count: 1
answer count: 1
favorite count: 0
type: Question
has body: I have a module and I'm trying to call the docstrings using the help function. Here is the module: """Retrieve and print words from a URL. Usage: py words.py &lt;URL&gt; """ import sys from urllib.request import urlopen def fetch_words(url): """Fetch a list of words from a URL. Args: url: The URL of a UTF-8 text docuemnt. Returns: A list of strings containing the words from the document. """ with urlopen(url) as story: story_words = [] for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) return story_words def print_items(items): """Print items one per line. Args: url: The URL of a UTF-8 text. """ for item in items: print(item) def main(url): """Print each words form a text document from a URL. Args: url: The URL of a UTF -8 text document. """ words = fetch_words(url) print_items(words) if __name__ == '__main__': main(sys.argv[1]) When I type the command help(words) I get Help on module words: NAME words FUNCTIONS fetch_words() FILE c:\users\cacheson\pyfund\words.py Any help would be greatly appreciated
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85447368
has answer: http://stackoverflow.com/a/49221886
tagged with: python

http://stackoverflow.com/comment/85330680
type: Comment
type: QuestionComment
has text: What is annoying is that you asked 2 questions and left a comment under a third one for this problem, all without linking between them. It's a hell of work to understand the problem if you don't synchronize your efforts.
comment on: http://stackoverflow.com/q/49156484
score: 1

http://stackoverflow.com/q/49213730
tagged with: python
has body: Problem: After I updated VS Code to version 1.21.0 the Pylint Linter does not work. I receive no linting errors in the problems tab inside of VS Code. I deliberately made some errors to confirm this behaviour. Expected result: When I make a style error I expect my linter to notify my like it did before. What have I tried? Pylint I checked that pylint is installed. I updated pylint using PIP while I was at it. I tried enabling another Linter (Pep8), but these also didn't give me the expected result VS Code I checked my VS Code settings that linting is enabled. I have installed VS code insiders build. Here there was no problem, my code was being linted. I copied my settings from VS code to the insider build, to double check. Since it works on the insiders build, it can't be a PATH issue. previously it also worked on the normal build, so a PATH issue is out of the question i think. I prefer to use the stable release. I tried the command: "Python: Enable Linting". The following error message appeared in VS Code: VS Code error message Other commands associated with the Python extension result in a similar error: Other error message These commands do not result in an error on the insider build. General I have removed the Python extension and reinstalled it. I have removed VS Code and reinstalled it. Both resulted in the same problem as before . Search I searched GitHub issues. I searched Stack overflow questions. I searched the official documentation. Both VS code documentation as Pylint documentation as well as the Python extension documentation. Question Did I miss anything in my testing that could solve this issue? Is this a bug that I should report? If so, is this a VS Code bug? a Python extension bug? My VS Code USER SETTINGS: { "workbench.startupEditor": "newUntitledFile", "git.ignoreMissingGitWarning": true, "workbench.colorTheme": "Monokai", "[python]": { }, "python.linting.pylintUseMinimalCheckers": false, "explorer.sortOrder": "type", "editor.rulers": [ 79 ], "f…
has comment: http://stackoverflow.com/comment/85438831
score: 2
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49344611
has answer: http://stackoverflow.com/a/49344611
has title: VS code doesn't lint my code, but the insider build does
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85437813
tagged with: visual-studio-code
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/85462297
downvote count: 0
tagged with: pylint

http://stackoverflow.com/comment/85319630
score: 0
has text: You mean this string-'1496\n8584\n172\n5988\n7184\n704\n3448\n6580\n8504\n'
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49157419

http://stackoverflow.com/q/49137639
accepted answer: http://stackoverflow.com/a/49137735
tagged with: substring
has title: Select string between two substrings to every row in dataframe in Python
favorite count: 0
type: Question
upvote count: 4
tagged with: python-3.x
answer count: 1
downvote count: 0
tagged with: string
has body: I want to be able to select a string between two specific substrings (as the following), but with a loop that will iterate through every row in the dataframe. CODE: import pandas as pd df = pd.DataFrame(['first: hello1 \nSecond this1 is1 a1 third: test1\n', 'first: hello2 \nSecond this2 is2 a2 third: test2\n', 'first: hello3 \nSecond this3 is3 a3 third: test3\n']) df = df.rename(columns={0: "text"}) def find_between(df, start, end): return (df.split(start))[1].split(end)[0] df2 = df['text'][0] print(find_between(df3, 'first:', '\nSecond')) [OUTPUT NEEDED] Dataframe with following information: output 0 hello1 1 hello2 2 hello3 the find_between() function is created based on Find string between two substrings, but here you're only able to do that for one specific variable (df2) that is already saved as a string, as the shown example. I need to be able to do that for every row (strings) in the 'df' dataframe. I would really much appreciate if anyone can help me with this! Thank you!
score: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49137735
linked to: http://stackoverflow.com/q/3368969
tagged with: pandas
tagged with: python

http://stackoverflow.com/q/49142382
answer count: 1
has body: I have a User and a Deal model as shown below. The User model has a 'favorites' field which is a many to many relationship with the Deal model. I'm trying to allow a user to save a Deal to their Favorites. I have tested both the favorite and remove_favorite views and both are doing exactly what they are supposed to do. Here's My Issue -- The conditional statement on my deal_detail.html page which checks to see if the current deal on the page is a favorite of the logged in user doesn't seem to be working. {% if deal_detail in user.favorites %} I'm just having a hard time wrapping my head around how to check this. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, error_messages={'unique':"This email has already been registered."}) username = models.CharField(max_length=40, default='') first_name = models.CharField(max_length=40, default='', blank=True) last_name = models.CharField(max_length=40, default='', blank=True) date_joined = models.DateTimeField(default=timezone.now) favorites = models.ManyToManyField(Deal, related_name='favorited_by', null=True, blank=True) class Deal(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=140, unique=True) description = models.TextField(default='') My corresponding views look like this: def deal_by_detail(request, slug): deal_detail = Deal.objects.get(slug=slug) user = request.user return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail, 'user': user}) @login_required(login_url='/accounts/sign_in/') def favorite(request, pk): if request.method == 'POST': favorite = Deal.objects.get(pk=pk) user = request.user user.favorites.add(favorite) messages.add_message(request, messages.INFO, 'Deal Favorited.') return redirect('home') @login_required(login_url='/accounts/sign_in/') def remove_favorite(request, pk): if request.method == 'POST': favorite = Deal.objects.get(pk=pk) user = request.user user.favorites.remove(favorite) messages.add_mes…
tagged with: django
type: Question
accepted answer: http://stackoverflow.com/a/49143176
type: AnsweredQuestion
score: 0
tagged with: python
has title: Django - Query To Check if Item In Many to Many Relationship Field
has answer: http://stackoverflow.com/a/49143176

http://stackoverflow.com/q/49175961
accepted answer: http://stackoverflow.com/a/49176913
score: 18
upvote count: 18
tagged with: python
has answer: http://stackoverflow.com/a/49176557
tagged with: lstm
type: AnsweredQuestion
answer count: 3
has answer: http://stackoverflow.com/a/49176913
downvote count: 0
tagged with: machine-learning
has body: I am training a LSTM model with Keras on the dataset which looks like following. The variable "Description" is a text field and "Age" and "Gender" are categorical and continuous fields. Age, Gender, Description 22, M, "purchased a phone" 35, F, "shopping for kids" I am using word-embedding to convert the text fields to word vectors and then input it in the keras model. The code is given below: model = Sequential() model.add(Embedding(word_index, 300, weights=[embedding_matrix], input_length=70, trainable=False)) model.add(LSTM(300, dropout=0.3, recurrent_dropout=0.3)) model.add(Dropout(0.6)) model.add(Dense(1)) model.add(Activation('sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics['accuracy']) This model is running successfully but I want to input "age" and "gender" variables as features as well. What changes are required in the code to use these features as well ?
has comment: http://stackoverflow.com/comment/91202328
tagged with: keras
has answer: http://stackoverflow.com/a/56993864
possible better answer: http://stackoverflow.com/a/56993864
tagged with: tensorflow
favorite count: 0
type: Question
has title: How to use additional features along with word embeddings in Keras ?

http://stackoverflow.com/q/49210078
type: AnsweredQuestion
score: 3
has title: Binarize image data
has comment: http://stackoverflow.com/comment/85432718
answer count: 3
has comment: http://stackoverflow.com/comment/85432281
has comment: http://stackoverflow.com/comment/85426233
tagged with: python
tagged with: image-processing
has body: I have 10 greyscale brain MRI scans from BrainWeb. They are stored as a 4d numpy array, brains, with shape (10, 181, 217, 181). Each of the 10 brains is made up of 181 slices along the z-plane (going through the top of the head to the neck) where each slice is 181 pixels by 217 pixels in the x (ear to ear) and y (eyes to back of head) planes respectively. All of the brains are type dtype('float64'). The maximum pixel intensity across all brains is ~1328 and the minimum is ~0. For example, for the first brain, I calculate this by brains[0].max() giving 1328.338086605072 and brains[0].min() giving 0.0003886114541273855. Below is a plot of a slice of a brain[0]: I want to binarize all these brain images by rescaling the pixel intensities from [0, 1328] to {0, 1}. Is my method correct? I do this by first normalising the pixel intensities to [0, 1]: normalized_brains = brains/1328 And then by using the binomial distribution to binarize each pixel: binarized_brains = np.random.binomial(1, (normalized_brains)) The plotted result looks correct: A 0 pixel intensity represents black (background) and 1 pixel intensity represents white (brain). I experimented by implementing another method to normalise an image from this post but it gave me just a black image. This is because np.finfo(np.float64) is 1.7976931348623157e+308, so the normalization step normalized_brains = brains/1.7976931348623157e+308 just returned an array of zeros which in the binarizition step also led to an array of zeros. Am I binarising my images using a correct method?
accepted answer: http://stackoverflow.com/a/49216843
type: Question
tagged with: numpy
upvote count: 3
has answer: http://stackoverflow.com/a/52967370
has answer: http://stackoverflow.com/a/49211238
possible better answer: http://stackoverflow.com/a/49211238
downvote count: 0
tagged with: voxel
tagged with: computer-vision
linked to: http://stackoverflow.com/q/46689428
has answer: http://stackoverflow.com/a/49216843
favorite count: 0

http://stackoverflow.com/comment/85570765
type: QuestionComment
score: 0
has text: The `apply` functions don't speed things up - they are just convenient (sometimes) ways of iterating. As long as your function has to be called with scalars or arrays of limited dimension, you have to iterate over the other axes (even if it is hidden by some numpy utility function).
type: Comment
comment on: http://stackoverflow.com/q/49276039

http://stackoverflow.com/comment/85431949
type: AnswerComment
has text: Thank you for the response. I tried that and I get another error: "AttributeError: 'bytes' object has no attribute 'timeout'" I checked what actually gets passed into urlopen and it is the following: b'http://www.google.com/\xef\xbb\xbf'
type: Comment
comment on: http://stackoverflow.com/a/49212101
score: 0

http://stackoverflow.com/comment/85541227
comment on: http://stackoverflow.com/q/49262649
score: 0
has text: @Jean-Paul Calderone Thanks for the suggestions. I will add one.
type: QuestionComment
type: Comment

http://stackoverflow.com/q/49134593
upvote count: 3
has comment: http://stackoverflow.com/comment/85339934
has comment: http://stackoverflow.com/comment/85313817
tagged with: machine-learning
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/85328352
has title: how to expand the words of tfidf vectorizer in sklearn without retraining the whole model from scratch?
downvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85273853
has body: I have a bunch of text documents that I throw at a tfidf vectorizer which I further use for multi-label text classification. I will keep getting a stream of more documents in the future. Now how do I add new words to the vectorizer it has never seen before without retraining the model from scratch? Is partial_fit the only option, cause OvR and pipeline don't work with it? Here is the link I am talking about online learning of text documents.
tagged with: tfidfvectorizer
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85294066
tagged with: python
tagged with: nlp
linked to: http://stackoverflow.com/q/39109743
score: 2
has comment: http://stackoverflow.com/comment/85410138
answer count: 0
has comment: http://stackoverflow.com/comment/85294197

http://stackoverflow.com/a/55215258
upvote count: 1
has body: You were just opening the text file and not reading the same meaning the content of the same file would not get recorded as a string and also you were just passing your file to nltk to tokenize sentences which is only possible when you provide nltk with string type input. Hope you understand. Thanks :)
score: 1
answers question: http://stackoverflow.com/q/49216339
downvote count: 0
type: Answer

http://stackoverflow.com/a/49264863
score: 0
answers question: http://stackoverflow.com/q/49260932
type: Answer
has body: This will reference the pandas dataframe column names: plt.yticks(pos, df.columns.values)

http://stackoverflow.com/q/49204861
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/85415148
answer count: 1
has answer: http://stackoverflow.com/a/49204993
has comment: http://stackoverflow.com/comment/85415053
type: Question
linked to: http://stackoverflow.com/q/5902371
has body: So I want to generate a chart graph from a csv data file, and I've been following a guide but I can't seem to manipulate my code in such a way to get what I want. So here is what I have so far: from pandas import DataFrame, read_csv import matplotlib.pyplot as plt import pandas as pd import sys import matplotlib df = pd.read_csv("TB_burden_countries_2018-03-06.csv") df = df.set_index(['country']) df2 = df.loc["Zimbabwe", "e_mort_num"] df2 = df.loc["Zimbabwe", "e_mort_num"] df = pd.DataFrame(data = df2, columns= ["e_mort_num"]) df.columns = ["Mortality"] print(df2) This code was just so I can choose a specific country (Zimbabwe) and look at its population number (e_mort_num). What could I write to generate a chart graph? I've been using this tutorial : http://pbpython.com/simple-graphing-pandas.html, but I'm having trouble manipulating variable names, a I'm not too sure what I should be doing. If you require more information, please say so. Thank you for your help! CSV bit of interest: Country Year Mortality Zimbabwe 2000 20000 Zimbabwe 2001 18000 Zimbabwe 2002 17000 Zimbabwe 2003 19000 Zimbabwe 2004 19000 Zimbabwe 2005 22000 Zimbabwe 2006 24000 Zimbabwe 2007 24000 Zimbabwe 2008 23000 Zimbabwe 2009 17000 Zimbabwe 2010 13000 Zimbabwe 2011 14000 Zimbabwe 2012 14000 Zimbabwe 2013 11000 Zimbabwe 2014 11000 Zimbabwe 2015 9000 Zimbabwe 2016 5600
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85415044
duplicate of: http://stackoverflow.com/q/5902371
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/85414999
has comment: http://stackoverflow.com/comment/85415149
tagged with: python
has comment: http://stackoverflow.com/comment/85415221
has title: Pandas/Python - Generating a chart
has comment: http://stackoverflow.com/comment/85415000

http://stackoverflow.com/comment/85526432
has text: Yes that should work and the `except` allows it to also hit the end without an error message.
type: Comment
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49261264

http://stackoverflow.com/comment/85431318
score: 1
has text: It looks like one of your URLs in your CSV has a typo e.g. `https>` rather than `https://`, try adding a `print url` so you can see which URLs are causing a problem.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49212897

http://stackoverflow.com/comment/85343903
has text: Why are you using a class here? Why not just a plain function? There really is no need for all this state. Anyway, your error stems from using `fibb` instead of `self.fibb`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/49169303
type: QuestionComment

http://stackoverflow.com/q/49184989
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/85375735
tagged with: super
has answer: http://stackoverflow.com/a/49185068
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/85375816
type: Question
accepted answer: http://stackoverflow.com/a/49185068
has body: class Person: def __init__(self, name): self.name = name # Getter function @property def name(self): return self._name # Setter function @name.setter def name(self, value): if not isinstance(value, str): raise TypeError('Expected a string') print(self) self._name = value # Deleter function @name.deleter def name(self): raise AttributeError("Can't delete attribute") class SubPerson(Person): @property def name(self): print('Getting name') return super().name @name.setter def name(self, value): print('Setting name to', value) super(SubPerson, SubPerson).name.__set__(self, value) @name.deleter def name(self): print('Deleting name') super(SubPerson, SubPerson).name.__delete__(self) s = SubPerson('Guido') print(s.name) when i make the super(SubPerson, SubPerson).name.__set__(self, value) to super(SubPerson, self).name.__set__(self, value), i get this issue AttributeError: 'SubPerson' object has no attribute '_name' Why?
has title: what is the difference between super(type, obj) and super(type, type)
upvote count: 1
tagged with: python

http://stackoverflow.com/a/49252746
accepted answer of: http://stackoverflow.com/q/49238036
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49238036
has comment: http://stackoverflow.com/comment/102812793
has body: Ok, thanks for answers. I like using pylint to help me coding better and I was hoping that the pylint project explains and arguments somewhere the warnings with details useful for beginners like me: helping to: understand why it is important to consider these warnings when a certain context can moderate the point of view when it came from a PEP etc. It looks like it is not the case. Anyway, although it is really not filled-in/detailed enough, Pylint messages (which I found before asking my question) remain the least bad answer to my question.
upvote count: 2
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/comment/85396925
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49195844
has text: I understood what you did. I tried the same but it is not giving the desirable results either. The red plot shifts completely to the right of the blue plot whereas I wanted the red plot to be superimposed over the blue plot for values 101-150. Like I have the plot for `test1` from 1-150. Then on the same graph and axis, I have the plot of `predictions1` from 101-150.

http://stackoverflow.com/comment/85296381
type: AnswerComment
comment on: http://stackoverflow.com/a/49144891
score: 0
has text: Thank you for your help, I wasn't reading it properly But I found out what I was doing wrong. Thank you very much this helped me alot.
type: Comment

http://stackoverflow.com/comment/85536965
comment on: http://stackoverflow.com/q/49249996
has text: Possible duplicate of [How to create a global hotkey on Windows with 3 arguments?](https://stackoverflow.com/questions/16615087/how-to-create-a-global-hotkey-on-windows-with-3-arguments)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49223250
type: Answer
has body: Here is the function I propose you: from operator import itemgetter import re def get_most_ooo_word(words): words = ' '.join(words) # join all the strings into a single string words = re.sub(' +', ' ', words) # replace multiple spaces by a single one words = words.split(' ') # split the string to obtain all the words # initialize an array containing the count of o occurrences for each string count = [None] * len(words) # fill it properly using a differentiation for i, word in enumerate(words): count[i] = len(word) - len(word.replace('o','')) # find the maximum number of o occurrences count_max = max(count) # return all the words whose number of o occurrences equals the maximum return itemgetter(*[i for i, elem in enumerate(count) if elem == count_max])(words) And here is a small example: print(get_most_ooo_word(['oaa oa ooo', 'aaaa ao oa aaaoooa aooqq aoooqa'])) # ['ooo', 'aaaoooa', 'aoooqa']
score: 0
answers question: http://stackoverflow.com/q/49219328

http://stackoverflow.com/a/49218379
has body: I believe you need groupby with size for count and reshape by unstack, last filter columns (cities) by subset: df.groupby(['month', 'city']).size().unstack(fill_value=0)'A','B'.plot() Similar: pd.crosstab(df['month'], df['city'])'A','B'.plot() For plot all cities is possible omit subset [[]]. If want filter top counts: top = df['city'].value_counts().head(2).index df.query('city in @top').groupby(['month', 'city']).size().unstack(fill_value=0).plot()
has comment: http://stackoverflow.com/comment/85440758
has comment: http://stackoverflow.com/comment/85440800
type: Answer
has comment: http://stackoverflow.com/comment/85440610
has comment: http://stackoverflow.com/comment/85440588
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/49218349
downvote count: 0
has comment: http://stackoverflow.com/comment/85440888
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49218349
has comment: http://stackoverflow.com/comment/85440694

http://stackoverflow.com/q/49208752
upvote count: 0
has comment: http://stackoverflow.com/comment/85422088
answer count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85422380
has comment: http://stackoverflow.com/comment/85422067
type: UnansweredQuestion
has title: How to add points to a variable?
score: -4
tagged with: python
has body: I want to use the user input value and add it to an existing points variable. Here's the code I have: points= 0 add = input() if add == 1: points+= 20 print (points) Any idea how I can do this?
downvote count: 4
has answer: http://stackoverflow.com/a/49707476

transducer-machines
type: Tag
tag name: transducer-machines
tags question: http://stackoverflow.com/q/49225534

http://stackoverflow.com/comment/85375505
comment on: http://stackoverflow.com/q/49184573
has text: I mean take the logs of the absolute value of my matrix, sorry for my ambiguous expression.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85389208
type: Comment
has text: I've checked the html source of the page and the site does not seem to have the prices at the moment. Maybe that's why the variables are empty?
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49191954

http://stackoverflow.com/a/49301704
upvote count: 11
has comment: http://stackoverflow.com/comment/117648194
has comment: http://stackoverflow.com/comment/85615351
answers question: http://stackoverflow.com/q/49247796
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85612041
has comment: http://stackoverflow.com/comment/117644078
has body: how the R formula works The r formula presented in the question applies to a randomForest. Each tree in a random forest tries to predict the target variable directly. Thus, prediction of each tree lies in the expected interval (in your case, all house prices are positive), and prediction of the ensemble is just the average of all the individual predictions. ensemble_prediction = mean(tree_predictions) This is what the formula tells you: just take predictions of all the trees x and average them. why the Python PDP values are small In sklearn, however, partial dependence is calculated for a GradientBoostingRegressor. In gradient boosting, each tree predicts the derivative of the loss function at current prediction, which is only indirectly related to the target variable. For GB regression, prediction is given as ensemble_prediction = initial_prediction + sum(tree_predictions * learning_rate) and for GB classification predicted probability is ensemble_prediction = softmax(initial_prediction + sum(tree_predictions * learning_rate)) For both cases, partial dependency is reported as just sum(tree_predictions * learning_rate) Thus, initial_prediction (for GradientBoostingRegressor(loss='ls') it equals just the mean of the training y) is not included into the PDP, which makes the predictions negative. As for the small range of its values, the y_train in your example is small: mean hous value is roughly 2, so house prices are probably expressed in millions. how the sklearn formula actually works I have already said that in sklearn the value of partial dependence function is an average of all trees. There is one more tweak: all irrelevant features are averaged away. To describe the actual way of averaging, I will just quote the documentation of sklearn: For each value of the ‘target’ features in the grid the partial dependence function need to marginalize the predictions of a tree over all possible values of the ‘complement’ features. In decision trees this function can be ev…
has comment: http://stackoverflow.com/comment/85611804
has comment: http://stackoverflow.com/comment/85611729
has comment: http://stackoverflow.com/comment/85612912
downvote count: 0
type: Answer
score: 11
accepted answer of: http://stackoverflow.com/q/49247796

http://stackoverflow.com/comment/85422956
type: AnswerComment
has text: @TarunK, Actually, you **can't** use CSS selector in find function.
score: 1
type: Comment
comment on: http://stackoverflow.com/a/49209177

http://stackoverflow.com/comment/85563610
comment on: http://stackoverflow.com/a/49149191
score: 0
type: Comment
has text: For the second one the error stays. For the first one it now seems to work. Maybe I get your advice wrong for the second one. Should I have there while loop too? Just to know. The error stays with and without the loop. What did you do that the first version now works? I mean what does your code do there?
type: AnswerComment

http://stackoverflow.com/a/49196051
has comment: http://stackoverflow.com/comment/85399232
type: Answer
answers question: http://stackoverflow.com/q/49195864
has comment: http://stackoverflow.com/comment/85397887
has body: from netifaces import interfaces, ifaddresses, AF_INET def ip4_addresses(): ip_list = [] for interface in interfaces(): for link in ifaddresses(interface)[AF_INET]: ip_list.append(link['addr']) return ip_list print(ip4_addresses()) Reference: How do I determine all of my IP addresses when I have multiple NICs?
score: 0
has comment: http://stackoverflow.com/comment/85398978

http://stackoverflow.com/comment/85465506
score: 0
type: AnswerComment
has text: @user3574939 You probably haven't get the difference between instantiating a new object verus a genral function call. When you call `c1=Bozo(3)`, you are creating a new object of `Bozo` class, and the method `__init__()` will be called to do some initializing stuff(assigning value = 2 * input). While `clown()` is a class method. And by chaining the function calls, they will get executed from inside to out.
comment on: http://stackoverflow.com/a/49216011
type: Comment

http://stackoverflow.com/comment/89111626
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49167836
has text: I have similar problem, but when I use your suggestion and name my layer as `prediction = tf.layers.dense(net, 8, name='prediction_output')` I get operations named like `prediction_output/bias prediction_output/bias/read prediction_output/bias/Initializer/zeros prediction_output/bias/Assign prediction_output/kernel/Regularizer/l2_regularizer/scale ` but not any name `prediction_output`, which is why I get the error `KeyError: "The name 'prediction_output:0' refers to a Tensor which does not exist. The operation, 'prediction_output', does not exist in the graph." ` How can I resolve this?
score: 0

filter
tags question: http://stackoverflow.com/q/49188049
type: Tag
tags question: http://stackoverflow.com/q/49212905
tags question: http://stackoverflow.com/q/49262481
tags question: http://stackoverflow.com/q/49241335
tag name: filter
tags question: http://stackoverflow.com/q/49171749

http://stackoverflow.com/comment/85450356
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49223238
type: Comment
has text: Yes, it will work in Python. See my answer.

http://stackoverflow.com/q/49176376
possible better answer: http://stackoverflow.com/a/49176935
upvote count: 11
type: Question
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/49176460
accepted answer: http://stackoverflow.com/a/49176460
downvote count: 0
tagged with: python
score: 11
favorite count: 0
type: AnsweredQuestion
tagged with: pandas
has title: Pandas DataFrame to lists of lists including headers
has body: Say I have a DataFrame that looks like this: df = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['Col 1', 'Col 2', 'Col 3']) &gt;&gt;&gt; df Col 1 Col 2 Col 3 0 1 2 3 1 4 5 6 2 7 8 9 Is there a Pandas way of returning the DataFrame as a list of lists with the headers included? I can return the headers and values as lists as follows &gt;&gt;&gt; df.columns.values.tolist() ['Col 1', 'Col 2', 'Col 3'] &gt;&gt;&gt; df.values.tolist() [[1, 2, 3], [4, 5, 6], [7, 8, 9]] &gt;&gt;&gt; df.tolist() But how could I return the following result? [['Col 1', 'Col 2', 'Col 3'], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
has answer: http://stackoverflow.com/a/49176935

http://stackoverflow.com/a/65964857
has body: In my windows 10 Enterprise edition os this code works fine: (suppose for environment namely testenv) conda env remove --name testenv
upvote count: 54
score: 53
answers question: http://stackoverflow.com/q/49127834
downvote count: 1
type: Answer

http://stackoverflow.com/a/49258573
type: AcceptedAnswer
downvote count: 0
upvote count: 1
has body: One liner using zip and list comprehension: &gt;&gt;&gt; ['-'.join(ele) for ele in zip(student_names, marks)] Here, the zip command is used to create tuples combining the student_name and marks which are then joined together using join function. #driver values : IN : student_names= ['James', 'Jack', 'Ivy', 'Eva', 'Lee'] IN : marks = ['10', '64', '36', '86', '35'] OUT : ['James-10', 'Jack-64', 'Ivy-36', 'Eva-86', 'Lee-35']
answers question: http://stackoverflow.com/q/49258328
score: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/49258328

http://stackoverflow.com/a/51478603
score: 0
has body: You would want to do some testing to figure out whether the bottleneck was sending the data over your network, or the process of taking the screenshot and preparing the image. Presuming that it is sending the data over the network, I would suggest sending the full image the first time, and thereafter send diffs. I imagine that a high percentage of the actions that you take by time would be the mouse moving around the screen, so the diffs may often be minimal. from PIL import Image px1 = im1.load() px2 = im2.load() for x in range(0, im1.width): for y in range(0, im1.height): if px1[x, y] != px2[x, y]: ...
answers question: http://stackoverflow.com/q/49145983
type: Answer

http://stackoverflow.com/comment/85406122
comment on: http://stackoverflow.com/a/49199650
has text: @chepner a mutable, sure. But to the novice developer (as the OP seems to be), it looks an awful lot like copying as assignment to an instance attribute isn't reflected "up" to the class attribute. But sure if you want to be pedantic about it, and overly specific to a novice question. Then yes, it's not copied in a literal sense.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/49214240
has body: I just tried some random user agents to see if they allow anything without the captcha but with no success. Surprisingly the Safari user agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27 Raises error: MISSING_KEY:wc.check.err.browsernotsupported.header MISSING_KEY:wc.check.err.browsernotsupported.blurb1 On top of that : We’re Sorry You’ve reached the code limit and we’re unable to complete your request. Please try again later. Return to Apple Support site. Conclusion: As the person above mentioned. It doesn't seem to be possible at this moment in time. They also block connections after certain number of tries so even if you find a solution to use their service without the captcha you will need to use proxy to check more than 10-20 warranties.
type: Answer
answers question: http://stackoverflow.com/q/49214137
score: 0

http://stackoverflow.com/comment/85501202
score: 0
comment on: http://stackoverflow.com/a/49248790
has text: @IvanKalita: Much cleaner than my own check. I didn't use `inspect` because I wanted to run it against 2.4, but then I couldn't find my working 2.4 installation, so it was all a waste… :)
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49277682
downvote count: 0
has title: Prevent pandas concat'ting my dataframes both vertically and horizontally
accepted answer: http://stackoverflow.com/a/49277747
favorite count: 0
type: Question
possible better answer: http://stackoverflow.com/a/67682797
tagged with: python
has comment: http://stackoverflow.com/comment/126826875
has answer: http://stackoverflow.com/a/67682797
has answer: http://stackoverflow.com/a/49277747
has body: I am trying to concat two dataframes, horizontally. df2 contains 2 result variables for every observation in df1. df1.shape (242583, 172) df2.shape (242583, 2) My code is: Fin = pd.concat([df1, df2], axis= 1) But somehow the result is stacked in 2 dimensions: Fin.shape (485166, 174) What am I missing here?
tagged with: concatenation
upvote count: 12
tagged with: pandas
type: AnsweredQuestion
score: 12
answer count: 2
has comment: http://stackoverflow.com/comment/85558010

http://stackoverflow.com/q/49271771
accepted answer: http://stackoverflow.com/a/49271887
type: AnsweredQuestion
tagged with: attributeerror
tagged with: oop
has body: I am new to python programming and I have encountered an error for the below mentioned program. It is a simple program to add a node to the end of the linked list. The error says object LinkedList has no attribute head. Please Help me with the problem. class Node: def _init_(self, data): self.data = data self.next = None class LinkedList: def _init_(self): self.head=None def createNode(self, data): newNode = Node(data) return newNode def insertNodeHelper(self, head, data): if(head==None): return self.createNode(data) head.next = self.insertNodeHelper(head.next,data) return head def insertNode(self, data): self.head = self.insertNodeHelper(self.head,data) def printList(self, head): if(head==None): return; print(head.data) self.printList(head.next) def printLinkedList(self): self.printList(self.head) l = LinkedList() l.insertNode(12) l.insertNode(13) l.insertNode(15) l.printList() I am getting the following error: Message File Name Line Position Traceback &lt;module&gt; &lt;module1&gt; 35 insertNode &lt;module1&gt; 21 AttributeError: 'LinkedList' object has no attribute 'head'
has title: object has no attribute error in python
tagged with: python
has answer: http://stackoverflow.com/a/49271887
type: Question
tagged with: linked-list
downvote count: 0
upvote count: 1
score: 1
answer count: 1
favorite count: 0

http://stackoverflow.com/q/49208514
has answer: http://stackoverflow.com/a/49208738
type: AnsweredQuestion
score: 0
answer count: 2
has title: Python exercise generate an array with abs and argmin
type: Question
possible better answer: http://stackoverflow.com/a/49208763
has answer: http://stackoverflow.com/a/49208763
accepted answer: http://stackoverflow.com/a/49208738
has body: Generate a 10 x 3 array of random numbers in [0,1]. For each row, pick the number closest to 0.5. Use abs and argmin to find the column j closest for each row I don't understand the solution, could you please help me out? Solution x1 = np.random.random([10,3]) print(x1) c05 = [a[np.abs(a-0.5).argmin()] for a in x1] print(c05)
tagged with: python

http://stackoverflow.com/comment/85394311
comment on: http://stackoverflow.com/q/49194423
type: Comment
score: 0
has text: "value 0 for `inlet_10_00_00`, value 1 for `inlet_10_00_01`" -- but what value for `inlet_11_11_11`?
type: QuestionComment

http://stackoverflow.com/comment/85469008
type: Comment
comment on: http://stackoverflow.com/a/49199140
has text: Your third proposition was exactly what I needed, thanks a lot!
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85293082
has text: @StephenRauch In this instance is it not the only way he can achieve what he desires? I agree string concatenation should be avaoided if possible but what are the alternatives? is the possiblity not there because sometimes it is all one can do?
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/49143239

http://stackoverflow.com/q/49205948
has comment: http://stackoverflow.com/comment/85426692
type: Question
has title: Linear programming with matrix in python
has comment: http://stackoverflow.com/comment/85423515
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85417374
has comment: http://stackoverflow.com/comment/85423486
has comment: http://stackoverflow.com/comment/85417215
has body: I have a matrix as following: lift Out[147]: array([[188, 149, 147, 129, 104], [104, 168, 197, 114, 119], [134, 157, 152, 153, 103], [126, 176, 174, 126, 151], [137, 146, 168, 183, 121]], dtype=int64) I'm trying to minimize it, subjected to the condition that the row summation should be less than the following matrix: Constt Out[148]: array([[12000], [18000], [18000], [12000], [12000]]) I've used the following code: res = linprog(lift, A_ub=lift, b_ub=Constt, bounds=list(zip(VminA, VmaxA)), options={"disp": True}) VminA and VmaxA are (5 X 5) matrices consisting of the bounds. I'm not getting the solution. I get the following error: Traceback (most recent call last): File "&lt;ipython-input-149-cd1e2b9696bc&gt;", line 1, in &lt;module&gt; res = linprog(lift, A_ub=lift, b_ub=Constt, bounds=list(zip(VminA, VmaxA)), options={"disp": True}) File "C:\Users\hp1\Anaconda3\lib\site-packages\scipy\optimize\_linprog.py", line 993, in linprog bounds=bounds, callback=callback, **options) File "C:\Users\hp1\Anaconda3\lib\site-packages\scipy\optimize\_linprog.py", line 579, in _linprog_simplex L[i] = bounds[i][0] if bounds[i][0] is not None else -np.inf ValueError: setting an array element with a sequence. Can somebody help me here? Also please tell me how should I add another constraint regarding column summation?
has comment: http://stackoverflow.com/comment/85424470
has comment: http://stackoverflow.com/comment/85417097
score: 0
has comment: http://stackoverflow.com/comment/85423737
tagged with: matrix
has comment: http://stackoverflow.com/comment/85417131
tagged with: python
tagged with: linear-programming
tagged with: ipython
tagged with: scipy

http://stackoverflow.com/comment/85524456
has text: @user9485152 innerHTML will return *exactly* what's there. If you had ` This is some text `, you would want to have the possible `\n` in there. What if you had ` \n \n Text \n \n ` and you asked for the outer div's innerHTML? Which `\n` would you remove? All of them? Only the ones outside the ` ` . It doesn't make much sense, does it?
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49260063
score: 1

http://stackoverflow.com/comment/85271291
score: 0
comment on: http://stackoverflow.com/q/49132073
type: QuestionComment
has text: In any case, you can try adding the argument `dtype='object'` to the `read_csv` function. Then you'll have to replace all words in your dataframe with nulls or numbers, after which you can convert to float.
type: Comment

http://stackoverflow.com/q/49207415
answer count: 2
has comment: http://stackoverflow.com/comment/85420724
has title: Heroku Deployment - PermissionError: [Errno 13] Permission denied: '/etc/passwd-'
upvote count: 1
has comment: http://stackoverflow.com/comment/85420612
score: 1
has answer: http://stackoverflow.com/a/49208982
downvote count: 0
favorite count: 0
type: Question
tagged with: heroku
has body: Can anyone help me with this error? I don't what's wrong with the code. is it a database credentials error? Is it an application code error? Is it a Linux/Unix related error? This is my first time to deploy my application on Heroku but I got this error message: PermissionError: [Errno 13] Permission denied: '/etc/passwd-' python ph_dorms/manage.py collectstatic --noinput Traceback (most recent call last): File "ph_dorms/manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 353, in copy_file with source_storage.open(path) as source_file: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 33, in open return self._open(name, mode) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 218, in _open return File(open(self.path(name), mode)) PermissionError: [Errno 13] Permission denied: '/etc/passwd-' ! Error while …
has answer: http://stackoverflow.com/a/49209851
possible better answer: http://stackoverflow.com/a/49209851
accepted answer: http://stackoverflow.com/a/49208982
tagged with: heroku-toolbelt
tagged with: django
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/49268554
answer count: 1
favorite count: 0
has body: I have data as follows Gene Distance 0 A 18 1 B 16 2 C 58 3 D 45 4 E 34 If two genes have distance less than 50, they should be combined (in a list) as follows 1 A,B 2 C,D,E A loop should bread between B and C as the distance between them is more than 50. How can I create such breaks in a loop and for lists many times.
has answer: http://stackoverflow.com/a/49268777
type: Question
has comment: http://stackoverflow.com/comment/85540493
tagged with: dataframe
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85540547
has comment: http://stackoverflow.com/comment/85540520
tagged with: pandas
downvote count: 0
score: 1
upvote count: 1
has title: How to run the loop and return into different lists everytime in python

http://stackoverflow.com/a/49179116
answers question: http://stackoverflow.com/q/49178947
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49178947
type: AcceptedAnswer
has body: Use datetime: https://docs.python.org/3/library/datetime.html At a high level, I would start with initializing a datetime object with the first timestamp in your range, and a 1-second timedelta object. import datetime myDatetime = datetime.datetime(# TODO) myTimedelta = datetime.timedelta(# TODO) Then you could use a while loop and an endDatetime object with your last time in the range: endDateTime = datetime.datetime(# TODO) while myDatetime &lt;= endDatetime: print(myDatetime) # need to format it to look like your example myDatetime = myDatetime + myTimedelta Or you can calculate how many seconds are between the first and last end time and use a for loop: seconds = # TODO for i in range(seconds+1): print(myDatetime + (i * myTimedelta))

http://stackoverflow.com/comment/85531896
type: Comment
score: 1
type: QuestionComment
has text: Why do you expect this to generate errors? This should print `24` then `None`. All Python functions return some value. If you don't specify a value to return, `None` is returned automatically
comment on: http://stackoverflow.com/q/49264239

http://stackoverflow.com/a/49209440
type: Answer
answers question: http://stackoverflow.com/q/49195267
has comment: http://stackoverflow.com/comment/85505432
score: 0
has body: This is an interesting situation in which the file object abstraction partially breaks down. The reason your solution does not work, is because subprocess is not actually using your QuietLogger but is getting the raw file number out of it (then repackaging it as a io.TextIOWrapper object). I don't know if this is an intrinsic limitation in how the subprocess is handled, relying on OS support, or if this is just a mistake in the Python design, but in order to achieve what you want, you need to use the standard subprocess.PIPE and then roll your own file writer. If you can wait for the subprocess to finish, then it can be trivially done, using the subprocess.run and then picking the stream out of the CompletedProcess (p) object: p = subprocess.run(command, stdout=subprocess.PIPE, universal_newlines=True) data = filter(p.stdout) with open(logfile, 'w') as f: f.write(data) If you must work with the ouput while it is being generated (thus, you cannot wait for the subprocess to end) the simplest way is to resort to subprocess.Popen and threads: import subprocess import threading logfile ='tmp.txt' filter_passed = lambda line: line[:3] != 'Bad' command = ['my_cmd', 'arg'] def writer(p, logfile): with open(logfile, 'w') as f: for line in p.stdout: if filter_passed(line): f.write(line) p = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True) t = threading.Thread(target=writer, args=(p,logfile)) t.start() t.join()
has comment: http://stackoverflow.com/comment/85515007

http://stackoverflow.com/comment/85340631
comment on: http://stackoverflow.com/q/49166701
score: 0
type: Comment
has text: sorry all, I have a alphabetic string in here, so i was not able to convert it
type: QuestionComment

http://stackoverflow.com/comment/98359638
comment on: http://stackoverflow.com/a/55848638
has text: Welcome to Stack Overflow! Here is a guide on [How to Answer](http://stackoverflow.com/help/how-to-answer). Please note the conventions for formatting [How do I format my posts using Markdown or HTML](http://stackoverflow.com/help/formatting). (see my edit)
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/49188717
answers question: http://stackoverflow.com/q/49188607
has body: n = ["paul", "saul", "steve", "chimpy"] n2 = [28, 59, 22, 5] n3 = [59, 85, 55, 60] d={} for i in zip(*(n, n2, n3)): if i[2] &gt;=60: d[i[0]] = [i[1], i[2], "Pass"] else: d[i[0]] = [i[1], i[2], "Fail"] print d Output: {'steve': [22, 55, 'Fail'], 'paul': [28, 59, 'Fail'], 'chimpy': [5, 60, 'Pass'], 'saul': [59, 85, 'Pass']}
score: 1
type: Answer
downvote count: 0
upvote count: 1

http://stackoverflow.com/q/49268188
has body: First off, I am a total beginner when it comes to web tech, so this may be a relatively simple problem to solve. I am attempting to open a text file from a python script that is interacting with an XMLHTTPRequest and I am receiving the following error: Traceback (most recent call last): File "/home/ryan/VirtualDesktop/ComputerScience/4410_web_Technologies/projects/p3stuff/cgi-bin/p3.py", line 20, in &lt;module&gt; msgs = open("msgs.txt") FileNotFoundError: [Errno 2] No such file or directory: 'msgs.txt' This is the python code: #!/usr/bin/python3 import sys, cgi import cgitb cgitb.enable() sys.stderr = sys.stdout print("Access-Control-Allow-Origin: *") print("Content-type: text/html\n\n") msgs = open("msgs.txt") print(msgs.read()) The "msgs.txt" file is definitely in the proper directory and it runs fine if I run the python script in my terminal (without interacting with the javascript): ryan@ryan-XPS-15-9560:~/VirtualDesktop/ComputerScience/4410_web_Technologies/projects/p3stuff/cgi-bin$ ls msgs.txt p3.py* ryan@ryan-XPS-15-9560:~/VirtualDesktop/ComputerScience/4410_web_Technologies/projects/p3stuff/cgi-bin$ ./p3.py Access-Control-Allow-Origin: * Content-type: text/html alice: hello bob: whatever ryan@ryan-XPS-15-9560:~/VirtualDesktop/ComputerScience/4410_web_Technologies/projects/p3stuff/cgi-bin$ It seems to me the javascript code that I am using to interact with the python script is working fine, as it goes smoothly if I just print the contents of msgs.txt straight from the python file (ie removing the last two lines of the python code and replacing them with print("alice: hello\nbob: whatever"). Just trying to access that file seems to be my main problem. It's like the python script can't even see it when I'm trying to open it from my webpage. Any advice would be much appreciated. Thank you in advance! Edit: Using the full filepath in the open call is not permitted (this is part of an assignment).
has comment: http://stackoverflow.com/comment/85539943
tagged with: cgi
tagged with: javascript
answer count: 1
accepted answer: http://stackoverflow.com/a/49268373
has title: Python script throwing very odd error when trying to open a text file
has comment: http://stackoverflow.com/comment/85540327
has answer: http://stackoverflow.com/a/49268373
has comment: http://stackoverflow.com/comment/85539773
type: Question
tagged with: http://stackoverflow.com/tag/html
tagged with: python
tagged with: xmlhttprequest
has comment: http://stackoverflow.com/comment/85539895
has comment: http://stackoverflow.com/comment/85539805
has comment: http://stackoverflow.com/comment/85539786
has comment: http://stackoverflow.com/comment/85539874
type: AnsweredQuestion
score: 0

instantiation
type: Tag
tags question: http://stackoverflow.com/q/49250890
tag name: instantiation

http://stackoverflow.com/a/49186822
score: 2
type: Answer
has body: You can use this: pets = {'family1':{'dogs':2,'cats':3,'fish':1}, 'family2':{'dogs':3,'cats':2}} def addDict(d): d2 = {} for outKey, inKey in d.items(): for inKey, inVal in inKey.items(): try: d2[inKey] += inVal except KeyError: d2[inKey] = inVal return d2 print(addDict(pets)) Output: {'dogs': 5, 'cats': 5, 'fish': 1} This is called as EAFP principle in Python. What you simply do, is try to add the value for a key. If the key is not present, it'll throw a KeyError. Catch that error and insert the key.
upvote count: 2
answers question: http://stackoverflow.com/q/49186689
downvote count: 0

http://stackoverflow.com/comment/85366877
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49180630
has text: The executable being your python script.
type: Comment

http://stackoverflow.com/comment/85550402
type: Comment
type: QuestionComment
has text: if you have tried please share your code?
comment on: http://stackoverflow.com/q/49273694
score: 0

http://stackoverflow.com/q/49183367
has body: So in pandas, we can generate a simple monthly period index via the following pi = pandas.period_range("2018-01", periods=10, freq='M') Output: PeriodIndex(['2018-01', '2018-02', '2018-03', '2018-04', '2018-05', '2018-06', '2018-07', '2018-08', '2018-09', '2018-10'], dtype='period[M]', freq='M') We can also generate a set of period dates by applying the following method. pi.to_timestamp() Output: DatetimeIndex(['2018-01-01', '2018-02-01', '2018-03-01', '2018-04-01', '2018-05-01', '2018-06-01', '2018-07-01', '2018-08-01', '2018-09-01', '2018-10-01'], dtype='datetime64[ns]', freq='MS') Simple periodic sets of dates can be assembled using the following above. However, how can more complex sets of periods be assembled using pandas? Let's say that we wanted to define a period of the following... For each month, get the Friday of the 3rd week within the month I'm looking to get insight into how to define composite periods within the Pandas API. I'm getting rather confused with the role of the pandas Period and PeriodIndex classes within all of this and how concrete Datetimes/Timestamps are generated from instances of both of these classes.
type: AnsweredQuestion
score: 0
has title: How to assemble complex periods in Pandas
answer count: 1
type: Question
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49183544
tagged with: python
has answer: http://stackoverflow.com/a/49183544

http://stackoverflow.com/comment/85335253
has text: Do you want `r1` to be `r1` or `1`...?
type: Comment
comment on: http://stackoverflow.com/q/49164666
type: QuestionComment
score: 0

http://stackoverflow.com/a/49175140
has comment: http://stackoverflow.com/comment/85357612
has comment: http://stackoverflow.com/comment/85355653
upvote count: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/85361232
has comment: http://stackoverflow.com/comment/85355508
accepted answer of: http://stackoverflow.com/q/49174419
has comment: http://stackoverflow.com/comment/85355888
has comment: http://stackoverflow.com/comment/85365253
has body: The reason is, your program is in practice sequential. This is an example code snippet that is from parallelism standpoint identical to yours: from multiprocessing import Pool from time import sleep def gwork( qq): print (qq) sleep(1) return 42 p = Pool(processes=4) for q in range(1, 10): p.apply_async(gwork, args=(q,)).get() p.close() p.join() Run this and you shall notice numbers 1-9 appearing exactly once in a second. Why is this? The reason is your .get(). This means every call to apply_async will in practice block in get() until a result is available. It will submit one task, wait a second emulating processing delay, then return the result, after which another task is submitted to your pool. This means there is no parallel execution ongoing at all. Try replacing the pool management part with this: results = [] for q in range(1, 10): res = p.apply_async(gwork, args=(q,)) results.append(res) p.close() p.join() for r in results: print (r.get()) You can now see parallelism at work, as four of your tasks are now processed simultaneously. Your loop does not block in get, as get is moved out of the loop and results are received only when they are ready. NB: If your arguments to your worker or the return values from them are large data structures, you will lose some performance. In practice Python implements these as queues, and transmitting a lot of data via a queue is slow on relative terms compared to getting an in-memory copy of a data structure when a subprocess is forked.
type: Answer
answers question: http://stackoverflow.com/q/49174419
has comment: http://stackoverflow.com/comment/85361073
has comment: http://stackoverflow.com/comment/85356202
score: 3

http://stackoverflow.com/comment/85386904
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49190979
type: Comment
has text: Fails in Py 3..

http://stackoverflow.com/a/49260603
has body: You can also use regex: import re s = ['5 4 7', '4 3 1', '6 8 4', '4 8 6'] new_s = [sum(map(int, re.findall('\d+', b))) for b in s] Output: [16, 8, 18, 18] However, if every digit is a single character, then you can use isdigit(): last_result = [sum(map(int, filter(lambda x:x.isdigit(), i))) for i in s]
score: 0
answers question: http://stackoverflow.com/q/49260371
type: Answer

http://stackoverflow.com/q/49131704
has comment: http://stackoverflow.com/comment/85493674
tagged with: dataframe
tagged with: python
has body: I have a lot of data that I'd like to structure in a Pandas dataframe. However, I need a multi-index format for this. The Pandas MultiIndex feature has always confused me and also this time I can't get my head around it. I built the structure as I want it as a dict, but because my actual data is much larger, I want to use Pandas instead. The code below is the dict variant. Note that the original data has a lot more labels and more rows as well. The idea is that the original data contains rows of a task with index Task_n that has been performed by a participant with index Participant_n. Each row is a segment. Even though the original data does not have this distinction, I want to add this to my dataframe. In other words: Participant_n | Task_n | val | dur ---------------------------------- 1 | 1 | 12 | 2 1 | 1 | 3 | 4 1 | 1 | 4 | 12 1 | 2 | 11 | 11 1 | 2 | 34 | 4 The above example contains one participants, two tasks, with respectively three and two segments (rows). In Python, with a dict structure this looks like this: import pandas as pd cols = ['Participant_n', 'Task_n', 'val', 'dur'] data = [[1,1,25,83], [1,1,4,68], [1,1,9,987], [1,2,98,98], [1,2,84,4], [2,1,9,21], [2,2,15,6], [2,2,185,6], [2,2,18,4], [2,3,8,12], [3,1,7,78], [3,1,12,88], [3,2,12,48]] d = pd.DataFrame(data, columns=cols) part_d = {} for row in d.itertuples(): participant_n = row.Participant_n participant = "participant" + str(participant_n) task = "task" + str(row.Task_n) if participant in part_d: part_d[participant]['all_sum']['val'] += int(row.val) part_d[participant]['all_sum']['dur'] += int(row.dur) else: part_d[participant] = { 'prof': 0 if participant_n &lt; 20 else 1, 'all_sum': { 'val': int(row.val), 'dur': int(row.dur), } } if task in part_d[participant]: # Get already existing keys k = list(part_d[participant][task].keys()) k_int = [] # Only get the ints (i.e. not all_sum etc.) for n in k: # Get digit from e.g. seg1 n = n[3:] try: k_int.append(int(n)) except ValueError: pass # Increment …
has title: Convert dict constructor to Pandas MultiIndex dataframe
tagged with: dictionary
possible better answer: http://stackoverflow.com/a/49214387
answer count: 2
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49291850
downvote count: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49291850
tagged with: python-3.x
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49214387
score: 8
upvote count: 9
linked to: http://stackoverflow.com/q/23108889

django-allauth
tags question: http://stackoverflow.com/q/49199253
type: Tag
tag name: django-allauth
tags question: http://stackoverflow.com/q/49276207

http://stackoverflow.com/comment/85467163
has text: @steve, you can use `a = players[:3]; b = players[3:]` to split the list.
type: Comment
comment on: http://stackoverflow.com/a/49229665
type: AnswerComment
score: 0

http://stackoverflow.com/q/49172863
answer count: 1
tagged with: python
has answer: http://stackoverflow.com/a/49939372
has title: How do I save a full raw EEG signal with events as a Matlab file?
tagged with: matlab
tagged with: mne-python
score: 0
has body: raw, timestamp = ur.MNE_Read_EDF(path) mne_events, events_dict = ev.MNE_prepare_events(path, timestamp) epochs = mne.Epochs(raw, mne_events, events_dict, tmin=-0.5, tmax=0.5) signal = epochs.plot(block=True) I have a raw EEG signal in EDF files and events in a CSV file. I managed to create epochs by those events and then plot the raw signal with marked events, however I need to transfer it into a file that's accessible in Matlab. I can't use scipy.io.savemat for a plot I guess? I can't simply load these files into Matlab because somehow it desynchronizes epochs, probably due to averaged sampling frequency. MNE doesn't do this, but further analysis has to be conducted in Matlab.
type: Question
type: UnansweredQuestion

http://stackoverflow.com/comment/89715562
type: Comment
comment on: http://stackoverflow.com/a/49156878
type: AnswerComment
has text: `AttributeError: 'str' object has no attribute 'font'`, so no.
score: 1

http://stackoverflow.com/comment/85302246
has text: you should format the code snippet as code. highlight it and click the '{ }' symbol.
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/49148877
type: Comment

http://stackoverflow.com/a/49270584
score: 3
upvote count: 3
has body: Taken from https://docs.python.org/3/reference/expressions.html The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [1]. Looks like modulus operator always yields results with same sign as second operator. Hence for -11 mod 5 will yield positive (4) result. &gt;&gt;&gt; -11 % 5 4 While 11 mod -5 will yield negative (-4) result. &gt;&gt;&gt; 11 % -5 -4
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/49270521

http://stackoverflow.com/comment/85474840
type: Comment
score: 0
has text: Upvoting because I support profiling, although this is the most confusing profiling script I have seen.
type: AnswerComment
comment on: http://stackoverflow.com/a/49235142

http://stackoverflow.com/comment/85421527
type: QuestionComment
has text: Checkout this answer I just posted https://stackoverflow.com/a/49208472/2867928
comment on: http://stackoverflow.com/q/49206827
score: 1
type: Comment

http://stackoverflow.com/a/49143186
upvote count: 1
answers question: http://stackoverflow.com/q/49141621
type: Answer
has body: Assuming that the location of the geckodriver is correct, you can check below: properties of the geckodriver should have the correct permission for the user. You would need to check the box "Allow this file to run as a program" or if you you have restricted access, save the geckodriver in your home/username/geckodriver then path it to your firefox. Saving it in your home folder will be able to modify the properties of your geckodriver. [EDIT] Are your running in command line? If so, you need a virtual display, I have used pyvirtualdisplay: from pyvirtualdisplay import Display display = Display(visible=0,size(800, 600)) display.start() driver = webdriver.Firefox(executable_path="/usr/local/bin/geckodriver")
has comment: http://stackoverflow.com/comment/85377324
has comment: http://stackoverflow.com/comment/85374037
score: 1
downvote count: 0

http://stackoverflow.com/comment/85410038
score: 1
type: Comment
has text: Got it working and rendered some pretty pdfs. Thanks a bunch!!!
comment on: http://stackoverflow.com/a/49201574
type: AnswerComment

http://stackoverflow.com/a/76944501
type: Answer
has comment: http://stackoverflow.com/comment/135719325
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/49212832
has comment: http://stackoverflow.com/comment/135723608
has body: This is a great article on drawing Mandelbrot set in Python that describes the process in great detail. The basic idea is that color will be black when Mandelbrot set is stable, and the Hue and Saturation will depend on the stability value when it is less then 1. Following their instructions you can get following: And here is the code: from dataclasses import dataclass from math import log from PIL import Image import numpy as np from scipy.interpolate import interp1d @dataclass class Viewport: image: Image.Image center: complex width: float @property def height(self): return self.scale * self.image.height @property def offset(self): return self.center + complex(-self.width, self.height) / 2 @property def scale(self): return self.width / self.image.width def __iter__(self): for y in range(self.image.height): for x in range(self.image.width): yield Pixel(self, x, y) @dataclass class Pixel: viewport: Viewport x: int y: int @property def color(self): return self.viewport.image.getpixel((self.x, self.y)) @color.setter def color(self, value): self.viewport.image.putpixel((self.x, self.y), value) def __complex__(self): return ( complex(self.x, -self.y) * self.viewport.scale + self.viewport.offset ) @dataclass class MandelbrotSet: max_iterations: int escape_radius: float = 2.0 def __contains__(self, c: complex): return self.stability(c) == 1 def stability(self, c: complex, smooth=False, clamp=True): value = self.escape_count(c, smooth) / self.max_iterations return max(0.0, min(value, 1.0)) if clamp else value def escape_count(self, c: complex, smooth=False): z = 0 for iteration in range(self.max_iterations): z = z ** 2 + c if abs(z) > self.escape_radius: if smooth: return iteration + 1 - log(log(abs(z))) / log(2) return iteration return self.max_iterations def paint(mandelbrot_set, viewport, palette, smooth): for pixel in viewport: stability = mandelbrot_set.stability(complex(pixel), smooth) index = int(min(stability * len(palette), len(palette) - 1)) pixel.color = palette…

http://stackoverflow.com/comment/85510102
comment on: http://stackoverflow.com/a/49245757
score: 0
type: Comment
has text: Thank you - this is exactly what I was looking for!
type: AnswerComment

http://stackoverflow.com/q/49238241
has answer: http://stackoverflow.com/a/49238385
answer count: 1
has title: Python Error with iteration, for loop
upvote count: 1
favorite count: 0
tagged with: iteration
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85479803
has body: I am having a problem with my iteration statement. I want to compare the letter x with the value inside to equal 12. I wRIte in python list = 9876554321 for x = list: if result -&gt; 12 output "Succes'
tagged with: python
downvote count: 6
type: Question
accepted answer: http://stackoverflow.com/a/49238385
tagged with: list
score: -5

http://stackoverflow.com/comment/85361210
score: 0
has text: no, the {} only appear on my GUI
comment on: http://stackoverflow.com/q/49177369
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49259991
has body: Execute the command giving the arguments in an array or in a single string. Like this: subprocess.check_output(["git", "log", "-1", "--pretty-format:%H"]) Please see https://docs.python.org/2/library/subprocess.html as reference. UPDATE Edited command according to phd's suggestion, in the comments.
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49259538
has comment: http://stackoverflow.com/comment/85523981
type: Answer

http://stackoverflow.com/q/49265053
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85533636
has body: I'm trying to create a flag variable using: df.where(((df['MOSL_Rating'] == 'Highly Effective') &amp; (df['MOTP_Rating'] == 'Developing')) | ((df['MOSL_Rating'] == 'Highly Effective') &amp; (df['MOTP_Rating'] == 'Ineffective')) | ((df['MOSL_Rating'] == 'Effective') &amp; (df['MOTP_Rating'] == 'Ineffective')) | ((df['MOSL_Rating'] == 'Ineffective') &amp; (df['MOTP_Rating'] == 'Highly Effective')) | ((df['MOSL_Rating'] == 'Ineffective') &amp; (df['MOTP_Rating'] == 'Effective')) | ((df['MOSL_Rating'] == 'Developing') &amp; (df['MOTP_Rating'] == 'Highly Effective')), df['disp_rating'], 1, axis=1) but this returns ValueError: For argument "inplace" expected type bool, received type int. If I change my code from df['disp_rating'], 1, axis=1 to df['disp_rating'], True, axis=1 it returns TypeError: Cannot do inplace boolean setting on mixed-types with a non np.nan value I've also tried np.where but have gotten similar errors. I'm clearly missing something here. Is there a better way to do this? edit: I've read this post as well, as it was flagged as a possible duplicate. However, I don't understand how the answer solves my problem since that is about comparing 2 dataframes and doesn't discuss at all how to use this to create a new variable using data from only a single dataframe.
tagged with: python
linked to: http://stackoverflow.com/q/44273037
has title: df.where not working as expected
duplicate of: http://stackoverflow.com/q/44273037
answer count: 0
tagged with: pandas
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85534348
favorite count: 0
type: Question
tagged with: python-3.x

http://stackoverflow.com/comment/85326006
score: 6
has text: @wim: It's showing that the behaviour is documented. I don't think you have a strong case for expecting the comparison to take order into account.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49159268

http://stackoverflow.com/q/49196607
has body: I'm aware that this same error has been asked about before, but in this example and this other example, the errors are caused by using pyspark.sql functions in a udf. This is not what I am doing. The offending code is the following function definition (if I remove the default parameter my code runs and passes all tests). from pyspark.sql import functions as F def apply_filter(df, group=F.lit(True)): filtered_df = df.filter(group) I am mainly looking for the reason that this code produces the same error that is found in the other examples. Edit: I cannot share the original code due to work, but if you run the previous code with spark-submit --deploy-mode cluster &lt;filename&gt; the following error is produced. LogType:stdout Log Upload Time:Fri Mar 09 16:01:45 +0000 2018 LogLength:343 Log Contents: Traceback (most recent call last): File "temp.py", line 3, in &lt;module&gt; def apply_filter(df, group=F.lit(True)): File "/mnt/yarn/usercache/hadoop/appcache/application_1520603520946_0005/container_1520603520946_0005_01_000001/pyspark.zip/pyspark/sql/functions.py", line 40, in _ AttributeError: 'NoneType' object has no attribute '_jvm' End of LogType:stdout Interestingly enough, the error doesn't persist if it is ran locally.
score: 0
has answer: http://stackoverflow.com/a/49202524
tagged with: python
has comment: http://stackoverflow.com/comment/85729597
type: Question
linked to: http://stackoverflow.com/q/47552309
tagged with: python-3.x
tagged with: apache-spark-sql
linked to: http://stackoverflow.com/q/40297403
type: UnansweredQuestion
tagged with: pyspark
answer count: 1
has title: AttributeError: 'NoneType' object has no attribute '_jvm' when passing sql function as a default parameter
has comment: http://stackoverflow.com/comment/85398254

http://stackoverflow.com/q/49160323
has comment: http://stackoverflow.com/comment/85328996
has comment: http://stackoverflow.com/comment/85329666
tagged with: python-2.7
score: 0
answer count: 0
upvote count: 1
has body: I have a back end application built in Python Flask with an api endpoint: /api/getdata/ where name can contain Swedish letters such as Å,Ä and Ö. When I try to use these in the API call using curl in my prompt the Swedish characters turn up like question marks in Python 3.6. But when I do this in Python 2.7 with this in the beginning of my script it works: import sys reload(sys) sys.setdefaultencoding("utf-8") How can I solve this? I am already using the utf-8 comment line in the beginning of the script. * UPDATE * This works in Python 2 with the above workaround but not in Python 3: app.route('/api/getdata/&lt;name&gt;') def hello_world(name): print(name) # Gives correct in Python 2.7, just a question mark in Python 3 return name Request: curl http://localhost:5000/api/getdata/Åland
has comment: http://stackoverflow.com/comment/85328517
downvote count: 1
has comment: http://stackoverflow.com/comment/85329845
tagged with: utf-8
has comment: http://stackoverflow.com/comment/85329532
has comment: http://stackoverflow.com/comment/85328271
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85328229
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85329807
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85328360
has comment: http://stackoverflow.com/comment/85328876
tagged with: python
has comment: http://stackoverflow.com/comment/85326387
has title: Python Flask - Non ascii characters in API Get Endpoint
has comment: http://stackoverflow.com/comment/85326359

http://stackoverflow.com/comment/85330102
comment on: http://stackoverflow.com/q/49161663
score: 0
has text: Yes, the cov_mat, since the gradient of the determinant involves an inverse matrix. I can get the gradient for the first iteration, but after that, I can't invert the matrix anymore.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49181120
has title: Python - returning from a While Loop after its end
tagged with: python
has body: I am trying to code a menu routine for an alarm-clock in python, which displays the relevant information on a 7-segment display according to some inputs via pushbuttons. I managed to create a loop which displays the current time, and whe the button "debMenu" is clicked 3 menu options are displayed. This works well only for the first time untill the 3rd. menu option is reached. When I push the button again the routine does not work - so the function "main_menu" is not called again. What I am doing wrong...? Thanks !! stop_loop = [False] def main_menu(stop_loop, n=[0]): stop_loop[0] = True debSelect = DebouncedSwitch(butSelect, cbButSelect, "butSelect") menuList = ['HO ', 'AL ', 'UP '] if n[0] &lt; 3: display.scroll(menuList[n[0]], 200) #display menu on 7-seg display display.show(menuList[n[0]]) n[0] += 1 elif n[0] == 3: n=[0] stop_loop[0] = False main() def main(): stop_loop[0] = False debMenu = DebouncedSwitch(butMenu, main_menu, stop_loop) while not stop_loop[0]: # display current time on 7-seg display curTime = rtc.datetime() display.numbers(curTime.hour, curTime.minute, False) time.sleep_ms(500) display.numbers(curTime.hour, curTime.minute) time.sleep_ms(500) main()
tagged with: esp32
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49181302
answer count: 1
has answer: http://stackoverflow.com/a/49181302
tagged with: setalarmclock
has comment: http://stackoverflow.com/comment/85383107
type: Question

http://stackoverflow.com/q/49200609
downvote count: 4
score: 2
has answer: http://stackoverflow.com/a/49200659
has comment: http://stackoverflow.com/comment/85406453
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85406466
has answer: http://stackoverflow.com/a/49200666
has body: In python3: &gt;&gt;&gt; abs(-5) == 5 and &gt;&gt;&gt; abs(5) == 5 but &gt;&gt; abs(5+0j) == 5.0
has title: Why is the absolute value of a complex number a floating point number?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85406430
has answer: http://stackoverflow.com/a/49200854
tagged with: math
has answer: http://stackoverflow.com/a/49201115
tagged with: python
tagged with: absolute-value
has comment: http://stackoverflow.com/comment/85406396
upvote count: 6
answer count: 4

http://stackoverflow.com/q/49276965
has body: I am exploring django with postgres. I have encountered a strange thing. TIMEZONE setting for my postgres connection(I am not talking about TIME_ZONE in settings.py) is surprisingly set to None. I have set timezone to 'Asia/Kolkata' and USE_TZ is also True. As per django docs, when USE_TZ is True, the connection timezone 'UTC' by default, while it'll be equal to the value of TIME_ZONE in settings.py, when USE_TZ is False. But, for me in both the cases, the value of connection.timezone is empty. I have tried with sqlite3 backend, where I am getting expected results. I don't know, why I am not getting expected behaviour with postgres. I am using django==1.10.5 and postgres is 9.5 on 64 bit machine. I am using following command to get connection's timezone. from django.db import connection print (connection.timezone) Thanks in advance.
tagged with: database-connection
downvote count: 0
answer count: 1
tagged with: django
has answer: http://stackoverflow.com/a/49277668
accepted answer: http://stackoverflow.com/a/49277668
favorite count: 0
type: Question
has title: why connection.timezone is None for postgres db connection in django?
tagged with: postgresql
type: AnsweredQuestion
tagged with: python
score: 2
upvote count: 2

http://stackoverflow.com/comment/85406665
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49184469
type: Comment
has text: @abarnert While it's true that, one doesn't need to configure a widget's text option, however, a widget's text _has_ to be configured in order to display the desired text, be it automatic or manual. Using variable classes are a bit redundant in the case above, that's why I suggested `configure`. You're suggesting the use, but _not_ showing how. The line most relevant creates a new label on top of another with the text value of a 'constant' `'0'`. I disagree that this is clear enough for everyone of what you're suggesting, if not misleading, hence the comment.

http://stackoverflow.com/comment/85498186
score: 0
type: AnswerComment
has text: Hey I am having some trouble changing my program to work with dictionaries. Is there a way I can convert the two existing lists into dictionaries to make this work? The problem I am having is I am not hard coding the lists so at the start of my program the list 'playerPoints' is actually empty and has players and points added to it during the program which I am then wanting to store in the 'totalRank' list
comment on: http://stackoverflow.com/a/49246502
type: Comment

http://stackoverflow.com/a/49238675
upvote count: 1
has body: Code Here is my solution: def static_attributes(obj): """ Generator to return a list of names and attributes which are class-level variables or static methods """ klass = type(obj) for name, attribute in klass.__dict__.items(): if not name.startswith('__') and \ (type(attribute) in {staticmethod, classmethod} or not callable(attribute)): yield name, attribute for name, attribute in static_attributes(obj): print(name) Output static_var static_method Discussion This generator function yields a list of name and attributes that are either staticmethod, classmethod, or class-level variables. I also filtered out those names that starts with dunder (such as __doc__)
accepted answer of: http://stackoverflow.com/q/49237781
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/49237781

http://stackoverflow.com/q/49241864
downvote count: 0
tagged with: pandas
upvote count: 1
score: 1
tagged with: windows
answer count: 1
tagged with: memory
favorite count: 0
type: Question
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85487521
tagged with: python
has answer: http://stackoverflow.com/a/49241895
has body: I'm loading a large csv file into pandas and when I load too many lines at once I get a dialog box telling me "Python has stopped working" without any error messages in the terminal (screenshot). I suspect it's a memory limitation but it'd be nice to confirm with the python stacktrace directly. Anyone have a similar experience and know how to get at what's happening? update: Turns out not to have been a memory limitation after all. I think the root cause was a pandas issue, upgrading from 20.3 -> 22.0 seems to have fixed it. I suspect it was related to this: https://github.com/pandas-dev/pandas/issues/16798
has title: python dies on windows without stacktrace

http://stackoverflow.com/comment/85458463
type: QuestionComment
comment on: http://stackoverflow.com/q/49211358
type: Comment
score: 0
has text: Just for future reference, if you provide all this information in the first place itself, i.e., in your original question, it'd be faster to arrive where we are at right now. As for the GPIOs, you'd have to try a bunch of things. Try explicitly pushing it LOW and then HIGH. Also try other pins instead of 22, 12.

selenium-chromedriver
tags question: http://stackoverflow.com/q/49270109
tags question: http://stackoverflow.com/q/49247204
tags question: http://stackoverflow.com/q/49177222
tags question: http://stackoverflow.com/q/49122003
tags question: http://stackoverflow.com/q/49177677
tags question: http://stackoverflow.com/q/49151036
tags question: http://stackoverflow.com/q/49123449
tag name: selenium-chromedriver
tags question: http://stackoverflow.com/q/49242609
tags question: http://stackoverflow.com/q/49232492
tags question: http://stackoverflow.com/q/49223145
tags question: http://stackoverflow.com/q/49265525
tags question: http://stackoverflow.com/q/49205243
type: Tag
tags question: http://stackoverflow.com/q/49201281

http://stackoverflow.com/q/49159976
score: 2
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/85329500
downvote count: 0
has title: Error stack overflow from pulling data from database
tagged with: stack-overflow
favorite count: 0
type: Question
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85327781
has body: I am running a code that pulls info from the 500 companies of the S&amp;P 500. Every time it reaches a particular company, ANDV, I get a stack overflow fatal error. Any suggestions for how to fix this? I added a time.sleep(2) to combat any potential API call throttling. Here is the code: import bs4 as bs import pickle import requests, time import datetime as dt import os import pandas as pd import pandas_datareader.data as web def save_sp500_tickers(): resp = requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies') soup = bs.BeautifulSoup(resp.text, "lxml") table = soup.find('table', {'class':'wikitable sortable'}) tickers = [] for row in table.findAll('tr')[1:]: ticker = row.findAll('td')[0].text tickers.append(ticker) with open("sp500tickers.pickle", "wb") as f: pickle.dump(tickers, f) print(tickers) return tickers #save_sp500_tickers() def get_data_from_morningstar(reload_sp500=False): if reload_sp500: tickers = save_sp500_tickers() else: with open("sp500tickers.pickle","rb") as f: tickers = pickle.load(f) if not os.path.exists('stock_dfs'): os.makedirs('stock_dfs') start = dt.datetime(2000,1,1) end = dt.datetime(2016,12,31) for ticker in tickers: print(ticker) time.sleep(2) if not os.path.exists('stock_dfs/{}.csv'.format(ticker)): df = web.DataReader(ticker, 'morningstar', start, end) df.to_csv('stock_dfs/{}.csv'.format(ticker)) else: print('Already have {}'.format(ticker)) get_data_from_morningstar() The error, shortening the File threads significantly, is this: ANDV adding ANDV to retry list Fatal Python error: Cannot recover from stack overflow. Current thread 0x00001690 (most recent call first): File "C:\Users\Aaron Mazie\AppData\Local\Programs\Python\Python36-32\lib\enum.py", line 519 in __new__ File "C:\Users\Aaron Mazie\AppData\Local\Programs\Python\Python36-32\lib\enum.py", line 291 in __call__ File "C:\Users\Aaron Mazie\AppData\Local\Programs\Python\Python36-32\lib\socket.py", line 103 in _intenum_converter File "C:\Users\Aaron Mazie\Ap…
type: UnansweredQuestion
tagged with: database
tagged with: python

http://stackoverflow.com/comment/85449895
type: QuestionComment
comment on: http://stackoverflow.com/q/49223147
type: Comment
score: 0
has text: Python guarantees no order to the elements of sets. (In fact, the set abstract data type does not impose order on its elements.) With the list of ints (instead of strings), you just got lucky because of how Python hashes integers.

http://stackoverflow.com/a/76548512
has body: I got away from this one by using the following: # Read content in bytes from whatever is your source, then: content = content[:28]+b'\xFE\xFF'+content[30:] with open('file.xls', 'wb') as file: file.write(content) # This works now df = pd.read_excel('file4.xls') Based on this: https://github.com/python-excel/xlrd/blob/master/xlrd/compdoc.py#L90
downvote count: 0
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/49197793
type: Answer

http://stackoverflow.com/q/49219142
has body: I am trying to match the result of this doctest in python by inputting the correct regular expression. This is what i have so far: import re import nltk import collections nltk.download('punkt') nltk.download('gutenberg') nltk.download('brown') nltk.download('averaged_perceptron_tagger') nltk.download('universal_tagset') regexp = re.compile('[0-9]+$') def annotateOD(listoftokens): """Annotate the ordinal numbers in the list of tokens &gt;&gt;&gt; annotateOD("the second tooth".split()) [('the', ''), ('second', 'OD'), ('tooth', '')] """ result = [] for t in listoftokens: if regexp.match(t): result.append((t, 'OD')) else: result.append((t, '')) return result # DO NOT MODIFY THE CODE BELOW def compute_f1(result, tagged): assert len(result) == len(tagged) # This is a check that the length of the result and tagged are equal correct = [result[i][0] for i in range(len(result)) if result[i][1][:2] == 'OD' and tagged[i][1][:2] == 'OD'] numbers_result = [result[i][0] for i in range(len(result)) if result[i][1][:2] == 'OD'] numbers_tagged = [tagged[i][0] for i in range(len(tagged)) if tagged[i][1][:2] == 'OD'] if len(numbers_tagged) &gt; 0: r = len(correct)/len(numbers_tagged) else: r = 0.0 if len(numbers_result) &gt; 0: p = len(correct)/len(numbers_result) else: p = 0.0 return 2*r*p/(r+p) if __name__ == "__main__": import doctest doctest.testmod() nltk.download('brown') tagged = nltk.corpus.brown.tagged_words(categories='news') words = [t for t, w in tagged] result = annotateOD(words) f1 = compute_f1(result, tagged) print("F1 score:", f1) The result I have is: Expected :[('the', ''), ('second', 'OD'), ('tooth', '')] Actual :[('the', ''), ('second', ''), ('tooth', '')] Then I tried a different approach and tried this regular expression: regexp = re.compile('.*(st|nd|rd|th)$') and got this as the result: Expected :[('the', ''), ('second', 'OD'), ('tooth', '')] Actual :[('the', ''), ('second', 'OD'), ('tooth', 'OD')] I've spent quite a long time trying to pass the doctest but the…
has comment: http://stackoverflow.com/comment/85443143
has title: Regular expression to annotate ordinal numbers
tagged with: tokenize
has comment: http://stackoverflow.com/comment/85443234
score: 1
tagged with: python
tagged with: regex
favorite count: 0
type: Question
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: nltk
downvote count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/85443396

http://stackoverflow.com/q/49180567
type: Question
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/49182551
tagged with: python
has title: Python groupby process csv
has body: i have a daily file of netowrk router utilizations. I am trying find the max of column uIN and uOUT for each unique router(QIN) and the time it occured. I have done a lot with Pandas and 'groupby' but can't seem to get the end result i need. Here is a sample of the data: Minute QIN uIN uOUT 2/14/2018 16:00 Bundle-Ether1 on (Router1.network.com) 0.10221 0.21195 2/14/2018 16:05 Bundle-Ether1 on (Router1.network.com) 0.089865 0.18722 2/15/2018 16:10 Bundle-Ether1 on (Router1.network.com) 0.07482 0.1705 2/16/2018 16:15 Bundle-Ether1 on (Router1.network.com) 0.09176 0.18846 2/17/2018 16:20 Bundle-Ether1 on (Router1.network.com) 0.11816 0.11785 2/14/2018 16:00 Bundle-Ether1 on (Router2.network.com) 0.08786 0.15235 2/14/2018 16:05 Bundle-Ether1 on (Router2.network.com) 0.07777 0.19253 2/15/2018 16:10 Bundle-Ether1 on (Router2.network.com) 0.07552 0.14232 2/16/2018 16:15 Bundle-Ether1 on (Router2.network.com) 0.1291 0.18758 2/17/2018 16:20 Bundle-Ether1 on (Router2.network.com) 0.13361 0.11747 Here is my code: import pandas as pd df = pd.read_csv('c://router_data.csv') df['Minute'] = pd.todatetime(df['Minute']) df.set_index('Minute').groupby('QIN')['uIN'].resample("M").max() Results: Bundle-Ether1 on (Router2.network.com) 0.13361 Bundle-Ether1 on (Router1.network.com) 0.11816 The results i need: 2/17/2018 16:20 Bundle-Ether1 on (Router2.network.com) 0.13361 2/17/2018 16:20 Bundle-Ether1 on (Router1.network.com) 0.11816
score: 0
tagged with: pandas-groupby
answer count: 1

http://stackoverflow.com/comment/85519169
type: Comment
has text: Thanks! The problem was in my urls.py file. Thanks to you, I was able to solve it!
comment on: http://stackoverflow.com/a/49258087
score: 0
type: AnswerComment

http://stackoverflow.com/a/49227937
type: Answer
has body: c = set(set(list(a) + list(b)) set() return &lt;str set&gt; so can't add two set together https://docs.python.org/2/library/sets.html
answers question: http://stackoverflow.com/q/49227864
has comment: http://stackoverflow.com/comment/85459410
has comment: http://stackoverflow.com/comment/85459463
upvote count: 0
has comment: http://stackoverflow.com/comment/85459387
score: -2
downvote count: 2

http://stackoverflow.com/a/49135074
upvote count: 0
answers question: http://stackoverflow.com/q/49134554
has comment: http://stackoverflow.com/comment/85275833
downvote count: 1
has body: The solution to my problem was to change the environmental variable python to run version 3.6 instead of 2.7. The issue was a cross compatibility issue and I found it easier to change the variable instead of trying to have it try both Tkinter and tkinter modules depending on the particular version.
has comment: http://stackoverflow.com/comment/85276156
type: Answer
has comment: http://stackoverflow.com/comment/85276297
score: -1

http://stackoverflow.com/comment/85514048
score: 0
has text: You should be using `with open() as file: file.write()`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49255507

http://stackoverflow.com/a/49426087
has body: I used base64 encoding at both ends and that worked perfectly for me.
score: 0
accepted answer of: http://stackoverflow.com/q/49254469
answers question: http://stackoverflow.com/q/49254469
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/85445238
type: Comment
has text: Thanks for the answer! This is exactly what I needed.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49220823

http://stackoverflow.com/a/49258639
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49258228
has comment: http://stackoverflow.com/comment/85522310
has comment: http://stackoverflow.com/comment/85520506
type: Answer
answers question: http://stackoverflow.com/q/49258228
has comment: http://stackoverflow.com/comment/85520729
score: 5
upvote count: 5
type: AcceptedAnswer
has body: It looks like /path/to/root/ is not on your python path when you call python core/emoji.py. You can check by printing sys.path in your script. import sys print(sys.path) You could add the root directory to your python path by setting the PYTHONPATH environment variable: PYTHONPATH=/path/to/root python core/emoji.py or you could set it in your script: import sys sys.path.append('/path/to/root')
has comment: http://stackoverflow.com/comment/126596189
has comment: http://stackoverflow.com/comment/126582881
has comment: http://stackoverflow.com/comment/85522723
has comment: http://stackoverflow.com/comment/85523016

http://stackoverflow.com/q/49265702
has comment: http://stackoverflow.com/comment/85535038
has comment: http://stackoverflow.com/comment/85536313
tagged with: python
upvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85535065
score: 1
has body: I have a string in python I want to replace any special characters in that string. I have done like below col_name = 'AN*_Gen_**Air_&amp;Outlet_$Temp' reps = (('_&amp;', ' '), ('*_', '('), ('_*', ')'), ('#_', '{'), ('_#', '}'), ('_##', ';'), ('_$', '.'), ('_$$', ','), ('_**', '=')) original_cols = reduce(lambda a, kv: a.replace(*kv), reps, col_name) Output: 'AN(Gen)*Air Outlet.Temp' Expected output: 'AN(Gen=Air Outlet.Temp' Here I see that in the string _** is being first replaced by )* instead of = as _* in reps is ) What should I do to get the correct string?
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/85534848
has comment: http://stackoverflow.com/comment/85535088
favorite count: 0
type: Question
has title: Special characters in Python string replace
has answer: http://stackoverflow.com/a/49265884
accepted answer: http://stackoverflow.com/a/49265884

http://stackoverflow.com/comment/85284879
has text: Try starting by expressing your intended logic in plain English.
comment on: http://stackoverflow.com/q/49139626
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/49238308
type: AnsweredQuestion
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/49238377
has title: Replace words from list with a dataframe
tagged with: pandas
has body: I have a list of words. Say: list = ['this', 'that', 'and', 'more'] I want to replace words in such fashion: x |y ----------- this |that plus |more Every time a word from the list is in column y, I want to replace it with what's found in column x on the same row. If the word isn't in y, it should remain as is. How can this be done?
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/49238547
type: Question
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/49238547
accepted answer: http://stackoverflow.com/a/49238377
tagged with: python
tagged with: text-mining
tagged with: replace

http://stackoverflow.com/comment/85512665
has text: The last line to calculate lamdba fails because `U*I` in numpy is not the matrix product but a element wise product. To calculate the matrix product you need to use `np.dot(U, I)`.
type: Comment
comment on: http://stackoverflow.com/q/49239475
type: QuestionComment
score: 0

ddos
tags question: http://stackoverflow.com/q/49204360
type: Tag
tag name: ddos

http://stackoverflow.com/comment/85276298
type: QuestionComment
comment on: http://stackoverflow.com/q/49135754
score: 1
type: Comment
has text: If you're running in pycharm or something, the filepath is always shown. Try running from cmd, shouldn't show there

http://stackoverflow.com/q/49182094
answer count: 0
has comment: http://stackoverflow.com/comment/85446327
tagged with: pyqt
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/85428779
has body: I want to use PyQT5 and OpenGL to create an interactive application which should run on the Raspberry Pi Zero with Raspbian. The first step is to display an image texture on screen, but this already fails with an error message on the Pi. (see down below) However it is running fine when executed on my Ubuntu development machine with OpenGL 2.0 profile. #!/usr/bin/env python import sys from PIL import Image from PyQt5.QtCore import QSize, Qt from PyQt5.QtGui import (QColor, QSurfaceFormat, QOpenGLVersionProfile) from PyQt5.QtWidgets import QApplication, QGridLayout, QOpenGLWidget, QWidget class GLWidget(QOpenGLWidget): def __init__(self, path, width, height, parent=None): super(GLWidget, self).__init__(parent) self.path = path self.width = width self.height = height self.texture_array = [] self.current_texture_index = 0 self.fps = 0 self.elapsed = 0 self.clearColor = QColor(Qt.black) def sizeHint(self): return QSize(self.width, self.height) def initializeGL(self): version = QOpenGLVersionProfile() version.setVersion(2, 0) self.gl = self.context().versionFunctions(version) self.gl.initializeOpenGLFunctions() self.gl.glEnable(self.gl.GL_DEPTH_TEST) self.gl.glEnable(self.gl.GL_TEXTURE_2D) self.gl.glClearColor(self.clearColor.redF(), self.clearColor.greenF(), self.clearColor.blueF(), self.clearColor.alphaF()) img = Image.open(self.path) img_data = img.convert("RGBA").tobytes("raw", "RGBA") self.texture_array.append(self.frameToTex(img_data, self.width, self.height)) def frameToTex(self, data, width, height): texture_id = self.gl.glGenTextures(1) self.gl.glBindTexture(self.gl.GL_TEXTURE_2D, texture_id) self.gl.glTexParameterf(self.gl.GL_TEXTURE_2D, self.gl.GL_TEXTURE_MIN_FILTER, self.gl.GL_LINEAR_MIPMAP_LINEAR) self.gl.glTexParameterf(self.gl.GL_TEXTURE_2D, self.gl.GL_TEXTURE_MAG_FILTER, self.gl.GL_LINEAR) self.gl.glTexParameteri(self.gl.GL_TEXTURE_2D, self.gl.GL_GENERATE_MIPMAP, self.gl.GL_TRUE) self.gl.glTexImage2D(self.gl.GL_TEXTURE_2D, 0, self.gl.GL_RGBA, width, height…
type: Question
has comment: http://stackoverflow.com/comment/85371141
type: UnansweredQuestion
tagged with: opengl-es-2.0
tagged with: python
has title: PyQt5's OpenGL ES 2.0 Texture Mapping for Raspberry Pi not working
has comment: http://stackoverflow.com/comment/85429567
score: 0
tagged with: raspberry-pi

http://stackoverflow.com/comment/85470859
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49233838
type: AnswerComment
has text: can you tell me how to get that domain name i really confused as i am new to this

http://stackoverflow.com/a/49179608
type: Answer
accepted answer of: http://stackoverflow.com/q/49179356
has comment: http://stackoverflow.com/comment/85365154
has comment: http://stackoverflow.com/comment/85364914
answers question: http://stackoverflow.com/q/49179356
type: AcceptedAnswer
downvote count: 0
score: 16
has comment: http://stackoverflow.com/comment/114922541
has comment: http://stackoverflow.com/comment/85365057
upvote count: 16
has body: Your are quite correct. A little better solution is below. #include "pybind11/pybind11.h" #include "pybind11/numpy.h" namespace py = pybind11; py::array_t&lt;double&gt; make_array(const py::ssize_t size) { // No pointer is passed, so NumPy will allocate the buffer return py::array_t&lt;double&gt;(size); } PYBIND11_MODULE(my_module, m) { .def("make_array", &amp;make_array, py::return_value_policy::move); // Return policy can be left default, i.e. return_value_policy::automatic }
has comment: http://stackoverflow.com/comment/85365287

http://stackoverflow.com/comment/85377651
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49185697
has text: thank you buddy, at least its not repeating 25 times but 217 result id returns. but still feels like there is something i skipped.
type: Comment

http://stackoverflow.com/q/49272560
answer count: 1
tagged with: shutil
type: Question
accepted answer: http://stackoverflow.com/a/49426454
has answer: http://stackoverflow.com/a/49426454
tagged with: python
has title: Random OSError 22 using shutil with unicode path
type: AnsweredQuestion
score: 0
has body: I'm currently facing issues using shutil module. I am using the following function to copy files recursively and overwrite other files def copytree(src, dst, symlinks=False, ignore=None): names = os.listdir(src) if ignore is not None: ignored_names = ignore(src, names) else: ignored_names = set() if not os.path.isdir(dst): # This one line does the trick os.makedirs(dst) errors = [] for name in names: if name in ignored_names: continue srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks, ignore) else: # Will raise a SpecialFileError for unsupported file types shutil.copy2(srcname, dstname) # catch the Error from the recursive copytree so that we can # continue with other files except shutil.Error as err: errors.extend(err.args[0]) except EnvironmentError as why: errors.append((srcname, dstname, str(why))) try: shutil.copystat(src, dst) except OSError as why: if WindowsError is not None and isinstance(why, WindowsError): # Copying file access times may fail on Windows pass else: errors.extend((src, dst, str(why))) if errors: raise shutil.Error(errors) Because I have got some paths which are longer than the PATH_MAX on Windows (260 characters), I am using '\\?\' at the beginning of my path. Sometimes shutil returns some errors like the following: shutil.Error: [ ('\\\\?\\F:\\Jenkins_tests\\workspace\\team_workspace_tests\\sources\\master\\distrib\\folders\\file.sch_txt'), '\\\\?\\F:\\Jenkins_tests\\workspace\\team_workspace_tests\\sources\\master\\IMAGE\\schema\\sch_0_15.sch_txt', "[Errno 22] Invalid argument: '\\\\\\\\?\\\\F:\\\\Jenkins_tests\\\\workspace\\\\team_workspace_tests\\\\sources\\\\master\\\\IMAGE\\\\schema\\\\sch_0_15.sch_txt']` But if I relaunch the script, I will have no errors, or an error on another file... Maybe I made a mistake ?

http://stackoverflow.com/a/49227365
downvote count: 1
accepted answer of: http://stackoverflow.com/q/49227062
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85478869
has body: import time import threading if __name__ == "__main__": def print_sum(l): while True: total = sum(l) print("the total is {}".format(total)) time.sleep(1) #list = [] - should not use 'list'. - this shadows the built in object name list. l = [] counter = 0 thread = threading.Thread(target=print_sum,args=(l,)) thread.daemon = True thread.start() while True: counter = counter + 1 l.append(counter) time.sleep(1) This spins up a thread in the background running function print_sum to display the sum of the list.
answers question: http://stackoverflow.com/q/49227062
score: 0
upvote count: 1
type: Answer

http://stackoverflow.com/comment/85323080
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49157506
score: 0
has text: @flyingdutchman ... your code above does not use `executemany()` which you only have to call **once** on a list of values.

http://stackoverflow.com/q/49200901
has body: I have got a script that should calculate the square root of 2, only it currently has 2 problems that I can't seem to solve. Firstly, the while loop does not stop, even when it should stop: (This is the first few lines of the output when I run this script, the rest is just repeating the last 4 lines.) sqrt: 1.5 sq: 2.25 sqrt: 1.41666666667 sq: 2.00694444444 sqrt: 1.41421568627 sq: 2.0000060073 sqrt: 1.41421356237 sq: 2.0 sqrt: 1.41421356237 sq: 2.0 Also, as the square root of 2 is an infinite number, I do not understand why it stops at 1.41421356237 and does not make a bigger number. This is my code: import time def sq(inp): a = float(inp) return a * a a = 2.0 b = 1 while sq(b) != 2.0: b = (b + a / b) / 2 print 'sqrt: ', b print 'sq: ', sq(b) time.sleep(0.1) print 'Done!' (I have put in a few extra bits to clarify, like the print 'Done' and the delay, but it does not change anything for me.) Any help would be much appreciated. Thanks!
has comment: http://stackoverflow.com/comment/85407043
answer count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/85407050
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/588004
tagged with: python-2.7
type: Question
duplicate of: http://stackoverflow.com/q/588004
score: 0
tagged with: floating-point
has title: Python While loop not stopping

http://stackoverflow.com/comment/85495794
comment on: http://stackoverflow.com/a/49245889
type: Comment
has text: Are you sure? `argparse` can take spaces after long args. So can tools that use GNU getoptlong, and the standard or most popular parsers for most other modern languages (Go, Rust, Ruby, Node.js, etc.). There are some older (C) tools with custom parsers that take `--` longopts but don't quite follow the GNU standards, and they will have problems with this, but that wouldn't be my first guess.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85249595
comment on: http://stackoverflow.com/q/49121985
type: QuestionComment
type: Comment
has text: TypeError: the JSON object must be str, not 'TextIOWrapper'
score: 0

http://stackoverflow.com/q/49216327
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/1005676
score: 0
has title: Tornado GET request query vs query_arguments
tagged with: python
accepted answer: http://stackoverflow.com/a/49216465
tagged with: tornado
type: Question
has body: I am seeing a format difference between my tornado GET request handler query and query_arguments methods. request.query = "InstID=IRSwap/wN1G7RLwkUFP+LdocRpxPW&amp;EndDate=10Y' request.query_arguments = {'InstID': ['IRSwap/wN1G7RLwkUFP LdocRpxPW'], 'EndDate': ['10Y']} Why does the InstID value drop the '+' in favor of ' '? Is there a way I can force query_arguments to return a consistent format to the query string (return string with + value in it). Thanks!
answer count: 1
has answer: http://stackoverflow.com/a/49216465

http://stackoverflow.com/q/49222772
type: Question
has title: Pandas: frequencies per date grouped by column in a form of a list
upvote count: 3
downvote count: 0
possible better answer: http://stackoverflow.com/a/49222955
tagged with: string
has answer: http://stackoverflow.com/a/49222955
favorite count: 0
has body: I would like to obtain frequencies of technologies per date from pandas data frame. A reproducible example: data = pd.DataFrame( {'dates': ['2017-01-31', '2017-02-28', '2017-02-28'], 'tech': [['c++', 'python'], ['c++', 'c', 'java'], ['java']]} ) The end result could look like this (or have the names in rows and one column with counts per date and technology): date c++ python c java 2017-01-31 1 1 0 0 2017-02-28 1 0 1 2 The second column, by which the data should be grouped is a list of technologies. Simply trying to group by the data in the present state: data.groupby(['dates', data.tech.values]).count() produces an error: TypeError: unhashable type: 'list' so I presume that grouping by list is not possible.
type: AnsweredQuestion
tagged with: list
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49222893
score: 3
has answer: http://stackoverflow.com/a/49222893
tagged with: python
has answer: http://stackoverflow.com/a/49225192

http://stackoverflow.com/a/71629598
type: Answer
downvote count: 0
upvote count: 1
score: 1
has body: This solution passes the performance test with a score of 100% def solution(A): n = sorted(i for i in set(A) if i &gt; 0) # Remove duplicates and negative numbers if not n: return 1 ln = len(n) for i in range(1, ln + 1): if i != n[i - 1]: return i return ln + 1
answers question: http://stackoverflow.com/q/49224022

http://stackoverflow.com/comment/85476688
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49236273
has text: Dear James, Does it mean I still record sound from microphone by Pyaudio, but this time, the "microphone" is virtual? For example, I create a virtual microphone which is already wired up to the sound card output. @James Kent

http://stackoverflow.com/comment/85548545
score: 0
has text: @cdarke That's not quite equivalent in this case.
comment on: http://stackoverflow.com/q/49272861
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85534880
type: Comment
type: QuestionComment
has text: That's a good thing to google.
score: 0
comment on: http://stackoverflow.com/q/49265300

http://stackoverflow.com/comment/85560980
type: Comment
has text: Would it be possible if Child1 returns 'x = True' and I somehow incorporate the new 'x = True' to Child2 without inheritance?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49278467

http://stackoverflow.com/comment/85372419
comment on: http://stackoverflow.com/q/49183196
score: 0
type: Comment
type: QuestionComment
has text: search for the 3 separately, store in 3 separate lists, and then combine the lists? that would probably triple your runtime, are you searching through a large directory?

http://stackoverflow.com/comment/85415910
type: AnswerComment
comment on: http://stackoverflow.com/a/49203922
has text: Unfortunatley, matplotlib does not recognize the categories. If i change my series to: ser1 = pd.Series( ['tom','tom','bob','bob','nancy','zulu']) ser2 = pd.Series( ['tom','nancy']) The results will be incorrect. Even when the series dtype('category')
score: 0
type: Comment

http://stackoverflow.com/q/49201592
type: AnsweredQuestion
tagged with: python-telegram-bot
has title: Telegram API Ask for User Confirmation
tagged with: python
score: 1
has body: I am trying to make a basic User Prompt in python-telegram-bot that asks a user a confirmation of Yes or No. Yes will continue execution and No will just do nothing. I can currently make the prompt by doing keyboard = [ [InlineKeyboardButton(u"Yes", callback_data=???)], [InlineKeyboardButton(u"No", callback_data=???)] ] reply_markup = InlineKeyboardMarkup(keyboard) But what do I set the callback_data as? Is there a better way to do this?
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85416233
tagged with: telegram
accepted answer: http://stackoverflow.com/a/50319791
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85412829
upvote count: 1
has answer: http://stackoverflow.com/a/50319791

http://stackoverflow.com/comment/85490876
comment on: http://stackoverflow.com/q/49242820
has text: as of ffeast mentioned the stackoverflow question, they are totally different - even though it shows the same error message. Here, python 2 or 3 are all working fine. The problem seems HTTPD loading python virtual environment failed.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85487399
comment on: http://stackoverflow.com/q/49239961
score: 0
has text: Check if there is any change of the current working directory any where in your code. Try to generate absolute paths instead of relative ones..
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85543867
has text: @abarnert, I tried your suggestion regarding the `x==3` and `x%3` however it is necessary, because we only want to do the first grouping of 4 for the first group. Note that `ix=3` is the 4th character.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49269966

http://stackoverflow.com/q/49190411
tagged with: dataframe
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/49190438
answer count: 1
has title: Find a Text Pattern in python Data Frame
upvote count: 1
has answer: http://stackoverflow.com/a/49190438
has body: I have DataFrame having column with Chat Transcript. ID Chat 1 P1: Please call me soon P2 - will call you 2 P2: Please call me soon P1 - will call you I want to create a new column with yes/No or 1/0 if chat has pattern "call me soon" only between P1 &amp; P2 But not between P2 &amp; P1. Out put will be like ID Chat Call me soon 1 P1: Please call me soon P2 - will call you Yes 2 P2: Please call me soon P1 - will call you No I need to do it in python. Please suggest a appropriate method.
downvote count: 1
favorite count: 0
type: Question

http://stackoverflow.com/q/49193589
duplicate of: http://stackoverflow.com/q/49022273
duplicate of: http://stackoverflow.com/q/42874825
has comment: http://stackoverflow.com/comment/85392376
tagged with: python
type: Question
has title: What does this syntax mean in Keras Dropout(0.5)(X)?
score: 2
linked to: http://stackoverflow.com/q/14415881
linked to: http://stackoverflow.com/q/42874825
has comment: http://stackoverflow.com/comment/85391818
upvote count: 2
has answer: http://stackoverflow.com/a/49194324
duplicate of: http://stackoverflow.com/q/14415881
has body: I know that 'X' on right-hand side is the input before you applied dropout. Now when you say Dropout(0.5)(X), it means that you are randomly making the activation of 50% of the neurons in the input to zero. This line Dropout(0.5) means which are making a new object of class Dropout and passing 0.5 in its constructor. But appending X at the end of it? What does this mean in Python Syntax?
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/49194324
linked to: http://stackoverflow.com/q/49022273
type: AnsweredQuestion

http://stackoverflow.com/q/49201714
downvote count: 0
answer count: 1
upvote count: 1
has answer: http://stackoverflow.com/a/49201724
has comment: http://stackoverflow.com/comment/85467838
favorite count: 0
type: Question
linked to: http://stackoverflow.com/q/1239035
tagged with: python-multithreading
type: UnansweredQuestion
has title: Saving and retrieving thread object/state python
has body: I am using the python threading module for the first time and this is what I am trying to find out -- can we save and load state of python thread object in some database or file? Let's say I have the below piece of code in a program (this program runs like a server using python twisted) to do something asynchronously (like copying files in a non-blocking fashion). def foo(): print('Hello world!') import threading thr = threading.Thread(target=foo, args=(), kwargs={}) thr.start() Now, I don't do thr.join() here as I don't want to wait for the thread to complete. Now, is it even possible to save the state of thread or object and later retrieve it and find out if the thread is still alive or not? I can get the thread id and status by doing this but only through the thread object. # thr.ident # check status of thread by doing thr.is_alive() I may be completely wrong here - but is it possible to save/load thread objects? Also, looking for suggestions. Thanks a lot!
tagged with: python
score: 1
tagged with: multithreading

http://stackoverflow.com/comment/110301075
type: QuestionComment
comment on: http://stackoverflow.com/q/49270277
type: Comment
score: 0
has text: If n=1, you need to return a 1 for control statement on line 2, "if n==0" for the recursive call; otherwise, you'll return an area of 0. The for loop is unnecessary, but shouldn't cause any real issue.

http://stackoverflow.com/comment/85337736
type: Comment
has text: This should provide you with the details you are looking for (Refer tensorflows documentation on skip-grams vs CBOW for more clarity) https://www.analyticsvidhya.com/blog/2017/07/word-representations-text-classification-using-fasttext-nlp-facebook/
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49152069

http://stackoverflow.com/q/49206388
type: AnsweredQuestion
has title: Use a string in Python as a parameter for a function
has body: I have a problem I can't solve in Python. The question is hard to even put into words, so see the example below. phoneBook = {"Joe":12, "Jason":13, "Johnny":14} for i in range(0, len(dir(phoneBook))): if "__" not in dir(phoneBook)[i]: print(help(phoneBook.dir(phonebook)[i]) + "\n\n") What I want to do is to print the help() method for each dir() entry that doesn't contain underscores. (i.e., calling dir(phoneBook) returns clear, copy, fromkeys, get, items, etc...). I want the help() method to then print each of the values that dir() returns, as seen in the for loop above. However, if I use the syntax as shown above, I get a syntax error. There are other applications of this principle, this is a quick example that I can think of off the top of my head. Thanks in advance.
answer count: 2
score: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/49206439
has comment: http://stackoverflow.com/comment/85417764
upvote count: 1
possible better answer: http://stackoverflow.com/a/49206428
has answer: http://stackoverflow.com/a/49206439
favorite count: 0
type: Question
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/49206428

http://stackoverflow.com/a/49219138
downvote count: 0
upvote count: 1
accepted answer of: http://stackoverflow.com/q/49219009
has body: def __init__(self): self.last = time.time() #Initialization instant def cars_on_road(self, dis_cars,forbid_cars): if len(forbid_cars) &gt; 0 and dis_cars == forbid_cars: time_calculate = time.time() - self.last #Difference between self.last and the instant the sets became equal print "time_calculate" + str(time_calculate) self.last = time.time() #Do this if this method will be called again
answers question: http://stackoverflow.com/q/49219009
type: Answer
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/49212558
has answer: http://stackoverflow.com/a/49212752
favorite count: 0
has answer: http://stackoverflow.com/a/49212655
type: Question
accepted answer: http://stackoverflow.com/a/49212655
has title: Python - Appending a column to a list of DataFrames
score: 3
possible better answer: http://stackoverflow.com/a/49212752
has answer: http://stackoverflow.com/a/49213186
tagged with: pandas
has answer: http://stackoverflow.com/a/49212906
tagged with: dataframe
tagged with: python
answer count: 4
type: AnsweredQuestion
has body: I have a list that is comprised of DataFrames where I would like to iterate over the list of DataFrames and insert a column to each DataFrame based on an array. Below is a small example that I have created for illustrative purposes. I would do this manually if it was only 4 DataFrames but my dataset is much larger: #Create dataframes df1 = pd.DataFrame(list(range(0,10))) df2 = pd.DataFrame(list(range(10,20))) df3 = pd.DataFrame(list(range(20,30))) df4 = pd.DataFrame(list(range(30,40))) #Create list of Dataframes listed_dfs = [df1,df2,df3,df4] #Create list of dates Dates = ['2015-05-15','2015-02-17', '2014-11-14', '2014-08-14'] #Objective: Sequentially append each instance of "Dates" to a new column in each dataframe #First, create list of locations for iterations locations = [0,1,2,3] #Second, create for loop to iterate over [Need help here] #Example: for the 1st Dataframe in the list of dataframes, add a column 'Date' that # has the the 1st instance of the 'Dates' list for every row, # then for the 2nd DataFrame in the list of dataframes, add the 2nd instance of the 'Dates' list for every row for i in Dates: for a in locations: listed_dfs[a]['Date'] = i print(listed_dfs) The problem with the above for loop is that it applies the last date first, then it does not apply the 2nd date to the 2nd DataFrame, only the 1st date for each DataFrame. Desired Output from for loop: listed_dfs[0]['Date'] = Dates[0] listed_dfs[1]['Date'] = Dates[1] listed_dfs[2]['Date'] = Dates[2] listed_dfs[3]['Date'] = Dates[3] pd.concat(listed_dfs)
upvote count: 3
tagged with: list
downvote count: 0

http://stackoverflow.com/a/49289090
score: 6
answers question: http://stackoverflow.com/q/49141083
accepted answer of: http://stackoverflow.com/q/49141083
upvote count: 6
type: Answer
downvote count: 0
has body: Let's start by trying to solve the confusion I think my confusion comes down to misunderstanding what this actually means: Notice that only one connection is specified, but the systems form a circuit since: (1) the lengths of the paths are justified and (2) the orientation and ordering of the flows is mirrored. (2) The orientation and ordering of the flows is mirrored. The thing you probably understood wrong is the meaning of mirrored, which is indeed confusing in this case. One would think, that mirrored equals inverted, but this is only partly true: The flows (or as you call it in your code: values) must be inverted, this one you got right. Because the values corresponds to the inputs(value &gt; 0) or outputs(value &lt; 0). And only an output can be connected to an input, and vice versa. But the orientation must be the same for both flows which you try to connect. This one isn't inverted, but it still needs to be "mirrored". What is meant with that? Well, if an I/O is looking in the direction of the arrow he came from, it needs to see another I/O (as when looking in a mirror), only then they can connect themselves. It's not so easy to explain as a non-native speaker, but I'll try to illustrate the idea: Able to connect: Not able to connect: Not able to connect: I/O Mirror I/O I/O Mirror I/O I/O Mirror I/O ╚══&gt; | &gt;══╝ ╗ | ╔ | ║ ║ | ║ ══&gt; | ║ v | ^ | ^ In your code, you have inverted the orientation. That's why for example the 3rd flow of the orange system is in the top left corner, and its counterpart from the blue system is in the bottom right. There is no way, that these I/Os will ever be able to "see" each other. You can revert the inverting of the second system by deleting the - which prepends the x in orientations: orientations=[x["orientation"] for x in system_2] You'll see that now the flows are close to each other, but you're in a situation like shown in the Not able to connect-illustration (No. 2). This means the structure of your diagram won't be…
type: AcceptedAnswer

http://stackoverflow.com/q/49219465
answer count: 1
downvote count: 0
tagged with: machine-learning
score: 1
upvote count: 1
favorite count: 0
type: Question
tagged with: dummy-variable
linked to: http://stackoverflow.com/q/37425961
accepted answer: http://stackoverflow.com/a/49219528
tagged with: python
has answer: http://stackoverflow.com/a/49219528
type: AnsweredQuestion
tagged with: pandas
has title: Dummy variables when not all categories are present across multiple features & data sets
has body: I want to ask an extension of this question, which talks about adding a label to missing classes to make sure the dummies are encoded as blanks correctly. Is there a way to do this automatically across multiple sets of data and have the labels automatically synched between the two? (I.e. for Test &amp; Training sets). I.e. the same columns but different classes of data represented in each? E.g.: Suppose I have the following two dataframes: df1 = pd.DataFrame.from_items([('col1', list('abc')), ('col2', list('123'))]) df2 = pd.DataFrame.from_items([('col1', list('bcd')), ('col2', list('234'))]) df1 col1 col2 1 a 1 2 b 2 3 c 3 df2 col1 col2 1 b 2 2 c 3 3 d 4 I want to have: df1 col1_a col1_b col1_c col1_d col2_1 col2_2 col2_3 col2_4 1 1 0 0 0 1 0 0 0 2 0 1 0 0 0 1 0 0 3 0 0 1 0 0 0 1 0 df2 col1_a col1_b col1_c col1_d col2_1 col2_2 col2_3 col2_4 1 0 1 0 0 0 1 0 0 2 0 0 1 0 0 0 1 0 3 0 0 0 1 0 0 0 1 WITHOUT having to specify in advance that col1_labels = ['a', 'b', 'c', 'd'], col2_labels = ['1', '2', '3', '4'] And can I do this systematically for many columns all at once? I'm imagining a fuction that when passed in two or more dataframes (assuming columns are the same for all): reads which columns in the pandas dataframe are categories figures out what that overall labels are and then provides the category labels to each column Does that seem right? Is there a better way?

http://stackoverflow.com/q/49211458
has answer: http://stackoverflow.com/a/49211548
has comment: http://stackoverflow.com/comment/85427334
has answer: http://stackoverflow.com/a/49211571
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85427385
answer count: 2
upvote count: 0
has body: I have two strings: ['Renewables\n', '17.9% (3,951 MW)\n'] ['Solar\n', '27.4% (1,081 MW)\n', 'LATEST SYSTEM\n', 'GENERATION\n', '4,738 MW\n', 'THERMAL GENERATION\n', '(COAL, GAS, OTHER)\n', '54 %\n', 'RENEWABLE\n', 'GENERATION\n', '47.61 %\n'] But the only data I want from each is the numerical value of the percentage at the end of each string e.g 17.9 and 47.61, I want to take these numbers and use them in a follow up program where an outcome will be determined depending on which number is larger, as they are the results of a web scraping tool. How do I extract just these values as floats so I can use them going forward? Edit Just to make it clear, I only want the last percentage values of each string, any MW values or previous percentage values are not wanted.
tagged with: string
possible better answer: http://stackoverflow.com/a/49211571
downvote count: 1
has comment: http://stackoverflow.com/comment/85427479
favorite count: 0
has comment: http://stackoverflow.com/comment/85427306
has comment: http://stackoverflow.com/comment/85427390
type: Question
tagged with: extract
has comment: http://stackoverflow.com/comment/85427344
has title: Extracting wanted numerical values from strings in Python
accepted answer: http://stackoverflow.com/a/49211548
tagged with: python
score: -1

http://stackoverflow.com/comment/85395434
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49194281
has text: Please look at the docs I linked to, or the Django docs themselves, for the syntax for `render`; it is `render(request, template_name, context)`.
type: Comment

http://stackoverflow.com/q/49127897
accepted answer: http://stackoverflow.com/a/49128242
upvote count: 10
possible better answer: http://stackoverflow.com/a/69634876
has title: Python Pandas Fillna Median not working
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49128242
tagged with: python-3.x
has answer: http://stackoverflow.com/a/69634876
score: 10
tagged with: dataframe
tagged with: python
has comment: http://stackoverflow.com/comment/85260381
has comment: http://stackoverflow.com/comment/85260455
type: AnsweredQuestion
tagged with: python-2.7
answer count: 2
tagged with: pandas
has body: I am trying to fill all the nans in a dataframe containing multiple columns and several rows. I am using this to train a multi variate ML-model so I want to fill the nans for each column with the median. Just to test the median function I did this: training_df.loc[[0]] = np.nan # Sets first row to nan print(training_df.isnull().values.any()) # Prints true because we just inserted nans test = training_df.fillna(training_df.median()) # Fillna with median print(test.isnull().values.any()) # Check afterwards But when I do this nothing happens, the print of the last row still returns True. If I try to change to use the median function like this instead: training_df.fillna(training_df.median(), inplace=True) Nothing happens as well. If I do this: training_df = training_df.fillna(training_df.median(), inplace=True) Training_df becomes none. How can I solve this?
downvote count: 0

nlp
tags question: http://stackoverflow.com/q/49145386
tags question: http://stackoverflow.com/q/49227015
tags question: http://stackoverflow.com/q/49233067
tags question: http://stackoverflow.com/q/49130879
tags question: http://stackoverflow.com/q/49161277
tags question: http://stackoverflow.com/q/49274650
tags question: http://stackoverflow.com/q/49219826
tags question: http://stackoverflow.com/q/49183719
tags question: http://stackoverflow.com/q/49249404
tags question: http://stackoverflow.com/q/49184241
tags question: http://stackoverflow.com/q/49247590
tags question: http://stackoverflow.com/q/49132607
tag name: nlp
tags question: http://stackoverflow.com/q/49179118
tags question: http://stackoverflow.com/q/49173754
type: Tag
tags question: http://stackoverflow.com/q/49134593
tags question: http://stackoverflow.com/q/49125026
tags question: http://stackoverflow.com/q/49197667
tags question: http://stackoverflow.com/q/49252156
tags question: http://stackoverflow.com/q/49217493

http-patch
tags question: http://stackoverflow.com/q/49184472
tag name: http-patch
type: Tag

http://stackoverflow.com/comment/85456559
has text: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/166643/discussion-between-abarnert-and-sharan-duggirala).
score: 0
comment on: http://stackoverflow.com/q/49226243
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85465994
has text: Thanks @rendrum however I am running a single uwsgi instance exposing all workers on the same socket. I could switch to multiple uswgi processes but then I would lose the worker management abilities uwsgi gives me.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/49231130
type: QuestionComment

http://stackoverflow.com/a/49221372
has body: Get in the habit of having your functions return values. Functions with no return statement return None by default. Here is an example of how you might rewrite your program: class Simple: def __init__(self, str): self.s = str # Two methods: def show(self): return self.s def showMsg(self, msg): return msg + ': ' + self.show() x = Simple("A constructor argument") print(x.show()) # A constructor argument print(x.showMsg('A message')) # A message: A constructor argument While you can have print inside your class, it's a better idea to have your class handle logic and have flexibility with what you do with the results (print them, store them in a list, pass them on to another function, etc).
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49221338

http://stackoverflow.com/a/49154062
has comment: http://stackoverflow.com/comment/85312606
type: Answer
downvote count: 0
upvote count: 1
type: AcceptedAnswer
has body: As the error message suggests, you define a function that accepts a single argument and try to pass eight of them to it. Two simplest fixes are: Call it with a single iterable as argument: print(max_sum2((3, -10, 4, -1, 2, 3, 6, -7))) Redefine the function to accept arbitrary number of arguments: def max_sum2(*nums):
accepted answer of: http://stackoverflow.com/q/49153945
answers question: http://stackoverflow.com/q/49153945
score: 1

http://stackoverflow.com/q/49247557
has comment: http://stackoverflow.com/comment/85502239
has comment: http://stackoverflow.com/comment/85514761
score: 1
has comment: http://stackoverflow.com/comment/85501541
answer count: 1
has comment: http://stackoverflow.com/comment/85502855
upvote count: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/85499308
has title: Why cannot I close the world of my ontology
has body: I defined some classes under my ontology. But I faced with a problem, I cannot close the world of my ontology lib. To my surprise, if I rewrite Teacher class as class Teacher(Employee): equivalent_to = [Person &amp; empolied.min(1, University)] or class Teacher(Employee): equivalent_to = [Person &amp; empolied.min(1, College)] even class Teacher(Employee): equivalent_to = [Person] it will be closed successfully. It seams that the problem is raised from the expression University | College. Moreover, I can close any class in the ontology including Thing. What is the reason? # -*- coding: utf-8 -*- from owlready2 import * import datetime society = get_ontology("http://test.org/society.owl") with society: class Person(Thing): def __ini__(self, wholename='', birthday=None, gender='male', *args, **kwargs): super(Person, self).__ini__(*args, **kwargs) self.wholename = wholename self.birthday = birthday self.gender = gender self.info = '' def __str__(self): return '%s (%s, %s)'%(self.wholename, self.birthday, self.gender) class Orgonization(Thing): def __ini__(self, wholename='', birthday=0, members=[], taxno='', *args, **kwargs): super(Person, self).__ini__(*args, **kwargs) self.wholename = wholename self.birthday = birthday self.members = members self.taxno = taxno self.info = '' class Institution(Orgonization): pass class University(Institution): pass class College(Institution): pass class Employee(Person): def __ini__(self, no=0, level=0, salary=0, *args, **kwargs): super(Person, self).__ini__(*args, **kwargs) self.no = no self.level = level self.salary = salary def show_info(self): print(self) print('no: %s\nlevel: %d\nsalary: %.2f'%(self.no, self.level, self.salary)) class empolied(Employee &gt;&gt; Orgonization): pass class empoly(Orgonization &gt;&gt; Employee): inverse_property = empolied class friend(Person &gt;&gt; Person, SymmetricProperty): pass class Teacher(Employee): equivalent_to = [Person &amp; empolied.min(1, University | College)] zjc = College('zjc', wh…
tagged with: owl
type: UnansweredQuestion
downvote count: 0
tagged with: owlready
tagged with: ontology
tagged with: python
has answer: http://stackoverflow.com/a/49251923

http://stackoverflow.com/q/49219565
type: Question
has body: hello i am trying to insert new patterns in aiml using python(aiml library) i am following this tutorial, i can use the predefined patterns of A.L.I.C.E chatbot and change the answer of it using the template tag but when I insert new pattern which is not in the A.L.I.C.E chatbot the program gives this error WARNING: No match found for input: '', please help is there a way to insert new patterns using python aiml library? below is my chatbot.py file import aiml import sys mybot = aiml.Kernel() mybot.setBotPredicate('name','chefbot') mybot.learn('sample.aiml') while True: if input == "quit": sys.exit(0) input_text = input("> ") response = mybot.respond(input_text) print(response) This is my sample.aiml file WHY CAN NOT YOU EAT Actually I eat only electricity. EACH YEAR IN PRO BASEBALL THE * The Gold Glove. hello Hello my friend how are you,i am chefbot WHAT IS YOUR NAME My name is chefbot YOU CAN DO BETTER Get that cake for me It gives response to the patterns in UpperCase because they are predefined in A.L.I.C.E bot but prints error on patterns which I have defined in Lowercase. Thanks in advance..
answer count: 1
tagged with: aiml
has title: how to insert new patterns in python aiml
type: AnsweredQuestion
score: 0
accepted answer: http://stackoverflow.com/a/49249559
has answer: http://stackoverflow.com/a/49249559
tagged with: python

http://stackoverflow.com/comment/85643207
has text: Do you want people to import your modules or do you want them to access them through an API or a webpage?
comment on: http://stackoverflow.com/q/49220475
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/49170357
type: Answer
has comment: http://stackoverflow.com/comment/85346146
downvote count: 0
upvote count: 1
has body: There is a regex module in python (https://docs.python.org/3.6/library/re.html) That should do exactly the same thing just with import re m = re.search("i*(?&lt;!\\.)cake.*", your_string) for match in m: print(m)
answers question: http://stackoverflow.com/q/49170237
score: 1

http://stackoverflow.com/q/49256431
linked to: http://stackoverflow.com/q/3394835
has body: I have a class to parse data from some online dictionaries, it reads info about word from json and then executes methods as json tells to. An example of json: { "functions": [ { "name": "find_translations", "properties": { "only_first": false } }, { "name": "find_synonyms", "properties": { "number": 5 } ], "word": "to exuberate", "language": "angielski", "target_language": "polski", "collection": "default" } So, I have a class with methods find_translations and find_synonyms. And __init __ is reading the json, and I want to execute functions with parameters as in json. I could do a bunch of ifs, but it isn't scalable, I guess. I could do eval(), but it is a vulnerability. What do I do? Can I create something like a dictionary with functions? EDIT: Here's my class (simplified): class Parser: def __init__(self, path): ... # reads data from json ... # my problem: I need to launch methods from this class # that were mentioned in json. In case from example, I'd launch self.find_translations(self) self.find_synonyms(self) # it is an example, so without parameters def find_translations(self): # do something def find_synonyms(self): # do something def find_usage(self): # do something
score: 1
possible better answer: http://stackoverflow.com/a/49256769
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/85515961
has answer: http://stackoverflow.com/a/49256769
accepted answer: http://stackoverflow.com/a/49257041
has title: Alternative to eval when reading json
type: Question
tagged with: function
answer count: 2
has answer: http://stackoverflow.com/a/49257041
has comment: http://stackoverflow.com/comment/85516445
has comment: http://stackoverflow.com/comment/85515840
downvote count: 0
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/85516114
tagged with: class
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json

axios
tag name: axios
type: Tag
tags question: http://stackoverflow.com/q/49273858

superclass
type: Tag
tag name: superclass
tags question: http://stackoverflow.com/q/49268725

ip
tags question: http://stackoverflow.com/q/49123337
type: Tag
tag name: ip

http://stackoverflow.com/a/49127793
has comment: http://stackoverflow.com/comment/85283514
answers question: http://stackoverflow.com/q/49126651
upvote count: 1
has body: You could also do this: from bs4 import BeautifulSoup from collections import Counter import requests soup = BeautifulSoup(requests.get("https://en.wikipedia.org/wiki/Beautiful_Soup_(HTML_parser)").text, "html.parser") foundUrls = Counter([link["href"] for link in soup.find_all("a", href=lambda href: href and not href.startswith("#"))]) foundUrls = foundUrls.most_common() for item in foundUrls: print ("%s: %d" % (item[0], item[1])) The soup.find_all line checks if every atag has an href set and if it doesn't start with the # character. The Counter method counts the occurrences of each list entry and the most_common orders by the value. The for loop just prints the results.
downvote count: 1
type: Answer
score: 0

http://stackoverflow.com/q/49162364
upvote count: 3
type: UnansweredQuestion
score: 3
downvote count: 0
tagged with: mask
has body: Is there an implement way or procedure to get an aproximation of the percentage of a structure/color in a image using opencv. I was attempting several methods by using masks, CLAHE, kernels, transformation...but don't really achieve what I am looking for. Let's suppose I want to count or detect the percentage of a structure which can have a color in a particulare image. For instance, if I have the following image: redeye If I want to represent the percentage of blood vessels (those red ones) How shoul I proceed?. This is what I already tried but doesn't seem to be the optimal way: path = 'C:/.../redeye.jpg' img=cv2.imread(path) #try with HSV (I already tried RGB transformation) img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # lower mask (0-10) lower_red = np.array([7,50,50]) upper_red = np.array([10,255,255]) mask0 = cv2.inRange(img_hsv, lower_red, upper_red) # upper mask (170-180) lower_red = np.array([170,50,50]) upper_red = np.array([180,255,255]) mask1 = cv2.inRange(img_hsv, lower_red, upper_red) # join my masks mask = mask0+mask1 # set my output img to zero everywhere except my mask output_img = img.copy() output_img[np.where(mask==0)] = 0 plt.imshow(output_img) plt.show()
favorite count: 0
type: Question
tagged with: opencv
has title: percentage of a color/structure in image openCV python
tagged with: python
answer count: 0

http://stackoverflow.com/comment/85550922
type: AnswerComment
comment on: http://stackoverflow.com/a/49272921
score: 0
type: Comment
has text: You're right, I forgot to mention that the developer will need to append to the list also.

http://stackoverflow.com/comment/85416014
comment on: http://stackoverflow.com/q/49204280
score: 0
has text: The source mask needs to use all of the color regions that the target mask uses, but it may also have extra unneeded color regions that can be utilized by other target image/mask combinations (or just simply these unused color regions are ignored). However I think that my code handles this at the moment.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85366980
comment on: http://stackoverflow.com/a/49179514
score: 0
type: AnswerComment
has text: @vijaysingh I don't understand what you mean. If you want different values in different functions (on the same object), you presumably want them to have different names, so you can refer to those different values in some way. And you can have multiple attributes with different names, of course, just like you have have multiple local variables with different names.
type: Comment

http://stackoverflow.com/comment/85290301
has text: Then I'd re-raise wim's suggestion that you try `numpy` here. Especially if you've never used it before. Of course it's also worth learning how to code up something like this for yourself, but _doing_ clever things with matrices and vectors is going to come up a lot more often than _implementing_ clever matrix and vector classes.
type: Comment
comment on: http://stackoverflow.com/q/49141878
score: 0
type: QuestionComment

http://stackoverflow.com/comment/85379151
score: 3
comment on: http://stackoverflow.com/a/49186889
type: Comment
type: AnswerComment
has text: @MateenUlhaq Hmm, feeling a little mad scientist-y these days ;)

http://stackoverflow.com/comment/85384228
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/49189075
score: 0
has text: Ofc, one second I update my first coment

http://stackoverflow.com/comment/85519553
score: 0
type: Comment
type: AnswerComment
has text: File "C:\Users\Simon\AppData\Local\Programs\Python\Python36-32\lib\site-packages\openpyxl\reader\excel.py", line 121, in _validate_archive archive = ZipFile(filename, 'r', ZIP_DEFLATED) File "C:\Users\Simon\AppData\Local\Programs\Python\Python36-32\lib\zipfile.py", line 1090, in __init__ self.fp = io.open(file, filemode) FileNotFoundError: [Errno 2] No such file or directory: 'wellbeing.xlsx'
comment on: http://stackoverflow.com/a/49244258

http://stackoverflow.com/a/49277164
score: 2
upvote count: 2
downvote count: 0
answers question: http://stackoverflow.com/q/49275996
type: Answer
has body: Try using slice. First, you need to find the rows where C == 0. So let's create a bool df for this. I'll just name it 'a': a = (df['C'] == 0) So, whenever C == 0, a == True. Now we need to find the index of each row where C == 0, create an empty row and add it to the df: df2 = df.copy() #make a copy because we want to be safe here for i in df.loc[a].index: empty_row = pd.DataFrame([], index=[i]) #creating the empty data j = i + 1 #just to get things easier to read df2 = pd.concat([df2.ix[:i], empty_row, df2.ix[j:]]) #slicing the df df2 = df2.reset_index(drop=True) #reset the index I must say... I don't know the size of your df and if this is fast enough, but give it a try
has comment: http://stackoverflow.com/comment/85558798

http://stackoverflow.com/comment/85292920
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49143799
has text: you should use python's `set` type for this. It supports difference, union, intersection, etc.

http://stackoverflow.com/comment/85459358
comment on: http://stackoverflow.com/a/49227566
score: 0
has text: @pstatix Trying to understand the reasons behind downvotes is hard enough; trying to understand why people think those are good reasons is beyond me. I stopped worrying about scores years ago, beyond making me briefly consider whether to expand or rewrite. (And, frankly, if you've seen the length of most of my answers, all that expanding may not be a good thing…)
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/85477443
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49236770
has text: @BryanOakley I have been trying since I last posted... All I have is a square box with the title "zork" nothing else and I have watched like 6 hours of tutorials with no luck.
score: 0

http://stackoverflow.com/comment/85248859
has text: i changed the variable name but the same problem
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49121587
type: Comment

http://stackoverflow.com/q/49228596
downvote count: 0
tagged with: python
has body: I have the below case statement in python, pd_df['difficulty'] = 'Unknown' pd_df['difficulty'][(pd_df['Time']&lt;30) &amp; (pd_df['Time']&gt;0)] = 'Easy' pd_df['difficulty'][(pd_df['Time']&gt;=30) &amp; (pd_df['Time']&lt;=60)] = 'Medium' pd_df['difficulty'][pd_df['Time']&gt;60] = 'Hard' But when I run the code, it throws an error. A value is trying to be set on a copy of a slice from a DataFrame
favorite count: 0
type: AnsweredQuestion
tagged with: conditional-statements
has answer: http://stackoverflow.com/a/76866430
upvote count: 61
tagged with: pandas
tagged with: dataframe
has title: Pandas - Case when & default in pandas
possible better answer: http://stackoverflow.com/a/73619829
answer count: 4
accepted answer: http://stackoverflow.com/a/49228646
score: 61
type: Question
has answer: http://stackoverflow.com/a/73619829
has answer: http://stackoverflow.com/a/73973563
has answer: http://stackoverflow.com/a/49228646

http://stackoverflow.com/comment/85502723
type: QuestionComment
has text: Can you post the dictionary contained in `data`?
comment on: http://stackoverflow.com/q/49249675
score: 0
type: Comment

http://stackoverflow.com/comment/85416162
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49204613
has text: @BradSolomon No, you are right, there was an indexing error. Thanks for pointing it out.

http://stackoverflow.com/q/49137152
tagged with: python
has comment: http://stackoverflow.com/comment/85279738
tagged with: sqlalchemy
score: 0
has comment: http://stackoverflow.com/comment/85282879
answer count: 0
tagged with: sql
type: UnansweredQuestion
type: Question
tagged with: foreign-keys
has body: I'm kind of a noobie when it comes to sqlalchemy and RDBMS's but I've recently taken on a project that requires it. I want to try and do everything through the ORM too. This is the set up that I have: class A(Base): __tablename__ = 'a' id = Column(Integer, primary_key=True) b_children = relationship('B') x_children = relationship('X') y_children = relationship('Y') class B(Base): __tablename__ = 'b' id = Column(Integer, primary_key=True) c_children = relationship('C') x_children = relationship('X') y_children = relationship('Y') a_parent_id = Column(Integer, ForeignKey('a.id')) class C(Base): __tablename__ = 'c' id = Column(Integer, primary_key=True) x_children = relationship('X') y_children = relationship('Y') b_parent_id = Column(Integer, ForeignKey('b.id')) class X(Base): __tablename__ = 'x' id = Column(Integer, primary_key=True) a_parent_id = Column(Integer, ForeignKey('a.id')) b_parent_id = Column(Integer, ForeignKey('b.id')) c_parent_id = Column(Integer, ForeignKey('c.id')) class Y(Base): __tablename__ = 'y' id = Column(Integer, primary_key=True) a_parent_id = Column(Integer, ForeignKey('a.id')) b_parent_id = Column(Integer, ForeignKey('b.id')) c_parent_id = Column(Integer, ForeignKey('c.id')) So A, B, and C are all hierarchical. A's contains B's, B's contain C's, and C's are the end of that tree. A's, B's, and C's can all contain X's and Y's. So far so good, right? The kicker is that X's and Y's can only be attached to one A, B, or C at a time. I don't want to have an A and a B that reference the same X or Y. I also don't want to have excess columns that aren't being used. In this case, X's and Y's will always have two empty columns. I am pretty sure that there is no way for sqlalchemy (or SQL for that matter) to combine multiple ForeignKeys into a single column, because that wouldn't make much sense. My question, however, is this: Is what I want to achieve here even possible? Is there a better way to do this using a different database system? Or should I com…
has title: sqlalchemy and handling multiple foreign keys in a single column

http://stackoverflow.com/a/49204372
answers question: http://stackoverflow.com/q/49204190
score: 8
upvote count: 8
has body: Should've relized this far sooner, once I added the $or it needs to be in quotes. So this works: dataout = releasescollection.find( { "$or": [{"l_title":{"$regex": "i walk the line", "$options": "-i"}}, {"artistJoins.0.artist_name":{"$regex": "Johnny Cash", "$options": "-i"}}]}).sort('id', pymongo.ASCENDING).limit(25)
has comment: http://stackoverflow.com/comment/101183825
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/49204190
type: AcceptedAnswer

http://stackoverflow.com/a/49205251
answers question: http://stackoverflow.com/q/49204639
type: Answer
score: 13
upvote count: 13
has comment: http://stackoverflow.com/comment/85429125
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49204639
has body: Going straight to the source of Lib/csv.py, excel-tab has all the properties of excel, plus a tab-delimiter. class excel(Dialect): """Describe the usual properties of Excel-generated CSV files.""" delimiter = ',' quotechar = '"' doublequote = True skipinitialspace = False lineterminator = '\r\n' quoting = QUOTE_MINIMAL register_dialect("excel", excel) class excel_tab(excel): """Describe the usual properties of Excel-generated TAB-delimited files.""" delimiter = '\t' register_dialect("excel-tab", excel_tab)
has comment: http://stackoverflow.com/comment/85429194

http://stackoverflow.com/comment/85345969
score: 0
type: AnswerComment
has text: I like this way, too!
comment on: http://stackoverflow.com/a/49170411
type: Comment

http://stackoverflow.com/a/49219534
score: 2
type: Answer
has body: 1) itertools.product all_combinations = itertools.product(elements) 2) filter with lambda filtered_combinations = filter(lambda x: len(x) != len(set(x)), all_combinations)
answers question: http://stackoverflow.com/q/49219469
upvote count: 2
accepted answer of: http://stackoverflow.com/q/49219469
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/49191508
tagged with: uwsgi
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/49271551
answer count: 1
has comment: http://stackoverflow.com/comment/85392539
has comment: http://stackoverflow.com/comment/85389905
has body: I have the following stack for my application: NGINX (1.4.6) uWSGI (1.9.17.1-debian (64bit)) Flask Python 3.4 The Problem After NGINX restart all works well for a period(few minutes). After that period I receive a "504 Gateway Time-out" error. NGINX log: *13 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 86.123.39.44, server: app.fc.com, request: "GET /dashboard/overview HTTP/1.1", upstream: "uwsgi://127.0.0.1:8001", host: "app.fc.com", referrer: "http://app.fc.com/dashboard/overview" uWSGI log: app.fc.com [pid: 100017|app: 0|req: 103/219] 86.123.39.44 () {44 vars in 859 bytes} [Fri Mar 9 06:24:22 2018] GET /login => generated 245 bytes in 1 msecs (HTTP/1.1 302) 3 headers in 131 bytes (1 switches on core 1) My NGINX configuration is: server { listen 80; listen [::]:80; root /var/www/fc/website; index index.html index.htm index.php; # Make site accessible from http://localhost/ server_name app.fc.com; location / { sendfile on; client_max_body_size 20M; keepalive_timeout 0; proxy_connect_timeout 10; proxy_send_timeout 15; proxy_read_timeout 20; include uwsgi_params; uwsgi_pass 127.0.0.1:8001; #uwsgi_read_timeout 30; #uwsgi_send_timeout 30; uwsgi_connect_timeout 60; uwsgi_ignore_client_abort on; } } My uWSGI configuration is: [uwsgi] vhost = true socket = :8001 #wsgi-file = /var/www/app.fc.com/reviewApp/wsgi.py wsgi-file = /var/www/fc/app/wsgi.py callable = app processes = 2 threads = 4 chdir = /var/www/fc/app/ pythonpath = /var/www/fc/app/ pythonpath = /var/www/py3/lib/python3.4 virtualenv = /var/www/py3 plugins = python3 Usually, the response to my request last under 5 seconds
tagged with: flask
favorite count: 0
type: Question
score: 3
upvote count: 3
tagged with: redis
tagged with: nginx
has comment: http://stackoverflow.com/comment/85392350
has title: Upstream timed out (uWSGI + NGINX + Flask)
has answer: http://stackoverflow.com/a/49271551
tagged with: python

http://stackoverflow.com/q/49235785
upvote count: 1
accepted answer: http://stackoverflow.com/a/49236484
favorite count: 0
has answer: http://stackoverflow.com/a/49236484
type: Question
has body: I need to multiply each month of my data by the number of days in the corresponding month. The data are average monthly precipitation and multiplying by the number of days will have accumulated precipitation. I would like a pythonic way of doing this (maybe xarray or pandas). My code at below: #!/usr/bin/env python3.6 import xarray as xr ncfile = 'https://www.esrl.noaa.gov/psd/thredds/dodsC/' \ 'Datasets/cmap/std/precip.mon.mean.nc' with xr.open_dataset(ncfile, autoclose=True) as dset: lat = dset['lat'] lon = dset['lon'] precip = dset['precip'] print(precip) For Example: The first three months from data are: 1979-01-01, 1979-02-01, 1979-03-01, so: print(precip[0:3, 10, 10].values) [ 0.81 0.76999998 0.70999998] 0.81 * 31 0.76999998 * 28 0.70999998 * 31
has comment: http://stackoverflow.com/comment/85474732
tagged with: python
has title: How multiply month by the number of days
tagged with: python-xarray
type: AnsweredQuestion
tagged with: pandas
has comment: http://stackoverflow.com/comment/85474866
has comment: http://stackoverflow.com/comment/85475469
score: 1
has comment: http://stackoverflow.com/comment/85484737
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/85459425
type: QuestionComment
has text: The most idiomatic way is to `yield x` instead. That doesn't give you a list, but it gives you, almost like magic, a different kind of iterable that can be used like a list in most ways. Don't use this until you're ready to learn about generators and iterators—but once you are, you'll start using it all over the place.
score: 1
comment on: http://stackoverflow.com/q/49227963
type: Comment

http://stackoverflow.com/comment/85322983
score: 7
type: Comment
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].
type: QuestionComment
comment on: http://stackoverflow.com/q/49158987

http://stackoverflow.com/a/49181257
type: Answer
score: 0
answers question: http://stackoverflow.com/q/49142669
has body: OK, got this working: def dataframe_get(df, index2, default_value=0): index_length = len(df.index.levels) levels = df.index.levels[:-1] + index2 new_index = pandas.MultiIndex.from_product(levels, names=["index1", "index2"]) data = df.reindex(new_index) data.index = data.index.droplevel(index_length - 1) return data.fillna(default_value)

http://stackoverflow.com/comment/85307526
has text: changed the version, It starts running. which is rectified and the code is running now. However, the output is not like as expected. I have sent you the out coming.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/49147237
score: 0

http://stackoverflow.com/a/49152987
downvote count: 1
has body: Code: L3 = [dict(a.items() + b.items()) for a,b in zip(L1,L2)]
answers question: http://stackoverflow.com/q/49151289
type: Answer
score: -1
upvote count: 0

http://stackoverflow.com/a/49217030
score: 4
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/49217006
has body: You really shouldn't check for types in that manner The reason you code does not work is because: &gt;&gt;&gt; type(type(str)) &lt;class 'type'&gt; &gt;&gt;&gt; type(str) &lt;class 'type'&gt; As you can see the printed representation of type(str) looks like a string you could compare against but the expression type(self.radius) == "&lt;class 'str'&gt;": is comparing a type on the left hand side with a str on the right hand side which will never evaluate to true. The way to check if something is a particular type is to use isinstance as follows: class RadiusInputError(Exception): pass class Circle: def __init__(self,radius): self.radius = radius if isinstance(self.radius, str): raise RadiusInputError try: a = Circle('Hello') except RadiusInputError: print("'Hello' is not a number.") This works as expected, the rest of your code is fine, just change the type check.
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49217006
type: AcceptedAnswer

http://stackoverflow.com/a/68115815
upvote count: 3
downvote count: 0
answers question: http://stackoverflow.com/q/49232866
has body: To delete only the last character in an entry widget You can use the following code entryname.delete(len(entryname.get())-1,END)
type: Answer
score: 3

android-studio
tags question: http://stackoverflow.com/q/49263681
type: Tag
tag name: android-studio

connection
tag name: connection
type: Tag
tags question: http://stackoverflow.com/q/49126664

http://stackoverflow.com/a/49198331
accepted answer of: http://stackoverflow.com/q/49196758
type: Answer
upvote count: 1
has body: What you want to do is sum a function func over a triangular k * k matrix. Here is the way to do it with your for loops which I slightly modified to fit our abstraction. k = 3 summation = 0.0 for i in range(k + 1): # Loop from 0 to k for j in range(i + 1): # Loop from 0 to i summation += func(i, j) # Sum the value You can vectorize your summation by abstracting the matrix with itertools.product instead of loops. from itertools import product summation = sum(func(i, j) for i, j in product(range(k + 1), repeat=2) if j &lt;= i) The function product returns an iterator, which is memory efficient, especially if you need k to be big.
score: 1
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/49196758

http://stackoverflow.com/comment/85515206
type: Comment
has text: I asked for migration to CS like you suggested @yarwest. Also, I edited my original post. I think it is a lot more specific now.
type: QuestionComment
comment on: http://stackoverflow.com/q/49238522
score: 1

http://stackoverflow.com/comment/85467473
has text: I think you need to show the code under test, as well as the rest of the test case.
score: 3
type: Comment
comment on: http://stackoverflow.com/q/49231824
type: QuestionComment

http://stackoverflow.com/a/49142267
type: Answer
has body: You can install these packages in a non-global location (generally in ~/.local/lib/python&lt;x.y&gt;) using the --user flag, e.g.: pip install --user sqlalchemy coloredlogs That way you don't have to worry about changing how imports work, and you're still compliant with your sysadmins policies.
has comment: http://stackoverflow.com/comment/85290104
has comment: http://stackoverflow.com/comment/85332247
upvote count: 1
answers question: http://stackoverflow.com/q/49142187
downvote count: 1
has comment: http://stackoverflow.com/comment/85290126
score: 0

http://stackoverflow.com/comment/85433823
type: QuestionComment
comment on: http://stackoverflow.com/q/49214709
has text: First of all, that class declaration and instantiation aren't okay. Secondly, why would you want to dynamically name variables? If you're just looking for a way to name the instance of the class then you can add a name attribute.
score: 1
type: Comment

http://stackoverflow.com/comment/85499546
comment on: http://stackoverflow.com/q/49247827
score: 1
type: Comment
type: QuestionComment
has text: There can be many reasons, IMHO you'll have to give a lot more info about your app and what you're doing to get some useful answers...

http://stackoverflow.com/q/49261328
tagged with: python
has comment: http://stackoverflow.com/comment/85526766
has body: So I am a novice programmer who has just managed to build up his first web scraper with a lot of help from internet tutorials. The code works perfectly (sorry about the lack of comments) but it prints out everything I need onto the command window. Now I have been using the | tee example.txt function to log my results in a simple text file, but when I transfer this code to a new environment, that option is no available to me. Getting to the point, at the end of the code I have it writing a text file to correct this but fileout.write(i.text) only grabs the last line of the data, is there a way to save all of the data gathered to a text file without having to alter the code? There probably is, and is really simple but as I said I am relatively new to this, and any advice would be greatly appreciated. The full output of data from the web scraper is located below the code. from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import NoSuchElementException driver = webdriver.Chrome() try: driver.get("http://www.caiso.com/TodaysOutlook/Pages/supply.aspx") # load the page WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.highcharts-legend-item.highcharts-pie-series.highcharts-color-0'))) # wait till relevant elements are on the page except TimeoutException: pass finally: try: stat_elements = driver.find_elements_by_css_selector('.highcharts-legend-item.highcharts-pie-series.highcharts-color-0') for el in stat_elements: for i in el.find_elements_by_tag_name('span'): print (i.text) except NoSuchElementException: print ("No Such Element Found") try: driver.get("http://smartgriddashboard.eirgrid.com/#all/generation") # load the page WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.key-s…
type: AnsweredQuestion
answer count: 2
has answer: http://stackoverflow.com/a/49263113
downvote count: 0
score: 1
upvote count: 1
has title: Write Web Scraping Results to a .txt file
tagged with: selenium
tagged with: web-scraping
possible better answer: http://stackoverflow.com/a/49261595
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/49261595
accepted answer: http://stackoverflow.com/a/49263113

http://stackoverflow.com/comment/91757264
has text: `PIL` is deprecated since a long time ago and has been replaced by `Pillow`. So if you're using old code, you need to look up what has been replaced and what other modifications are required.
comment on: http://stackoverflow.com/q/49247310
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85293072
type: Comment
has text: In VS code relative path works. The code runner runs the file from the directory you are in.
type: QuestionComment
comment on: http://stackoverflow.com/q/49143852
score: 0

http://stackoverflow.com/comment/85519071
comment on: http://stackoverflow.com/q/49241883
has text: The "inconsistent type" of the column is handled by Pandas by giving the column a common `object` dtype. It's not necessarily a problem -- for example, `pd.DataFrame([None, 1.23], dtype='object').astype(float)` raises no error. A cell containing a sequence, however, would raise an error: `pd.DataFrame([None, [1.23, 3.14]]).astype(float)`.
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49215458
has body: You can use a custom key with min. lst = [(0,5), (5,0), (2,2)] res = min(lst, key=lambda x: sum(x)) # (2, 2) To understand how min(lst) works in general, see How does the min/max function on a nested list work? If you wish to retrieve element with minimum sum sorted by first element, you can specify a tuple key: lst2 = [(0,5), (5,0), (2,2), (1,3)] res = min(lst2, key=lambda x: (sum(x), x[0])) # (1, 3) Without using the tuple key, the result above would be (2,2).
upvote count: 2
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/85435535
score: 2
answers question: http://stackoverflow.com/q/49215434

http://stackoverflow.com/comment/85291499
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/49142821
has text: @abarnert I'm highly skeptical of this approach. It sounds like the OP wants prototype based inheritance, but Python has class-based inheritance. So, likely, it is best to implement this another way.
type: Comment

http://stackoverflow.com/comment/85468155
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49231635
type: Comment
has text: Hey Frank, that's really helpful. I edited my code to add wait to avoid exception. But my code is still throwing the same error. Not sure if I'm doing it right.

http://stackoverflow.com/q/49254839
type: Question
has answer: http://stackoverflow.com/a/49255719
has comment: http://stackoverflow.com/comment/85609761
has answer: http://stackoverflow.com/a/49300197
has answer: http://stackoverflow.com/a/49300458
has comment: http://stackoverflow.com/comment/85609669
tagged with: django-admin
has title: Django save previous object from models
has comment: http://stackoverflow.com/comment/85647374
downvote count: 0
has body: In a Django admin site, I have this class. I want to save a previous version of a object (Servers) which is a manytomany field to find changes on the object. With normal CharField this work, but for manytomany fields I got this error: "&lt;SourceDestinationGroup: asdas&gt;" needs to have a value for field "id" before this many-to-many relationship can be used. here is my objectclass class SourceDestinationGroup(models.Model): STATE_CHOICES = ( ('C', 'in Change'), ('F', 'Finished') ) ServerGroupName = models.CharField(max_length=256) Description = models.CharField(max_length=256,blank=True) Servers = models.ManyToManyField(Server) Status = models.CharField(max_length=1, choices=STATE_CHOICES, default='C') def __init__(self, *args, **kw): super(SourceDestinationGroup, self).__init__(*args, **kw) self._old_Servers = self.Servers def save(self, **kw): if self.Servers != self._old_Servers: self.Status = 'C' self._old_Servers = self.Servers super(SourceDestinationGroup, self).save(**kw) def __str__(self): return self.ServerGroupName
tagged with: django
score: 11
possible better answer: http://stackoverflow.com/a/49300197
has comment: http://stackoverflow.com/comment/85642266
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49323125
has answer: http://stackoverflow.com/a/49323125
has comment: http://stackoverflow.com/comment/85601669
tagged with: django-models
tagged with: python
answer count: 4
favorite count: 0
upvote count: 11

http://stackoverflow.com/comment/85554209
score: 0
comment on: http://stackoverflow.com/q/49275868
has text: how wired seems to you changing field type to ArrayField containing JSONField? but on the other hand read this https://stackoverflow.com/a/41134445/953553
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/85305699
score: 1
has text: A better way would be to create an assign op once (before starting a session) and then call it as many times as needed. This means using `GRADIENT` instead of `loss_grad`. By the way, variables support `assign_sub` method.
comment on: http://stackoverflow.com/a/49149730
type: Comment
type: AnswerComment

http://stackoverflow.com/q/49132537
tagged with: python
has body: I have a data like this id name sub marks 1 a m 52 1 a s 69 1 a p 63 2 b m 36 2 b s 52 2 b p 56 3 c m 85 3 c s 62 3 c p 56 And I want output table which contain columns such as id, name and new column result(using criteria if marks in all subject is greater than 40 then this student is pass) id name result 1 a pass 2 b fail 3 c pass I would like to do this in python.
has title: extract rows with conditions and with new created column in python
linked to: http://stackoverflow.com/q/49133313
score: 0
has answer: http://stackoverflow.com/a/49132838
answer count: 3
has answer: http://stackoverflow.com/a/49132655
tagged with: pandas
has comment: http://stackoverflow.com/comment/85269784
type: Question
has answer: http://stackoverflow.com/a/49132645
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85269764

http://stackoverflow.com/q/49215207
has answer: http://stackoverflow.com/a/49215300
accepted answer: http://stackoverflow.com/a/49215300
downvote count: 0
upvote count: 1
score: 1
answer count: 1
tagged with: jinja2
favorite count: 0
type: Question
has body: I want to loop through the images stored in a serial number in my static/images folder. My code is as below: {% for x in range(5)%} &lt;img src="{{url_for('static', filename='images/{{i}}.jpg')}}" alt="Image"&gt; {% endfor%} but the html page is rendering it as : &lt;img src="/static/images/%7B%7Bi%7D%7D.jpg" alt="Image"&gt; Any idea on how to fix this?
tagged with: python
tagged with: flask
has title: render i value in a for loop, in flask
type: AnsweredQuestion

http://stackoverflow.com/q/49252844
tagged with: python
linked to: http://stackoverflow.com/q/17466561
has comment: http://stackoverflow.com/comment/131012556
has comment: http://stackoverflow.com/comment/85509251
has comment: http://stackoverflow.com/comment/85594468
has comment: http://stackoverflow.com/comment/85518848
score: 0
tagged with: oop
answer count: 0
has comment: http://stackoverflow.com/comment/85511423
has body: I'm currently writing a tiny windowed app using python and tkinter. I have very little experience with tkinter and I asked myself whether it would be best to: make my window a class inheriting from tkinter.Tk initialise all objects and variables do all the processes in its __init__ method as if it was a main likewise: class Main_Frame(tkinter.Tk): def __init__(self): super().__init__() self.grid = Grid(60, 40) can_width, can_height = self.canvas_dim() self.can = tk.Canvas(self, width = can_width, height = can_height) self.can.bind('&lt;Button-1&gt;', self.color_1) self.can.pack() Also, all the functions would be translated to become methods of that class. Or should I just instantiate the Tk class and put all treatments, variables and instances in the main? If you need a more detailed look on the code here are the two versions of the code: gist
has title: Python: proper usage when coding an oop, windowed app
tagged with: window
type: Question
tagged with: tkinter
has comment: http://stackoverflow.com/comment/85574708
type: UnansweredQuestion

http://stackoverflow.com/a/49161526
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/49161219
answers question: http://stackoverflow.com/q/49161219
has comment: http://stackoverflow.com/comment/85331658
type: Answer
score: 2
has body: Perhaps it goes without saying, but to spatially join two datasets they need to be in the same coordinate system. Latitude/longitude are coordinates in some geographic coordinate system (and there is more than one, so make sure you know which!). Shapefiles can include coordinates in a variety of coordinate systems. Typically there is a .prj file that is distributed with the shapefile that describes the coordinate system information. Looking at your data, I'd guess that it's in eastings and northings, measured in meters, in some projected coordinate system. So before you can spatially join with data in a geographic coordinate system you will first need to unproject the data (go from a projected or planar coordinate system to a spheroidal one), and then possibly perform a datum shift (adjust for differences between different geographic coordinate systems). I don't know about geopandas or shapely, but I know the proj4 library has good Python bindings and can perform these operations. But either way you'll need the data in the .prj file.
upvote count: 2

http://stackoverflow.com/a/49228028
has comment: http://stackoverflow.com/comment/85460068
has comment: http://stackoverflow.com/comment/85459596
answers question: http://stackoverflow.com/q/49227963
score: 0
has comment: http://stackoverflow.com/comment/85459539
type: Answer
has comment: http://stackoverflow.com/comment/85459942
has body: First of all, you have a syntax error: It should be elif x == 6: as = is the assignment operator and == is the comparison operator, and you are trying to compare, not assign. Next, you need to put the for loop inside a function in order to return a value. return can only be used inside a function. Otherwise, it returns a syntax error. So, make a function and insert the for loop inside it like this: def function (y): for x in y: if x in {3,4,6}: return (x) else: return ('not found') Then, you need to call the function on y. Like this: function(y) It is unclear what you mean by "handle all of such returned data at once as list". Anyway, if you mean that you want to store all the returned data in a list, then create an empty list and append each return value of function to the empty list. Like this: def function (y): emptyList = [] for x in y: if x in {3,4,6}: emptyList.append(x) else: emptyList.append("not found") return emptyList If you could provide a more clear question, I'll edit to fit your needs!
has comment: http://stackoverflow.com/comment/85459599
has comment: http://stackoverflow.com/comment/85459537

http://stackoverflow.com/comment/85491946
has text: where do you read that the original list maintained its size? no, `list_1` is just resized to store the reference of the new string.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/49244003
type: QuestionComment

http://stackoverflow.com/q/49271730
upvote count: 10
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/85546411
has title: How To Parse Verbs Using Spacy
tagged with: spacy
answer count: 1
downvote count: 1
tagged with: linguistics
has answer: http://stackoverflow.com/a/49285139
favorite count: 0
score: 9
type: Question
has body: I'm trying to parse verbs in a corpus and list them in dictionaries and count how many times each verb appears as a transitive, intransitive and ditransitive. I was wondering how I could use spacy to parse through the verbs and notate them as transitive, intransitive and ditransitive.
linked to: http://stackoverflow.com/q/5963269
type: UnansweredQuestion

http://stackoverflow.com/comment/85513730
score: 0
has text: I know my answer was late, but do also look at the alternative :).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/49253303

http://stackoverflow.com/comment/85309358
type: Comment
has text: That doesn't work either ... ERROR! 'ansible_become_pass' is not a valid attribute for a Play
type: AnswerComment
score: 2
comment on: http://stackoverflow.com/a/49152446

http://stackoverflow.com/comment/85286436
comment on: http://stackoverflow.com/q/49140017
type: QuestionComment
score: 0
has text: @hpaulj do you mean write out the help string for the command? I can't really do that much better than I have explained in this question because I am not sure how it would work? I geuss I will just procede by parsing '--computer' option arguments using regex matches and look for square brackets and '--component' options, and then combine --computers and --components arguments into one big dictionary which I can then convert to an sql query. -- that is, if I can not figure out a better way to do some of this with argparse itself.
type: Comment

http://stackoverflow.com/comment/85354094
comment on: http://stackoverflow.com/q/49174427
has text: @lkriener done :)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/85399088
has text: @cᴏʟᴅsᴘᴇᴇᴅ Update a method without groupby :-)
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/49196810
type: Comment

http://stackoverflow.com/comment/85407517
type: Comment
type: QuestionComment
has text: Okay. My apologies as I am new to this website.
comment on: http://stackoverflow.com/q/49200885
score: 0

http://stackoverflow.com/comment/85440694
has text: @jxn - In my opinion some 5, maybe 10 cities should be enough.
type: Comment
comment on: http://stackoverflow.com/a/49218379
score: 0
type: AnswerComment

http://stackoverflow.com/comment/85287555
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49132204
has text: I don't have enough knowledge to be sure that this is a bug and not some mistake that I have made myself. I don't use lumpy and have no idea what it is. I.update MacPorts monthly. This is the first time I've ever seen this error. Some port that I use must depends on bumpy which is probably why it is installed. Nothing I use fails to work. The only thing that failed was "port upgrade outdated'.

http://stackoverflow.com/comment/85541383
type: QuestionComment
comment on: http://stackoverflow.com/q/49267376
has text: Roganjosh using csv.reader worked great thank you.
score: 0
type: Comment

http://stackoverflow.com/a/49151241
accepted answer of: http://stackoverflow.com/q/49147739
downvote count: 0
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/49147739
score: 1
type: Answer
has body: The data you're looking for, is not available in the page source. And requests.get(...) gets you only the page source without the elements that are dynamically added through JavaScript. But, you can still get it using requests module. In the Network tab, inside the developer tools, you can see a file named VixDetails.json. A request is being sent to https://www.nseindia.com/live_market/dynaContent/live_watch/VixDetails.json, which returns the data in the form of JSON. You can access it using the built-in .json() function of the requests module. r = requests.get('https://www.nseindia.com/live_market/dynaContent/live_watch/VixDetails.json') data = r.json() vix_price = data['currentVixSnapShot'][0]['CURRENT_PRICE'] print(vix_price) # 15.7000

http://stackoverflow.com/q/49172770
score: -1
favorite count: 0
type: Question
tagged with: numpy
has body: I am trying to replace an array of 0's column by column like this import numpy as np a = np.zeros((2,10)) b = np.linspace(1,10,10) a[1,:] = b which gives the correct output a = [[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]] b = [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.] However, the data I am trying to insert is complex, for some reason this form of indexing removes the imaginary part of the data. For example a = np.zeros((2,10)) b = np.linspace(1,10,10) * 1j #now b is imaginary a[1,:] = b returns the following a = [[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]] b = [0. +1.j 0. +2.j 0. +3.j 0. +4.j 0. +5.j 0. +6.j 0. +7.j 0. +8.j 0. +9.j 0.+10.j] which is obviously incorrect. Is there a way to avoid this and keep the data complex? Thanks
type: UnansweredQuestion
has title: Python - Replacing column by indexing removes imaginary components
tagged with: arrays
answer count: 1
tagged with: python
tagged with: indexing
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/49173375

http://stackoverflow.com/a/49163707
has comment: http://stackoverflow.com/comment/128566539
has comment: http://stackoverflow.com/comment/128566383
has body: You have a writable stream that you're asking boto3 to use as a readable stream which won't work. Write the file, and then simply use bucket.upload_file() afterwards, like so: s3 = boto3.resource('s3') bucket = s3.Bucket('transportation.manifests.parsed') with open('/tmp/output2.csv', 'w') as data: data.write(response.content) key = 'csv/' + key bucket.upload_file('/tmp/output2.csv', key)
answers question: http://stackoverflow.com/q/49163099
type: Answer
upvote count: 4
downvote count: 0
score: 4

http://stackoverflow.com/comment/85427614
type: QuestionComment
has text: On some platforms `python` is always Py2 and if Py3 is installed the command for that is `python3`. If you are only just getting started, definitely target Py3.
comment on: http://stackoverflow.com/q/49211172
score: 0
type: Comment